<?php
function write_log($message) {
    $logFile = __DIR__ . '/api3.log';
    $timestamp = date('Y-m-d H:i:s');
    $logMessage = "[$timestamp] $message\n";
    file_put_contents($logFile, $logMessage, FILE_APPEND);
}

header('Content-Type: application/json');

// 1. قراءة الـ JSON
$json = file_get_contents('php://input');
if ($json === false) {
    http_response_code(400);
    echo json_encode(['status' => 'failed', 'statusCode' => 400, 'error' => 'Failed to read input']);
    exit;
}

$payload = json_decode($json, true);
if ($payload === null || json_last_error() !== JSON_ERROR_NONE) {
    http_response_code(400);
    echo json_encode(['status' => 'failed', 'statusCode' => 400, 'error' => 'Invalid JSON']);
    exit;
}

write_log("Received payload: $json");

// 2. تحليل الـ payload
if (empty($payload['query_string'])) {
    http_response_code(400);
    echo json_encode(['status' => 'failed', 'statusCode' => 400, 'error' => 'Missing query_string']);
    exit;
}

// ✅ استخراج فقط الـ query string بشكل ديناميكي
$parsed_query = parse_url($payload['query_string'], PHP_URL_QUERY);

if (empty($parsed_query)) {
    http_response_code(400);
    echo json_encode(['status' => 'failed', 'statusCode' => 400, 'error' => 'Invalid query_string format']);
    write_log("Invalid query_string format: " . $payload['query_string']);
    exit;
}

$query_string = '?' . $parsed_query;

write_log("Query string extracted: $query_string");

// 3. التحقق من Authorization
$headers = getallheaders();
$authHeader = $headers['Authorization'] ?? '';

if (!preg_match('/^Bearer\s+(.+)$/i', $authHeader, $matches)) {
    http_response_code(401);
    echo json_encode(['status' => 'failed', 'statusCode' => 401, 'error' => 'Invalid Authorization header']);
    write_log("Auth failed - Invalid Authorization header");
    exit;
}

$token = $matches[1];
$key = base64_decode($token);
if ($key === false) {
    http_response_code(401);
    echo json_encode(['status' => 'failed', 'statusCode' => 401, 'error' => 'Invalid token']);
    write_log("Token decode failed");
    exit;
}

// 4. توليد التوقيع
$timestamp = time();
$message = "$timestamp.$query_string";
$signature = hash_hmac('sha256', $message, $key);
write_log("Generated signature: $signature");

// 5. تجهيز الرابط
$base_url = 'https://empappsapi.kacst.gov.sa/api/ticket/attachment/download';
$full_url = $base_url . $query_string;
write_log("Full URL: $full_url");

// 6. تنفيذ طلب cURL
$original_filename = null;
$content_type = null;

$ch = curl_init($full_url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_TIMEOUT        => 60,
    CURLOPT_SSL_VERIFYPEER => true,
    CURLOPT_HTTPHEADER     => [
        "X-KACST-Timestamp: $timestamp",
        "X-KACST-Signature: $signature"
    ],
    CURLOPT_HEADERFUNCTION => function($curl, $header) use (&$original_filename, &$content_type) {

        $lower = strtolower($header);

        if (strpos($lower, 'content-disposition:') === 0) {
            if (preg_match('/filename="?([^";]+)"?/i', $header, $m)) {
                $original_filename = $m[1];
            }
        }

        if (strpos($lower, 'content-type:') === 0) {
            $content_type = trim(substr($header, 13));
        }

        return strlen($header);
    },
]);

$file_data = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);

write_log("HTTP Code: $http_code | Error: " . ($error ?: 'none') . " | Size: " . strlen((string)$file_data));

// 7. معالجة الأخطاء
if ($error || $http_code !== 200 || !$file_data) {
    http_response_code($error ? 502 : $http_code);
    $errMsg = $error ?: "HTTP $http_code";
    echo json_encode(['status' => 'failed', 'statusCode' => $http_code, 'error' => $errMsg]);
    write_log("Error: $errMsg");
    exit;
}

// 8. استخراج اسم الملف
$original_filename = $original_filename ?: ('file_' . time());
$original_filename = preg_replace('/[^a-zA-Z0-9._-]/', '_', basename($original_filename));

$pathinfo = pathinfo($original_filename);
if (empty($pathinfo['extension']) && !empty($content_type)) {
    $ext_map = [
        'pdf' => '.pdf',
        'word' => '.docx',
        'excel' => '.xlsx',
        'zip' => '.zip',
        'image' => '.jpg'
    ];
    foreach ($ext_map as $key => $ext) {
        if (stripos($content_type, $key) !== false) {
            $original_filename .= $ext;
            break;
        }
    }
}

// 9. حفظ الملف
$download_dir = __DIR__ . '/downloads/';
if (!is_dir($download_dir)) {
    mkdir($download_dir, 0755, true);
}

$unique_filename = uniqid('att_') . '_' . $original_filename;
$file_path = $download_dir . $unique_filename;

if (file_put_contents($file_path, $file_data) === false) {
    http_response_code(500);
    echo json_encode(['status' => 'failed', 'statusCode' => 500, 'error' => 'Failed to save file']);
    write_log("Failed to save file: $file_path");
    exit;
}

write_log("File saved: $file_path");

// 10. توليد الرابط العام
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'];
$script_dir = dirname($_SERVER['SCRIPT_NAME']);

$download_url = rtrim($protocol . '://' . $host . $script_dir, '/') . '/downloads/' . $unique_filename;

$ext = pathinfo($download_url, PATHINFO_EXTENSION);
$type = ($ext === "pdf") ? "file" : "image";

// 11. الإرجاع النهائي
echo json_encode([
    'status' => 'success',
    'statusCode' => 200,
    'download_url' => $download_url,
    'filename' => $original_filename,
    'exe' => $type,
    'size' => strlen($file_data)
]);

write_log("Download URL: $download_url");
exit;
