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

$type = isset($_POST['type']) ? filterRequest("type") : 'trips';

try {
    if ($type === 'earnings') {
        $sql = "
            SELECT 
                d.id as driver_id,
                COALESCE(d.name, d.nameArabic, d.firstName, 'Driver') as name,
                d.personal_photo as photoUrl,
                COALESCE(SUM(r.price_for_driver), 0) as value
            FROM `driver` d
            JOIN `ride` r ON d.id = r.driver_id
            WHERE r.status = 'Finished'
              AND r.created_at >= DATE(NOW() - INTERVAL WEEKDAY(NOW()) DAY)
            GROUP BY d.id
            ORDER BY value DESC
            LIMIT 10
        ";
    } else {
        // Default to trips
        $sql = "
            SELECT 
                d.id as driver_id,
                COALESCE(d.name, d.nameArabic, d.firstName, 'Driver') as name,
                d.personal_photo as photoUrl,
                COUNT(r.id) as value
            FROM `driver` d
            JOIN `ride` r ON d.id = r.driver_id
            WHERE r.status = 'Finished' 
              AND r.created_at >= DATE(NOW() - INTERVAL WEEKDAY(NOW()) DAY)
            GROUP BY d.id
            ORDER BY value DESC
            LIMIT 10
        ";
    }

    $stmt = $con->prepare($sql);
    $stmt->execute();
} catch (PDOException $e) {
    error_log("getLeaderboard Error: " . $e->getMessage());
    jsonError("Database error occurred");
}

if ($stmt->rowCount() > 0) {
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Add Rank manually to support older MySQL versions
    $rank = 1;
    foreach ($rows as &$row) {
        $row['rank'] = $rank++;
    }
    
    jsonSuccess($rows);
} else {
    jsonSuccess([]);
}
?>
