<?php
include "../../../jwtconnect.php";
date_default_timezone_set("Asia/Damascus");

// ========== إعدادات MTN ==========
$terminalId = "9001000000060863";
$currencyCode = 760;
$sessionNumber = 0;
$ttl = 15;

// ====== استقبال البيانات من فلاتر ======
$amount = filterRequest("amount");
$passengerId = filterRequest("passengerId");
$phone = filterRequest("phone");

// ✅ Log مبدئي
error_log("🚦 START | passengerId: $passengerId | phone: $phone | amount: $amount");

// تحقق من المدخلات
if (empty($amount) || empty($passengerId) || empty($phone) || $amount <= 0) {
    error_log("❌ Invalid input: amount=$amount, passengerId=$passengerId, phone=$phone");
    printFailure("بيانات الدفع غير كاملة أو غير صالحة.");
    exit;
}

// ====== توليد invoiceNumber و GUID ======
$invoiceNumber = mt_rand(10000000000, 99999999999); 
//$invoiceNumber = "MTN_" . $passengerId . "_" . time();
$guid = uniqid("mtn_");
error_log("🧾 Generated Invoice: $invoiceNumber");
error_log("🧭 Generated GUID: $guid");

// ====== 1. إنشاء الفاتورة ======
$createInvoiceBody = [
    "Amount" => intval($amount * 100),
    "Invoice" => $invoiceNumber,
    "Session" => $sessionNumber,
    "TTL" => $ttl
];
error_log("📦 Create Invoice Body: " . json_encode($createInvoiceBody, JSON_UNESCAPED_UNICODE));
$invoiceResponse = sendMtnApiRequest("pos_web/invoice/create", $terminalId, $createInvoiceBody);
error_log("📥 Create Invoice Response: " . json_encode($invoiceResponse, JSON_UNESCAPED_UNICODE));

if (!$invoiceResponse || isset($invoiceResponse['Errno']) && $invoiceResponse['Errno'] != 0) {
    error_log("❌ Failed to create invoice. Error: " . json_encode($invoiceResponse));
    printFailure("فشل إنشاء الفاتورة عبر MTN.");
    exit;
}

// ====== 2. بدء الدفع ======
$initiateBody = [
    "Invoice" => $invoiceNumber,
    "Phone" => $phone,
    "Guid" => $guid
];
error_log("📤 body initiateBody: $initiateBody");
error_log("📦 Initiate Payment Body: " . json_encode($initiateBody, JSON_UNESCAPED_UNICODE));
$initiateResponse = sendMtnApiRequest("pos_web/payment_phone/initiate", $terminalId, $initiateBody);
error_log("📥 Initiate Response: " . json_encode($initiateResponse, JSON_UNESCAPED_UNICODE));

if (!$initiateResponse || !isset($initiateResponse['OperationNumber'])) {
    error_log("❌ Failed to initiate payment.");
    printFailure($initiateResponse);
    exit;
}

$operationNumber = $initiateResponse['OperationNumber'];

// ====== 3. تسجيل العملية ======
try {
    $stmt = $con->prepare("INSERT INTO `paymentsLogSyriaDriver` 
        (`user_id`, `amount`, `status`, `order_ref`, `payment_method`, `created_at`) 
        VALUES (?, ?, 2, ?, 'mtn', NOW())");
    $stmt->execute([$passengerId, $amount, $invoiceNumber]);
    error_log("✅ DB Log Inserted.");
} catch (PDOException $e) {
    error_log("❌ DB ERROR: " . $e->getMessage());
    printFailure("فشل في تسجيل العملية.");
    exit;
}

// ====== 4. نجاح
error_log("✅ Payment initiation successful.");
printSuccess([
    "invoiceNumber" => $invoiceNumber,
    "operationNumber" => $operationNumber,
    "guid" => $guid
]);


// ====== دالة إرسال الطلب =====================
function sendMtnApiRequest($requestName, $terminalId, $body)
{
    $apiUrl = "https://cashmobile.mtnsyr.com:9000";
    $privateKey = openssl_pkey_get_private(file_get_contents("private_key.pem"));

    // ✅ تحويل الـ body إلى JSON بدون فراغات أو أسطر
    $bodyJson = trim(stripslashes(json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_LINE_TERMINATORS)), '"');
//$bodyJson = json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    // ✅ توليد التوقيع
   // $bodyHash = hash('sha256', $bodyJson, true);
  error_log("📤 body before JSON: $bodyJson");
    openssl_sign($bodyJson, $signature, $privateKey, OPENSSL_ALGO_SHA256);
    $xSignature = base64_encode($signature);
error_log("📤 body xSignature: $xSignature");
    // ✅ رؤوس الطلب
    $headers = [
        "Content-Type: application/json",
        "Accept-Language: en",
        "Request-Name: $requestName",
        "Subject: $terminalId",
        "X-Signature: $xSignature"
    ];

    $ch = curl_init($apiUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $bodyJson);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);

    // ✅ لوق داخلي
    error_log("🔐 Signature for $requestName: $xSignature");
    error_log("📤 Sent JSON: $bodyJson");

    curl_close($ch);
    return json_decode($response, true);
}