<?php
// Admin/v2/analytics/driver_ranking.php
require_once __DIR__ . '/../../../connect.php';

if ($role !== 'admin' && $role !== 'super_admin') {
    http_response_code(403);
    echo json_encode(['error' => 'Unauthorized access.']);
    exit;
}

try {
    // أفضل 10 كباتن حسب عدد الرحلات المكتملة
    $stmt = $con->prepare("
        SELECT 
            d.id, d.first_name, d.last_name, d.phone,
            COUNT(r.id) as completed_rides,
            SUM(r.price) as total_revenue
        FROM driver d
        JOIN ride r ON d.id = r.driver_id
        WHERE r.status = 'Finished'
        GROUP BY d.id, d.first_name, d.last_name, d.phone
        ORDER BY completed_rides DESC
        LIMIT 10
    ");
    $stmt->execute();
    $top_drivers = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // فك تشفير الأسماء
    foreach ($top_drivers as &$driver) {
        $driver['first_name'] = $encryptionHelper->decryptData($driver['first_name']);
        $driver['last_name'] = $encryptionHelper->decryptData($driver['last_name']);
        $driver['phone'] = $encryptionHelper->decryptData($driver['phone']);
    }

    echo json_encode([
        'status' => 'success',
        'data' => $top_drivers
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>
