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

// Use JWT token variables provided by connect.php
if (!$user_id || $role != 'driver') {
    jsonError("Invalid parameters or unauthorized token");
}

// 1. Get the driver's referral code
$stmtCode = $con->prepare("SELECT referral_code FROM user_referral_codes WHERE user_id = ? AND user_type = 'driver'");
$stmtCode->execute([$user_id]);

if ($stmtCode->rowCount() == 0) {
    // If no code exists, return empty stats
    printSuccess([
        "referral_code" => null,
        "total_invited_drivers" => 0,
        "total_invited_passengers" => 0,
        "referrals" => []
    ]);
    exit;
}

$referralCode = $stmtCode->fetchColumn();

// 2. Fetch all referrals made by this code
$stmtRefs = $con->prepare("
    SELECT id, invited_user_id, invited_user_type, status, trip_count, is_reward_claimed, created_at 
    FROM unified_referrals 
    WHERE inviter_code = ?
    ORDER BY created_at DESC
");
$stmtRefs->execute([$referralCode]);
$referrals = $stmtRefs->fetchAll(PDO::FETCH_ASSOC);

$totalDrivers = 0;
$totalPassengers = 0;

// Format data and calculate stats
foreach ($referrals as &$ref) {
    if ($ref['invited_user_type'] == 'driver') {
        $totalDrivers++;
        $ref['target_trips'] = 50;
        $ref['reward_syp'] = 500;
        $ref['can_claim'] = ($ref['trip_count'] >= 50 && $ref['is_reward_claimed'] == 0) ? true : false;
    } else {
        $totalPassengers++;
        $ref['target_trips'] = 1;
        $ref['reward_syp'] = 30 * min($ref['trip_count'], 10); // Or max depending on logic
        $ref['can_claim'] = ($ref['trip_count'] >= 1 && $ref['is_reward_claimed'] == 0) ? true : false;
    }
}

printSuccess([
    "referral_code" => $referralCode,
    "total_invited_drivers" => $totalDrivers,
    "total_invited_passengers" => $totalPassengers,
    "referrals" => $referrals
]);
?>
