<?php
// /v1/main/ride/syriatel/passenger/start_payment.php
include "../../../jwtconnect.php";
include_once "./syriatel_token_handler.php";

header('Content-Type: application/json; charset=utf-8');

// --- Input Parameters ---
$amount      = filterRequest('amount');
$passengerId = filterRequest('passengerId'); // بدل driverId
$phone       = filterRequest('phone');       // رقم الراكب (customerMSISDN)
$lang        = filterRequest('lang') ?? 'ar';

error_log("Syriatel Start (Passenger): Request received for passenger {$passengerId} with amount {$amount}");

if (!$amount || !$passengerId || !$phone) {
    printFailure($lang === 'ar' ? "بيانات ناقصة." : "Missing required parameters.");
    exit;
}
function generate_order_ref(): string {
    // مرجع مقروء + فريد: INT-YYYYMMDDHHMMSS-6digits
    $ts = date('YmdHis');
    $rand = str_pad((string)random_int(0, 999999), 6, '0', STR_PAD_LEFT);
    return "INT-$ts-$rand";
}

// --- Environment Variables ---
$baseUrl        = rtrim(getenv('SYRIATEL_API_BASE_URL'), '/');
$merchantMSISDN = getenv('SYRIATEL_MERCHANT_MSISDN');

if (!$baseUrl || !$merchantMSISDN) {
    error_log("Syriatel Start (Passenger): Missing SYRIATEL_API_BASE_URL or SYRIATEL_MERCHANT_MSISDN env variables.");
    printFailure($lang === 'ar' ? "خطأ إعدادات الخادم." : "Server configuration error.");
    exit;
}

try {
    // 1) Get Authentication Token
    $token = getSyriatelToken();
  error_log("Syriatel Start (Passenger):token= .$token");
    if (!$token) {
        printFailure($lang === 'ar' ? "تعذّر المصادقة مع مزوّد الدفع." : "Could not authenticate with the payment provider.");
        exit;
    }

    // 2) Generate transaction ID + log
    $transactionID = generate_order_ref(); // موجود لديك مسبقًا
    // ملاحظة: استخدم جدول منفصل للركاب، أو وحّد الجدول مع حقل user_type. هنا نفترض جدول خاص بالراكب.
    $stmt = $con->prepare(
        "INSERT INTO `paymentsLogSyria`
            (user_id, amount, status, order_ref, payment_method, created_at)
         VALUES
            (:user_id, :amount, 0, :order_ref, 'syriatel', NOW())"
    );
    $stmt->execute([
        ':user_id'   => $passengerId,
        ':amount'    => $amount,
        ':order_ref' => $transactionID
    ]);
    error_log("Syriatel Start (Passenger): Logged transaction {$transactionID} for passenger {$passengerId}");

    // 3) Call Syriatel paymentRequest
    $body = [
        "customerMSISDN" => $phone,            // هاتف الراكب
        "merchantMSISDN" => $merchantMSISDN,   // هاتف التاجر (المحفظة)
        "amount"         => $amount,
        "transactionID"  => $transactionID,
        "token"          => $token
    ];

    $ch = curl_init("{$baseUrl}/ePaymentExternalModule/paymentRequest");
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode($body, JSON_UNESCAPED_UNICODE),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => ["Content-Type: application/json"],
        CURLOPT_TIMEOUT        => 25,
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlErr  = curl_error($ch);
    curl_close($ch);

    if ($curlErr) {
        error_log("Syriatel Start (Passenger): cURL Error - {$curlErr}");
    }

    error_log("Syriatel Start (Passenger): API Response HTTP {$httpCode} - {$response}");

    if ($httpCode !== 200) {
        printFailure($lang === 'ar' ? "خطأ اتصال ببوابة الدفع." : "Payment gateway communication error.");
        exit;
    }

    $responseData = json_decode($response, true);

    // حسب الدوكيومنت: resultCode = 1 يعني OTP انرسل بنجاح
    //errorCode = 0 => Success
if (isset($responseData['errorCode']) && (string)$responseData['errorCode'] === "0") {
    printSuccess([
        'message'       => 'OTP sent successfully.',
        'transactionID' => $transactionID,
    ]);
}
// 2) إذا resultCode = 1 => OTP sent
elseif (isset($responseData['resultCode']) && (int)$responseData['resultCode'] === 1) {
    printSuccess([
        'message'       => 'OTP sent successfully.',
        'transactionID' => $transactionID,
    ]);
}
// 3) أي شيء آخر => فشل
else {
    $errorMessage = $responseData['resultDescription']
        ?? $responseData['errorDesc']
        ?? 'Failed to initiate payment.';
    printFailure($errorMessage);
}

} catch (Throwable $e) {
    error_log("Syriatel Start: Exception - " . $e->getMessage());
    printFailure("An unexpected server error occurred.");
}