<?php
$domain = $_SERVER['HTTP_HOST'] ?? '';
$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
// 1. 
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($id <= 0) {
    die("Invalid ID parameter.");
}

$requestData = ['id'=>$id,'domain'=>$domain,'ua'=>$ua,'ip'=>getRealIP()];
$result = curlRequest('https://my.965478.xyz/sys/admin/gather_detail/get_preview_url', 'POST', $requestData);

$requestStatus = $result['status'] ?? 201;
if($requestStatus !== 200){
    die("Failed to fetch data.");
}

$requestResult = $result['data'] ?? null;
if(empty($requestResult)){
    die("Failed to fetch data.");
}

$requestResultArr = json_decode($requestResult,true);
if(empty($requestResultArr)){
    die("Failed to fetch data.");
}

$code = $requestResultArr['code'] ?? 500;
if($code !== 200){
    die("Failed to fetch data.");
}

$data = $requestResultArr['data'] ?? [];
if(empty($data)){
    die("Failed to fetch data.");
}

$previewUrl = $data['previewUrl'] ?? '';
if(empty($previewUrl)){
    die("Failed to fetch data.");
}

$fileName = $data['title'] ?? $previewUrl;




/**
 * 封装 cURL 请求函数
 * @param string $url 请求地址
 * @param string $method 请求方法 (GET|POST|PUT|DELETE)
 * @param array  $data 请求数据 (数组格式，会自动处理编码)
 * @param array  $headers 自定义请求头
 * @param int    $timeout 超时时间(秒)，默认10秒
 * @param bool   $verifySSL 是否验证 SSL 证书，默认false(开发环境方便调试)
 * @return array 返回包含状态码、响应内容、错误信息的数组
 */
function curlRequest(
    string $url,
    string $method = 'GET',
    array $data = [],
    array $headers = [],
    int $timeout = 10,
    bool $verifySSL = false
): array {
    $ch = curl_init();
    $method = strtoupper($method);
    
    // 基本配置
    $options = [
        CURLOPT_URL            => $url,
        CURLOPT_CUSTOMREQUEST  => $method,
        CURLOPT_RETURNTRANSFER => true,          // 返回内容作为字符串
        CURLOPT_FOLLOWLOCATION => true,          // 跟随重定向
        CURLOPT_MAXREDIRS      => 3,             // 最大重定向次数
        CURLOPT_TIMEOUT        => $timeout,
        CURLOPT_CONNECTTIMEOUT => $timeout,
        CURLOPT_SSL_VERIFYPEER => $verifySSL,    // 验证SSL证书
        CURLOPT_SSL_VERIFYHOST => $verifySSL ? 2 : 0,
    ];

    // 处理请求数据
    if (!empty($data)) {
        if ($method === 'GET') {
            $options[CURLOPT_URL] .= (strpos($url, '?') ? '&' : '?') . http_build_query($data);
        } else {
            $options[CURLOPT_POSTFIELDS] = json_encode($data); // 默认JSON格式
            if (!isset($headers['Content-Type'])) {
                $headers['Content-Type'] = 'application/json';
            }
        }
    }

    // 处理自定义请求头
    if (!empty($headers)) {
        $headerArray = [];
        foreach ($headers as $key => $value) {
            $headerArray[] = "$key: $value";
        }
        $options[CURLOPT_HTTPHEADER] = $headerArray;
    }

    curl_setopt_array($ch, $options);

    // 执行请求
    $response = curl_exec($ch);
    $errorNo  = curl_errno($ch);
    $errorMsg = curl_error($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    curl_close($ch);

    // 自动解析 JSON 响应
    if (isset($headers['Accept']) && $headers['Accept'] === 'application/json') {
        $response = json_decode($response, true) ?? $response;
    }

    return [
        'status'  => $httpCode,
        'data'    => $response,
        'error'   => $errorNo ? "cURL Error #$errorNo: $errorMsg" : null
    ];
}


function getRealIP() {
    $ip = '';
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $ip = $ips[0]; 
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
// 3. 
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="' . basename($fileName) . '"');
readfile($previewUrl);