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

try {
    $swLat = floatval(filterRequest("southwestLat"));
    $neLat = floatval(filterRequest("northeastLat"));
    $swLon = floatval(filterRequest("southwestLon"));
    $neLon = floatval(filterRequest("northeastLon"));
    $yearMin = 2022;
    $yearMax = 2025;

    if (!is_numeric($swLat) || !is_numeric($neLat) || !is_numeric($swLon) || !is_numeric($neLon)) {
        throw new Exception("Invalid coordinate values provided");
    }

    $sql = "
    WITH LatestLocations AS (
        SELECT
            cl.driver_id,
            cl.latitude,
            cl.longitude,
            cl.heading,
            cl.speed,
            cl.status,
            cl.created_at,
            d.phone,
            d.email,
            d.first_name,
            d.last_name,
            d.gender,
            d.maritalStatus,
            d.education,
            cr.make,
            cr.car_plate,
            cr.model,
            cr.color,
            cr.color_hex,
            cr.year,
            dt.token,
            ROW_NUMBER() OVER(
                PARTITION BY cl.driver_id
                ORDER BY cl.created_at DESC
            ) AS row_num
        FROM car_locations cl
        JOIN driver d ON d.id = cl.driver_id
        LEFT JOIN CarRegistration cr ON cr.driverID = cl.driver_id
        LEFT JOIN driverToken dt ON dt.captain_id = cl.driver_id
        WHERE cl.latitude BETWEEN ? AND ?
        AND cl.longitude BETWEEN ? AND ?
        AND cr.year BETWEEN ? AND ?
        AND cl.created_at >= NOW() - INTERVAL 1 DAY
        AND cr.make NOT LIKE '%دراج%'
        AND cr.model NOT LIKE '%دراج%'
    )
    SELECT 
        d.id AS driver_id,
        d.phone,
        d.gender,
        d.name_arabic  AS name_arabic,
        d.name_english,
        d.address,
        ll.latitude,
        ll.longitude,
        FLOOR(DATEDIFF(CURDATE(), STR_TO_DATE(CONCAT(d.birthdate, '-01-01'), '%Y-%m-%d')) / 365.25) AS age,
        c.car_plate,
        c.make,
        c.model,
        c.year,
        c.color,
        c.fuel,
        c.displacement,
        c.color_hex,
        dt.token,
        COALESCE(avg_rating.rating, 5) AS rating,
        COALESCE(ride_count.count, 0) AS ride_count
    FROM driver d
    JOIN CarRegistration c ON c.driverID = d.id
    JOIN LatestLocations ll ON ll.driver_id = d.id AND ll.row_num = 1
    LEFT JOIN driverToken dt ON dt.captain_id = d.id
    LEFT JOIN (
        SELECT driver_id, AVG(rating) AS rating
        FROM ratingDriver
        GROUP BY driver_id
    ) avg_rating ON avg_rating.driver_id = d.id
    LEFT JOIN (
        SELECT driver_id, COUNT(*) AS count
        FROM ride
        WHERE status = 'Finished'
        GROUP BY driver_id
    ) ride_count ON ride_count.driver_id = d.id
    WHERE c.year BETWEEN ? AND ?
    ORDER BY rating DESC, c.year DESC, ride_count DESC
    LIMIT 10";

    $stmt = $con->prepare($sql);
    $stmt->execute([
        $swLat, $neLat, $swLon, $neLon,
        $yearMin, $yearMax,
        $yearMin, $yearMax
    ]);

    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // فك التشفير عن الحقول الحساسة
    foreach ($rows as &$row) {
        $row['phone']         = $encryptionHelper->decryptData($row['phone']);
        $row['gender']        = $encryptionHelper->decryptData($row['gender']);
        $row['name_arabic']   = $encryptionHelper->decryptData($row['name_arabic']);
        $row['name_english']  = $encryptionHelper->decryptData($row['name_english']);
        $row['address']       = $encryptionHelper->decryptData($row['address']);
        $row['car_plate']     = $encryptionHelper->decryptData($row['car_plate']);
        $row['token']         = $encryptionHelper->decryptData($row['token']);
    }

    if (count($rows) > 0) {
        jsonSuccess($rows);
    } else {
        jsonError("No drivers found in the specified area");
    }

} catch (PDOException $e) {
    jsonError("Database error: " . $e->getMessage());
} catch (Exception $e) {
    jsonError("Error: " . $e->getMessage());
}