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

try {
    $southwestLat = filterRequest("southwestLat");
    $southwestLon = filterRequest("southwestLon");
    $northeastLat = filterRequest("northeastLat");
    $northeastLon = filterRequest("northeastLon");

    if ($southwestLat === false || $southwestLon === false || $northeastLat === false || $northeastLon === false) {
        jsonError("Invalid coordinates provided");
        exit;
    }

    $sql = "
    SELECT
        cl.driver_id,
        cl.latitude,
        cl.longitude,
        cl.heading,
        cl.speed,
        cl.status,
        cl.created_at,
        cl.updated_at,
        d.phone,
        d.email,
        d.birthdate,
        d.first_name,
        d.last_name,
        d.gender,
        d.maritalStatus,
        cr.make,
        cr.car_plate,
        cr.model,
        cr.color,
        cr.vin,
        cr.color_hex,
        cr.year,
        dt.token,
        '' AS age,
        COALESCE(rdAvg.ratingDriver, 0) AS ratingDriver,
        rdAvg.ratingCount
    FROM
        car_locations cl
    LEFT 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
    LEFT JOIN (
        SELECT driver_id, AVG(rating) AS ratingDriver, COUNT(id) AS ratingCount
        FROM ratingDriver
        GROUP BY driver_id
    ) rdAvg ON rdAvg.driver_id = cl.driver_id
    WHERE
        cl.latitude BETWEEN :southwestLat AND :northeastLat
        AND cl.longitude BETWEEN :southwestLon AND :northeastLon
        AND cl.status = 'off'
        AND cl.updated_at >= NOW() - INTERVAL 5 SECOND
        AND (cr.make LIKE '%دراجة%' OR cr.model LIKE '%دراجة%')
    GROUP BY cl.driver_id
    ORDER BY ratingDriver DESC, cl.updated_at DESC
    LIMIT 10;
    ";

    $stmt = $con->prepare($sql);
    $stmt->bindParam(':southwestLat', $southwestLat);
    $stmt->bindParam(':southwestLon', $southwestLon);
    $stmt->bindParam(':northeastLat', $northeastLat);
    $stmt->bindParam(':northeastLon', $northeastLon);
    $stmt->execute();

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

    if ($rows) {
        $fieldsToDecrypt = [
            'phone', 'email', 'gender', 'birthdate',
            'first_name', 'last_name', 'maritalStatus', 'token',
            'make', 'car_plate', 'vin'
        ];

        $filteredRows = [];

        foreach ($rows as &$row) {
            foreach ($fieldsToDecrypt as $field) {
                if (isset($row[$field])) {
                    $row[$field] = $encryptionHelper->decryptData($row[$field]);
                }
            }

            // فلترة حسب الجنس
            if (strtolower($row['gender']) !== 'female') {
                continue;
            }

            // حساب العمر
            if (!empty($row['birthdate'])) {
                $birthDate = new DateTime($row['birthdate']);
                $today = new DateTime();
                $row['age'] = $today->diff($birthDate)->y;
            } else {
                $row['age'] = null;
            }

            $filteredRows[] = $row;
        }

        jsonSuccess($filteredRows);
    } else {
        jsonError("No car locations found");
    }
} catch (PDOException $e) {
    jsonError("Database error: " . $e->getMessage());
}