<?php  // syriatel_token_handler
function getSyriatelToken(): ?string {
    // اضبط البيئة: prod أو stage (افتراضي prod)
    $env = getenv("SYRIATEL_ENV") ?: "prod";

    // Base URLs من Postman
    $baseStage = "https://merchants.syriatel.sy:1443/ePayment_external_Json_test/rs/ePaymentExternalModule";
    $baseProd  = "https://merchants.syriatel.sy:1443/ePayment_external_Json/rs/ePaymentExternalModule";

    $baseUrl = ($env === "stage") ? $baseStage : $baseProd;
    $url     = $baseUrl . "/getToken";

    // ⚠️ لا تضع قيم افتراضية حساسة Hardcoded
    $username = getenv("SYRIATEL_USERNAME"); 
    $password = getenv("SYRIATEL_PASSWORD");

    if (!$username || !$password) {
        error_log("[GetSyriatelToken] Missing credentials in ENV");
        printFailure("Payment provider credentials are missing.");
        return null;
    }

    error_log("[GetSyriatelToken] Env={$env} | URL={$url} | user={$username}");

    $payload = [
        "username" => $username,
        "password" => $password
    ];

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => [
            "Content-Type: application/json",
            "User-Agent: Mozilla/5.0",
        ],
        CURLOPT_POSTFIELDS     => json_encode($payload, JSON_UNESCAPED_UNICODE),
        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);

    if ($errno) {
        error_log("[GetSyriatelToken] cURL error {$errno}: {$errstr}");
        printFailure("Could not connect to the payment provider.", $errno);
        return null;
    }

    if ($httpCode !== 200 || !$response) {
        error_log("[GetSyriatelToken] HTTP {$httpCode} | Empty/invalid response");
        printFailure("Could not authenticate with the payment provider.");
        return null;
    }

    $data = json_decode($response, true);
    $token = $data["token"] ?? null;

    if (!$token) {
        error_log("[GetSyriatelToken] Token not found in response: " . substr($response, 0, 300));
        printFailure("Could not authenticate with the payment provider.");
        return null;
    }

    error_log("[GetSyriatelToken] Token received successfully");
    return $token;
}