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

$driver_id = filterRequest("driver_id");

if (!$driver_id) {
    jsonError("Missing driver_id");
}

try {
    // 1. Get Country and Currency Info
    $stmtKazan = $con->prepare("SELECT country, currency FROM kazan LIMIT 1");
    $stmtKazan->execute();
    $kazan = $stmtKazan->fetch(PDO::FETCH_ASSOC) ?: ["country" => "Jordan", "currency" => "JOD"];

    // 2. Get Total Completed Trips
    $stmtTrips = $con->prepare("SELECT COUNT(*) as count FROM `ride` WHERE driver_id = :driver_id AND status = 'Finished'");
    $stmtTrips->execute([':driver_id' => $driver_id]);
    $totalTrips = (int)($stmtTrips->fetchColumn() ?: 0);

    // 3. Get Average Rating
    $stmtRate = $con->prepare("SELECT COALESCE(ROUND(AVG(rating), 2), 5.0) as rating FROM ratingDriver WHERE driver_id = :driver_id");
    $stmtRate->execute([':driver_id' => $driver_id]);
    $avgRating = (float)($stmtRate->fetchColumn() ?: 5.0);

    // 4. Get Referral Counts (Installed/Verified)
    $stmtDInv = $con->prepare("SELECT COUNT(*) FROM invites WHERE driverId = :driver_id AND isInstall = 1");
    $stmtDInv->execute([':driver_id' => $driver_id]);
    $driverInvites = (int)($stmtDInv->fetchColumn() ?: 0);

    $stmtPInv = $con->prepare("SELECT COUNT(*) FROM invitesToPassengers WHERE driverId = :driver_id AND isInstall = 1");
    $stmtPInv->execute([':driver_id' => $driver_id]);
    $passengerInvites = (int)($stmtPInv->fetchColumn() ?: 0);

    $totalReferrals = $driverInvites + $passengerInvites;

    // 5. Get Driver Behavior (Last 30 Days)
    $stmtBehavior = $con->prepare("
        SELECT 
            COALESCE(ROUND(AVG(behavior_score), 1), 100) as avg_score,
            COALESCE(SUM(hard_brakes), 0) as total_hard_brakes,
            COALESCE(MAX(max_speed), 0) as max_speed
        FROM `driver_behavior`
        WHERE driver_id = :driver_id
          AND created_at >= DATE(NOW()) - INTERVAL 30 DAY
    ");
    $stmtBehavior->execute([':driver_id' => $driver_id]);
    $behavior = $stmtBehavior->fetch(PDO::FETCH_ASSOC) ?: ["avg_score" => 100.0, "total_hard_brakes" => 0, "max_speed" => 0.0];

    // 6. Get Today's Completed Trips & Earnings (Local Ride Database)
    $stmtTodayTrips = $con->prepare("SELECT COUNT(*) FROM `ride` WHERE driver_id = :driver_id AND status = 'Finished' AND DATE(created_at) = CURDATE()");
    $stmtTodayTrips->execute([':driver_id' => $driver_id]);
    $todayTrips = (int)($stmtTodayTrips->fetchColumn() ?: 0);

    $stmtTodayEarnings = $con->prepare("SELECT COALESCE(SUM(price_for_driver), 0) FROM `ride` WHERE driver_id = :driver_id AND status = 'Finished' AND DATE(created_at) = CURDATE()");
    $stmtTodayEarnings->execute([':driver_id' => $driver_id]);
    $todayEarnings = (float)($stmtTodayEarnings->fetchColumn() ?: 0.0);

    // 7. Get Claimed Challenge Points from Payment Server via S2S
    $walletServer = "https://walletintaleq.intaleq.xyz";
    if (strtolower($kazan["country"]) == 'jordan') {
        $walletServer = getenv('WALLET_SERVER_JORDAN') ?: "https://walletintaleq.intaleq.xyz";
    } elseif (strtolower($kazan["country"]) == 'egypt') {
        $walletServer = getenv('WALLET_SERVER_EGYPT') ?: "https://walletintaleq.intaleq.xyz";
    } else {
        $walletServer = getenv('WALLET_SERVER_SYRIA') ?: "https://walletintaleq.intaleq.xyz";
    }

    $walletUrl = "$walletServer/v2/main/ride/driverWallet/get_s2s_wallet_dashboard.php";

    $ch = curl_init($walletUrl);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query(["driverID" => $driver_id]),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10,
        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);

    $challengePoints = 0;
    if (!$curlErr && $httpCode === 200) {
        $resDecoded = json_decode($response, true);
        if ($resDecoded && isset($resDecoded['status']) && $resDecoded['status'] === 'success') {
            $challengePoints = (int)($resDecoded['message']['challengePoints'] ?? 0);
        }
    }

    // 8. Calculate Normalized Points
    // 10 pts per finished trip, 100 pts per referral invite, 2 pts per behavior score point + claimed challenge points
    $normalizedPoints = ($totalTrips * 10) + ($totalReferrals * 100) + ((int)$behavior['avg_score'] * 2) + $challengePoints;

    jsonSuccess([
        "country" => $kazan["country"],
        "currency" => $kazan["currency"],
        "totalTrips" => $totalTrips,
        "averageRating" => $avgRating,
        "totalReferrals" => $totalReferrals,
        "driverInvites" => $driverInvites,
        "passengerInvites" => $passengerInvites,
        "behaviorScore" => (float)$behavior["avg_score"],
        "hardBrakes" => (int)$behavior["total_hard_brakes"],
        "maxSpeed" => (float)$behavior["max_speed"],
        "todayTrips" => $todayTrips,
        "todayEarnings" => $todayEarnings,
        "totalPoints" => $normalizedPoints
    ]);

} catch (PDOException $e) {
    error_log("getGamificationDashboard Error: " . $e->getMessage());
    jsonError("Database error occurred: " . $e->getMessage());
}
?>
