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

// Logic: 
// Driver -> Driver: 50 trips = 500 SYP (example)
// Driver -> Passenger: 10 trips = 30 SYP per trip. This could be progressive, but for manual claim we assume completed
$amountSyp = 0;

if ($referral['invited_user_type'] == 'driver') {
    if ($referral['trip_count'] >= 50) {
        $amountSyp = 500;
    } else {
        jsonError("Requirement not met (50 trips required)");
    }
} else if ($referral['invited_user_type'] == 'passenger') {
    if ($referral['trip_count'] >= 1) {
        // Here, user gets 30 SYP per trip, max 10. Let's assume claim all at once up to 10.
        $tripsToClaim = min($referral['trip_count'], 10);
        $amountSyp = $tripsToClaim * 30;
    } else {
        jsonError("Requirement not met (At least 1 trip required)");
    }
}

if ($amountSyp <= 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
        $walletStmt = $con->prepare("UPDATE driver SET wallet = wallet + ? WHERE id = ?"); 
        $walletStmt->execute([$amountSyp, $user_id]);
    } 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, $amountSyp]);
    }

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

} catch (PDOException $e) {
    $con->rollBack();
    jsonError("Database error: " . $e->getMessage());
}
?>
