<?php
function write_log($message) {
    $logFile = 'api.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');
// === استقبال JSON من العميل ===
$json = file_get_contents('php://input');
$input = json_decode($json, true);
// حفظ الطلب في اللوج
write_log("Received request webengage: $json");
// === قراءة الهيدر ===
$headers = getallheaders();
write_log("Received request header webengage: " . ($headers['Authorization'] ?? 'NO TOKEN FOUND'));
if (!isset($headers['Authorization']) || empty($headers['Authorization'])) {
    http_response_code(401);
    echo json_encode(['status'=>'failed','statusCode'=>401,'error'=>'Invalid token format']);
    write_log("Token decode failed (missing)");
    exit;
}
$authHeader = $headers['Authorization'];
$token = trim(str_replace("Bearer", "", $authHeader));
$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 (base64)");
    exit;
}
// ========================
// تنزيل الصورة + Base64
// ========================
function downloadAttachment($url)
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0");
    $fileData = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    if ($fileData === false || $http_code != 200) {
        write_log("Failed to download file: $url | HTTP: $http_code | Error: $error");
        return null;
    }
    // استخراج اسم الملف
    $fileName = basename(parse_url($url, PHP_URL_PATH));
    $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
    $mime = [
        "jpg" => "image/jpeg",
        "jpeg" => "image/jpeg",
        "png" => "image/png",
        "gif" => "image/gif",
        "pdf" => "application/pdf"
    ];
    $contentType = $mime[$ext] ?? "application/octet-stream";
    return [
        "FileName" => $fileName,
        "ContentType" => $contentType,
        "Base64Data" => base64_encode($fileData)
    ];
}
// رابط الصورة القادم من العميل
$imageUrl = $input["atchements"] ?? null;
$attachment = null;
if ($imageUrl && $imageUrl !== "emptyConcat") {
    $attachment = downloadAttachment($imageUrl);
}
// ============================
// تجهيز البوديلود للـ KACST
// ============================
$description = $input["Description"] ?? "";
$cleanedText = preg_replace('/[^a-zA-Zء-ي0-9\s]/u', '', $description);
$payloadArr = [
    "Title" => $input["Title"] ?? "",
    "Description" => $cleanedText ?? "",
    "MobileNumber" => $input["MobileNumber"] ?? "",
];
if ($attachment) {
    $payloadArr["Attachments"] = [ $attachment ];
}
// تحويله JSON
$payload = json_encode($payloadArr, JSON_UNESCAPED_SLASHES);
write_log("Generated final payload: " . substr($payload, 0, 500));
// ============================
// توقيع الطلب
// ============================
$timestamp = time();
$message = "$timestamp.$payload";
$signature = hash_hmac('sha256', $message, $key);
write_log("Generated signature: $signature");
// ============================
// إرسال الطلب لـ KACST
// ============================
$curl = curl_init();
curl_setopt_array($curl, [
  CURLOPT_URL => 'https://empappsapi.kacst.gov.sa/api/ticket/create',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_POST => true,
  CURLOPT_CONNECTTIMEOUT => 30, // وقت الاتصال
  CURLOPT_TIMEOUT => 30, // وقت التنفيذ الكامل
  CURLOPT_POSTFIELDS => $payload,
  CURLOPT_HTTPHEADER => [
      'Content-Type: application/json',
      "X-KACST-Timestamp: $timestamp",
      "X-KACST-Signature: $signature"
  ]
]);
$response = curl_exec($curl);
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$error = curl_error($curl);
curl_close($curl);
write_log("API Response (HTTP $http_code): " . substr($response, 0, 500));
// === معالجة الأخطاء ===
if ($error) {
    http_response_code(502);
    echo json_encode([
        'status'=>'failed',
        'statusCode'=>502,
        'error'=>'Gateway error',
        'details'=>$error
    ]);
    write_log("cURL Error: $error");
} else {
   $data = json_decode($response, true);
    $data['emptyResult'] = "data";
    // إذا data فارغة أو null
    if (!isset($data['data']) || empty($data['data'])) {
        $data['emptyResult'] = 'No data';
        $data['success'] = false;
    }
    http_response_code($http_code);
    $dd = json_encode($data, JSON_PRETTY_PRINT);
    write_log("return from data: $dd");
    echo json_encode($data, JSON_PRETTY_PRINT);
}
?>