Files
Siro/loction_server/siro/ride/location/get.php
2026-06-29 23:09:43 +03:00

147 lines
5.1 KiB
PHP
Executable File

<?php
include "../../connect.php";
// Set timezone for PHP logs only (Keep DB on UTC)
date_default_timezone_set('Asia/Amman');
try {
// 1) Read and validate coordinates
$southwestLat = filterRequest("southwestLat");
$southwestLon = filterRequest("southwestLon");
$northeastLat = filterRequest("northeastLat");
$northeastLon = filterRequest("northeastLon");
if ($southwestLat === false || $southwestLon === false ||
$northeastLat === false || $northeastLon === false) {
printFailure("Invalid coordinates provided");
exit;
}
// Fixed time window in seconds
$freshSeconds = 180; // 3 minutes
// =================================================================
// OPTIMIZATION: Create a Bounding Box Polygon in WKT format
// We create a geometric shape (a rectangle) that represents the map area.
// The SQL query will now find all points *inside* this shape.
// The format is POLYGON((lon lat, lon lat, ...))
// =================================================================
$boundingBoxWKT = sprintf(
'POLYGON((%f %f, %f %f, %f %f, %f %f, %f %f))',
$southwestLon, $southwestLat,
$northeastLon, $southwestLat,
$northeastLon, $northeastLat,
$southwestLon, $northeastLat,
$southwestLon, $southwestLat
);
// =================================================================
// OPTIMIZATION: Modified SQL Query
// - We replaced the two `BETWEEN` clauses with a single, highly efficient
// `ST_CONTAINS` function.
// - `ST_GeomFromText` converts our text polygon into a geometry object.
// - `ST_CONTAINS` uses the SPATIAL INDEX to rapidly find all `location_point`s
// that are within our bounding box.
// =================================================================
$sql = "
SELECT
NOW() AS serverNow,
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 AS make,
cr.car_plate AS car_plate,
cr.model AS model,
cr.color AS color,
cr.vin AS vin,
cr.color_hex AS color_hex,
cr.year AS year,
dt.token AS token,
COALESCE(rdAvg.ratingDriver, 0) AS ratingDriver
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
LEFT JOIN (
SELECT driver_id, AVG(rating) AS ratingDriver
FROM ratingDriver
GROUP BY driver_id
) rdAvg ON rdAvg.driver_id = cl.driver_id
WHERE
-- This is the optimized spatial condition
ST_CONTAINS(ST_GeomFromText(:boundingBox, 4326), cl.location_point)
AND cl.status = 'off'
AND cl.updated_at >= NOW() - INTERVAL :freshSeconds SECOND
AND COALESCE(cr.year, 0) > 2000
AND (cr.make NOT LIKE '%دراج%' AND cr.model NOT LIKE '%دراج%')
ORDER BY cl.updated_at DESC, ratingDriver DESC
LIMIT 5
";
$stmt = $con->prepare($sql);
// Bind the new bounding box parameter
$stmt->bindValue(':boundingBox', $boundingBoxWKT);
$stmt->bindValue(':freshSeconds', $freshSeconds, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (!$rows) {
printFailure("No car locations found");
exit;
}
// Decryption and age calculation logic remains the same
$fieldsToDecrypt = [
'phone','email','gender','birthdate',
'first_name','last_name','maritalStatus',
'token','make','car_plate','vin'
];
foreach ($rows as &$row) {
foreach ($fieldsToDecrypt as $field) {
if (isset($row[$field]) && $row[$field] !== null && $row[$field] !== '') {
try { $row[$field] = $encryptionHelper->decryptData($row[$field]); }
catch (Exception $e) { $row[$field] = null; }
}
}
if (!empty($row['birthdate'])) {
try {
$birthdate = new DateTime($row['birthdate']);
$today = new DateTime();
$row['age'] = $today->diff($birthdate)->y;
} catch (Exception $e) { $row['age'] = null; }
} else {
$row['age'] = null;
}
if (isset($row['serverNow'], $row['updated_at'])) {
error_log('PHP Now: '.date('Y-m-d H:i:s')
.' | MySQL Now: '.$row['serverNow']
.' | updated_at: '.$row['updated_at']);
}
}
unset($row);
printSuccess($rows);
} catch (PDOException $e) {
printFailure("Database error: " . $e->getMessage());
} catch (Throwable $e) {
printFailure("Internal error: " . $e->getMessage());
}