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

$referralId = filterRequest("referral_id");
$claimType = filterRequest("claim_type"); // 'wallet' or 'cash'

// Use JWT token variables provided by connect.php
if (!$user_id || $role != 'driver' || !$referralId || !in_array($claimType, ['wallet', 'cash'])) {
    jsonError("Invalid parameters or unauthorized token");
}

// 1. Get the referral info
$stmt = $con->prepare("
    SELECT r.id, r.inviter_code, r.invited_user_id, r.invited_user_type, r.trip_count, r.is_reward_claimed, c.user_id as inviter_id, c.user_type as inviter_type
    FROM unified_referrals r
    JOIN user_referral_codes c ON r.inviter_code = c.referral_code
    WHERE r.id = ? AND c.user_id = ? AND c.user_type = 'driver'
");
$stmt->execute([$referralId, $user_id]);

if ($stmt->rowCount() == 0) {
    jsonError("Referral not found or unauthorized");
}

$referral = $stmt->fetch(PDO::FETCH_ASSOC);

if ($referral['is_reward_claimed'] == 1) {
    jsonError("Reward already claimed");
}

// 2. Get local currency dynamically
$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';

$driverRewardBase = 0;
$passengerRewardPerTrip = 0;

switch ($currency) {
    case 'SYP':
        $driverRewardBase = 50000;
        $passengerRewardPerTrip = 2000;
        break;
    case 'EGP':
        $driverRewardBase = 300;
        $passengerRewardPerTrip = 15;
        break;
    case 'JOD':
    default:
        $driverRewardBase = 10;
        $passengerRewardPerTrip = 0.5;
        break;
}

$rewardAmount = 0;

if ($referral['invited_user_type'] == 'driver') {
    if ($referral['trip_count'] >= 50) {
        $rewardAmount = $driverRewardBase;
    } else {
        jsonError("Requirement not met (50 trips required)");
    }
} else if ($referral['invited_user_type'] == 'passenger') {
    if ($referral['trip_count'] >= 1) {
        $tripsToClaim = min($referral['trip_count'], 10);
        $rewardAmount = $tripsToClaim * $passengerRewardPerTrip;
    } else {
        jsonError("Requirement not met (At least 1 trip required)");
    }
}

if ($rewardAmount <= 0) {
    jsonError("No reward available to claim");
}

try {
    $con->beginTransaction();

    // Mark as claimed
    $updateStmt = $con->prepare("UPDATE unified_referrals SET is_reward_claimed = 1, status = 'claimed' WHERE id = ?");
    $updateStmt->execute([$referralId]);

    if ($claimType == 'wallet') {
        // Add to driver wallet via Payment Server S2S API
        $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 = "REF_" . time();
        $walletUrl = "$walletServer/v2/main/ride/driverWallet/add_s2s_reward.php";

        $payload = [
            "driverID" => $user_id,
            "paymentID" => $paymentID,
            "amount" => $rewardAmount,
            "paymentMethod" => "referral_reward"
        ];

        $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;
        if (!$curlErr && $httpCode === 200) {
            $resDecoded = json_decode($response, true);
            if ($resDecoded && isset($resDecoded['status']) && $resDecoded['status'] === 'success') {
                $s2sSuccess = true;
            }
        }

        if (!$s2sSuccess) {
            throw new Exception("S2S Wallet credit failed: " . ($curlErr ?: "HTTP $httpCode - Response: $response"));
        }

    } else if ($claimType == 'cash') {
        // Request manual cash out
        $cashStmt = $con->prepare("INSERT INTO driver_cash_claims (driver_id, referral_id, amount_syp, status) VALUES (?, ?, ?, 'pending')");
        $cashStmt->execute([$user_id, $referralId, $rewardAmount]);
    }

    $con->commit();
    printSuccess(["message" => "Reward claimed successfully as " . $rewardAmount . " " . $currency]);

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