<?php

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

$driver_id = filterRequest("driver_id");
$latitude = filterRequest("latitude");
$longitude = filterRequest("longitude");
$status = filterRequest("status");
$heading = filterRequest("heading");
$speed = filterRequest("speed");
$distance = filterRequest("distance");
$updated_at = date("Y-m-d H:i:s");

// Basic validation
if (!$driver_id || !$latitude || !$longitude || $status === null) {
    http_response_code(400);
    // Use your custom printFailure function for consistency
    jsonError('Missing required fields');
    exit;
}

// Secure SQL using prepared statement
$sql = "INSERT INTO `car_locations` (
            `driver_id`, `latitude`, `longitude`, `heading`, `speed`, `distance`, `status`, `updated_at`
        ) VALUES (
            :driver_id, :latitude, :longitude, :heading, :speed, :distance, :status, :updated_at
        )
        ON DUPLICATE KEY UPDATE
            `latitude` = VALUES(`latitude`),
            `longitude` = VALUES(`longitude`),
            `heading` = VALUES(`heading`),
            `speed` = VALUES(`speed`),
            `distance` = VALUES(`distance`),
            `status` = VALUES(`status`),
            `updated_at` = VALUES(`updated_at`)";

try {
    $stmt = $con->prepare($sql);
    
    // The execute method returns true on success and false on failure.
    $success = $stmt->execute([
        ':latitude'   => $latitude,
        ':longitude'  => $longitude,
        ':heading'    => $heading,
        ':speed'      => $speed,
        ':distance'   => $distance,
        ':status'     => $status,
        ':updated_at' => $updated_at,
        ':driver_id'  => $driver_id
    ]);

    // The reliable way to check for success is if execute() returns true
    // and doesn't throw an exception. We no longer need rowCount().
    if ($success) {
        // Print a success message
        jsonSuccess(null, "Car location updated successfully");
    } else {
        // This case is rare but might happen if execute fails without an exception
        jsonError("Failed to update car location");
    }

} catch (PDOException $e) {
    // A real database error occurred.
    http_response_code(500);
    // You can log the detailed error for debugging
    // error_log('Database error: ' . $e->getMessage()); 
    jsonError('Database error occurred');
}
?>
