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

$driver_id = filterRequest('driver_id');

if (empty($driver_id)) {
    jsonError('Missing driver ID');
    exit;
}

// Fetch latest record for this driver:
$sql = "SELECT * FROM write_argument_after_applied_from_background 
        WHERE driver_id = :driver_id 
        AND TIMESTAMPDIFF(MINUTE, time_of_order, NOW()) <= 2
        ORDER BY time_of_order DESC 
        LIMIT 1";



$stmt = $con->prepare($sql);
$stmt->bindParam(':driver_id', $driver_id);
$stmt->execute();

$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row) {
    // convert WKT POINT back to "lat,lng"
    foreach (['passenger_location', 'passenger_destination'] as $f) {
        if (!empty($row["{$f}_wkt"])) {
            // WKT format: POINT(lng lat)
            preg_match('/POINT\(([^ ]+) ([^ ]+)\)/', $row["{$f}_wkt"], $m);
            $row[$f] = "{$m[2]},{$m[1]}";
        }
        unset($row["{$f}_wkt"]);
    }
    jsonSuccess($row);
} else {
    jsonError('No data found');
}