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

// Ensure the caller has a valid user_id
if (empty($user_id)) {
    jsonError("Unauthorized", 401);
    exit;
}

$latitude = filterRequest("latitude");
$longitude = filterRequest("longitude");

// Validate inputs
if ($latitude === '' || $longitude === '') {
    jsonError("Latitude and longitude are required", 400);
    exit;
}

try {
    // Insert location log
    $sql = "INSERT INTO `passenger_opening_locations` (`passenger_id`, `latitude`, `longitude`) 
            VALUES (:passenger_id, :latitude, :longitude)";
    
    $stmt = $con->prepare($sql);
    $stmt->bindParam(':passenger_id', $user_id);
    $stmt->bindParam(':latitude', $latitude);
    $stmt->bindParam(':longitude', $longitude);
    
    if ($stmt->execute()) {
        jsonSuccess(null, "Location logged successfully");
    } else {
        jsonError("Failed to log location", 500);
    }
} catch (PDOException $e) {
    error_log("Database Error in save_passenger_location.php: " . $e->getMessage());
    jsonError("An error occurred while logging location", 500);
}
?>
