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

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

/** دوال الطباعة (لو موجودة أصلاً في jwtconnect.php تجاهل هذه) */
if (!function_exists('printSuccess')) {
    function printSuccess($data = null, $message = "success") {
        echo json_encode(["status"=>"success","message"=>$message,"data"=>$data], JSON_UNESCAPED_UNICODE); exit;
    }
}
if (!function_exists('printFailure')) {
    function printFailure($message = "failure", $code = null) {
        $resp = ["status"=>"failure","message"=>$message]; if ($code!==null) $resp["code"]=$code;
        echo json_encode($resp, JSON_UNESCAPED_UNICODE); exit;
    }
}

/** مولّد مرجع الطلب (TransactionID) */
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";
}

// --- Input Parameters ---
$amount    = filterRequest('amount');
$driverId  = filterRequest('driverId');
$phone     = filterRequest('phone'); // customerMSISDN
$lang      = filterRequest('lang') ?? 'ar';

error_log("Syriatel Start: Request received for driver {$driverId} with amount {$amount}");

if (!$amount || !$driverId || !$phone) {
    printFailure("Missing required parameters.");
}

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

if ($baseUrl === '' || $merchantMSISDN === '') {
    error_log("Syriatel Start: Missing SYRIATEL_API_BASE_URL or SYRIATEL_MERCHANT_MSISDN");
    printFailure("Server configuration error.");
}

// --- Logic ---
try {
    // 1) Token
    $token = getSyriatelToken();
    error_log("Syriatel Start: token=" . ($token ? substr($token,0,8).'...' : 'NULL'));

    if (!$token) {
        printFailure("Could not authenticate with the payment provider.");
    }

    // 2) Transaction ID + log DB
    $transactionID = generate_order_ref();
    $stmt = $con->prepare(
        "INSERT INTO `paymentsLogSyriaDriver` (user_id, amount, status, order_ref, payment_method, created_at)
         VALUES (:user_id, :amount, 0, :order_ref, 'syriatel', NOW())"
    );
    $stmt->execute([
        ':user_id'   => $driverId,
        ':amount'    => $amount,
        ':order_ref' => $transactionID
    ]);
    error_log("Syriatel Start: Logged transaction {$transactionID} for driver {$driverId}");

    // 3) Payment Request → Syriatel
    $body = [
        "customerMSISDN" => $phone,            // مثال: 09xxxxxxxx (حسب وثيقتهم)
        "merchantMSISDN" => $merchantMSISDN,   // من env
        "amount"         => $amount,
        "transactionID"  => $transactionID,
        "token"          => $token
    ];
error_log("Syriatel Start: customerMSISDN {$phone} merchantMSISDN {$merchantMSISDN}");
    $url = "{$baseUrl}/ePaymentExternalModule/paymentRequest";
    $ch  = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode($body, JSON_UNESCAPED_UNICODE),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => [
            "Content-Type: application/json",
            "User-Agent: Mozilla/5.0",
            "Accept: application/json"
        ],
        CURLOPT_CONNECTTIMEOUT => 8,
        CURLOPT_TIMEOUT        => 40,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
    ]);
    $response = curl_exec($ch);
    $errno    = curl_errno($ch);
    $errstr   = curl_error($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    error_log("Syriatel Start: paymentRequest HTTP {$httpCode} errno={$errno} resp=" . substr((string)$response,0,300));

    if ($errno) {
        printFailure("Payment gateway communication error.", $errno);
    }
    if ($httpCode !== 200) {
        printFailure("Payment gateway communication error (HTTP {$httpCode}).");
    }

    $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.");
}