<?php
require_once __DIR__ . '/../../connect.php';

$driver_id = filterRequest("driver_id");
$points = filterRequest("points"); // Reward points amount
$challenge_id = filterRequest("challenge_id");

if (!$driver_id || !$points || !$challenge_id) {
    jsonError("Missing required parameters");
    exit();
}

try {
    $con->beginTransaction();

    // 1. Get Country and Currency to determine Cash Multiplier
    $stmtKazan = $con->prepare("SELECT country, currency FROM kazan LIMIT 1");
    $stmtKazan->execute();
    $kazanData = $stmtKazan->fetch(PDO::FETCH_ASSOC);
    $country = $kazanData['country'] ?? 'Syria';
    $currency = $kazanData['currency'] ?? 'SYP';

    switch ($currency) {
        case 'SYP':
            $rate = 100.0; // 1 point = 100 SYP (e.g. 50 points = 5,000 SYP)
            break;
        case 'EGP':
            $rate = 1.0;   // 1 point = 1 EGP (e.g. 50 points = 50 EGP)
            break;
        case 'JOD':
        default:
            $rate = 0.05;  // 1 point = 0.05 JOD (e.g. 50 points = 2.5 JOD)
            break;
    }

    $cashAmount = $points * $rate;

    // 2. S2S Wallet credit to Payment Server
    $walletServer = "https://walletintaleq.intaleq.xyz";
    if (strtolower($country) == 'jordan') {
        $walletServer = getenv('WALLET_SERVER_JORDAN') ?: "https://walletintaleq.intaleq.xyz";
    } elseif (strtolower($country) == 'egypt') {
        $walletServer = getenv('WALLET_SERVER_EGYPT') ?: "https://walletintaleq.intaleq.xyz";
    } else {
        $walletServer = getenv('WALLET_SERVER_SYRIA') ?: "https://walletintaleq.intaleq.xyz";
    }

    $paymentID = "CHL_" . time();
    $walletUrl = "$walletServer/v2/main/ride/driverWallet/add_s2s_reward.php";

    $payload = [
        "driverID" => $driver_id,
        "paymentID" => $paymentID,
        "amount" => $cashAmount,
        "paymentMethod" => $challenge_id,
        "points" => $points
    ];

    $ch = curl_init($walletUrl);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query($payload),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 15,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/x-www-form-urlencoded',
            'X-S2S-Api-Key: ' . getenv('S2S_SHARED_KEY')
        ]
    ]);

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

    $s2sSuccess = false;
    $s2sMessage = "";
    if (!$curlErr && $httpCode === 200) {
        $resDecoded = json_decode($response, true);
        if ($resDecoded && isset($resDecoded['status'])) {
            if ($resDecoded['status'] === 'success') {
                $s2sSuccess = true;
            } else {
                $s2sMessage = $resDecoded['message'] ?? "Unknown S2S failure";
            }
        }
    }

    if (!$s2sSuccess) {
        $errMsg = $s2sMessage ?: ($curlErr ?: "HTTP $httpCode - Response: $response");
        throw new Exception($errMsg);
    }

    $con->commit();
    jsonSuccess("Reward claimed successfully as " . $cashAmount . " " . $currency);

} catch (Exception $e) {
    if ($con->inTransaction()) {
        $con->rollBack();
    }
    error_log("claimChallengeReward Error: " . $e->getMessage());
    jsonError("Failed to claim reward: " . $e->getMessage());
}
?>
