<?php

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

$sql = "SELECT
    COUNT(`car_locations`.driver_id) AS driver_count,
    driver.id,
    driver.phone,
    driver.name_arabic,
    MAX(dt.token) AS token
FROM
    `car_locations`
LEFT JOIN driver ON driver.id = car_locations.driver_id
LEFT JOIN driverToken dt ON dt.captain_id = driver.id
WHERE
    `car_locations`.created_at > TIMESTAMP(DATE_SUB(NOW(), INTERVAL 7 DAY))
GROUP BY
    driver.id
ORDER BY
    driver_count DESC
LIMIT 19;
";

$stmt = $con->prepare($sql);
$stmt->execute();

if ($stmt->rowCount() > 0) {
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

    jsonSuccess($rows);
} else {
    jsonError($message = "No recent driver location activity found");
}

?>