<?php
// --- backend/ride/invitor/claim.php ---
include "../../connect.php";
include "../../functions.php"; // Assuming a functions file exists for helper methods

header('Content-Type: application/json');

try {
    $inviteId = filterRequest("invite_id");
    $driverId = filterRequest("driver_id");
    $passengerId = filterRequest("passenger_id");
    $countryCode = filterRequest("country_code"); // Expected: Jordan, Syria, Egypt
    
    if (empty($inviteId)) {
        echo json_encode(["status" => "failure", "message" => "Invite ID required."]);
        exit;
    }

    $walletServer = "https://walletintaleq.intaleq.xyz"; // Default
    if (strtolower($countryCode) == 'jordan') {
        $rewardAmount = 5;
        $currency = "JOD";
        $walletServer = $_ENV['WALLET_SERVER_JORDAN'] ?? "https://walletintaleq.intaleq.xyz";
    } elseif (strtolower($countryCode) == 'egypt') {
        $rewardAmount = 500;
        $currency = "EGP";
        $walletServer = $_ENV['WALLET_SERVER_EGYPT'] ?? "https://walletintaleq.intaleq.xyz";
    } else {
        $rewardAmount = 500; // Default Syria
        $currency = "SYP";
        $walletServer = $_ENV['WALLET_SERVER_SYRIA'] ?? "https://walletintaleq.intaleq.xyz";
    }

    $walletUrl = "$walletServer/v2/main/ride/payment/add.php";

    $con->beginTransaction();

    if (!empty($driverId)) {
        // Driver Invitation Reward Logic
        $stmt = $con->prepare("SELECT * FROM invites WHERE id = :invite_id AND driverId = :driver_id AND isGiftToken = 0 FOR UPDATE");
        $stmt->execute([':invite_id' => $inviteId, ':driver_id' => $driverId]);
        $invitation = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($invitation) {
            $upd = $con->prepare("UPDATE invites SET isGiftToken = 1 WHERE id = :invite_id");
            $upd->execute([':invite_id' => $inviteId]);

            // Reward for current driver
            addWalletBalance($walletUrl, $driverId, "driver", $rewardAmount);
            // Reward for inviter
            addWalletBalance($walletUrl, $invitation['driverId'], "driver", $rewardAmount);

            $con->commit();
            echo json_encode(["status" => "success", "message" => "Reward of $rewardAmount $currency claimed successfully."]);
        } else {
            $con->rollBack();
            echo json_encode(["status" => "failure", "message" => "Invitation not valid or already claimed."]);
        }

    } elseif (!empty($passengerId)) {
        // Passenger Invitation Reward Logic
        $stmt = $con->prepare("SELECT * FROM invitesToPassengers WHERE id = :invite_id AND passengerID = :passenger_id AND isGiftToken = 0 FOR UPDATE");
        $stmt->execute([':invite_id' => $inviteId, ':passenger_id' => $passengerId]);
        $invitation = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($invitation) {
            $upd = $con->prepare("UPDATE invitesToPassengers SET isGiftToken = 1 WHERE id = :invite_id");
            $upd->execute([':invite_id' => $inviteId]);

            // Call Wallet Server
            addWalletBalance($walletUrl, $passengerId, "passenger", $rewardAmount);

            $con->commit();
            echo json_encode(["status" => "success", "message" => "Reward of $rewardAmount $currency claimed successfully."]);
        } else {
            $con->rollBack();
            echo json_encode(["status" => "failure", "message" => "Invitation not valid or already claimed."]);
        }

    } else {
        echo json_encode(["status" => "failure", "message" => "User ID required."]);
    }

} catch (Exception $e) {
    if ($con && $con->inTransaction()) { $con->rollBack(); }
    error_log("Error in claim.php: " . $e->getMessage());
    echo json_encode(["status" => "error", "message" => "Server error."]);
}

function addWalletBalance($url, $userId, $userType, $amount) {
    $data = [
        "user_id" => $userId,
        "user_type" => $userType,
        "amount" => $amount,
        "action" => "add",
        "reason" => "Invitation Reward"
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}
?>
