<?php 
function write_log($message) {
    $logFile = 'api22.log'; // Name of the log file
    $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 = file_get_contents('php://input');
if ($json === false || json_last_error() !== JSON_ERROR_NONE) {
    http_response_code(400);
    echo json_encode([
        'status' => 'failed',
        'statusCode' => 400,
        'error' => 'Invalid JSON'
    ]);
    exit;
}
write_log("Received request webengage: " . file_get_contents('php://input'));
$headers = getallheaders();
write_log("Received request header webengage: " . $headers['Authorization']);
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");
    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 format'
    ]);
    write_log("Token decode failed");
    exit;
}
$jsonFixed = preg_replace(
    '/"MobileNumber"\s*:\s*([0-9]+)/',
    '"MobileNumber":"$1"',
    $json
);

$data = json_decode($jsonFixed, true);
write_log("payload from zeyad: $data");
if ($data === null) {
    http_response_code(400);
    echo json_encode([
        'status' => 'failed',
        'error' => 'Invalid JSON'
    ]);
    exit;
}

if (!isset($data['MobileNumber'])) {
    http_response_code(400);
    echo json_encode([
        'status' => 'failed',
        'error' => 'MobileNumber is required'
    ]);
    exit;
}
$timestamp = time();
$mobileString = (string)$data['MobileNumber'];
$json = json_encode(['MobileNumber' => $mobileString]);
$payload = $json;
write_log("payload from zeyad: $json");
$message = "$timestamp.$payload";
$signature = hash_hmac('sha256', $message, $key);
write_log("Generated signature: $signature");
$curl = curl_init();
curl_setopt_array($curl, [
  CURLOPT_URL => 'https://empappsapi.kacst.gov.sa/api/ticket/view',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS => $payload,
  CURLOPT_HTTPHEADER => [
    'Content-Type: application/json',
    "X-KACST-Timestamp: $timestamp",
    "X-KACST-Signature: $signature"
  ],
]);
$response = curl_exec($curl);
write_log("API Response zeyad: $response");
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
write_log("API Response (HTTP $http_code): " . substr($response, 0, 500));
$error = curl_error($curl);
curl_close($curl);
if ($error) {
    http_response_code(502);
    $errorResponse = [
        'status' => 'failed',
        'statusCode' => 502,
        'error' => 'Gateway error',
        'details' => $error
    ];
    echo json_encode($errorResponse);
    write_log("cURL Error: $error");
} else {
    http_response_code($http_code);
    header('Content-Type: application/json');
        $responseVal = json_decode($response,true);
     if($responseVal['data']!=null){
        $responseVal = json_decode($response,true);
        $responseVal['count'] = count($responseVal['data']);
         foreach ($responseVal['data'] as $index => $item) {

            // conversations
            if (!isset($item['conversations']) || empty($item['conversations'])) {
                $responseVal['data'][$index]['conversations'] = "لا يوجد محادثات";
            }else{
                $output = "";
                foreach ($item['conversations'] as $c) {
                    $output .= "from: " . $c['from'] . "\n";
                    $output .= $c['message'] . "\n"; // أو استخدم $c['message'] لو بدك الرسالة الأصلية
                }
                 $responseVal['data'][$index]['conversations'] = $output;
            }
            // attachments
            if (!isset($item['attachments']) || empty($item['attachments'])) {
                $responseVal['data'][$index]['attachments'] = "لا يوجد مرفقات";
            }else{
                 $responseVal['data'][$index]['attachments'] = $item['attachments'][0]['content_url'];
            }

            // resolution
            if (!isset($item['resolution']) || $item['resolution'] === null || $item['resolution'] === "") {
                $responseVal['data'][$index]['resolution'] = "لا يوجد حل";
            }else{
                $output = "from: " . $item['resolution']['from'] . "\n";
                $output .= $item['resolution']['message'] . "\n"; // أو استخدم $c['message'] لو بدك الرسالة الأصلية
                $responseVal['data'][$index]['resolution'] = $output;
            }
        }
        $responseDataVal = json_encode($responseVal);  
     }
      write_log("taqnyat return: $responseDataVal");
    echo $responseDataVal;
}
?>