<?php
require_once 'db.php'; // Include database connection

header('Access-Control-Allow-Origin: *');
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

$response = array();

try {
    if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['id'])) {
        $id = $_GET['id'];

        $query = "SELECT tb.*, rv.vehicle_current_lat, rv.vehicle_current_lng, u.name AS user_name, rv.driver_name 
                  FROM new_trip_booking tb 
                  LEFT JOIN registered_vehicles rv ON tb.driver = rv.id 
                  LEFT JOIN users u ON tb.user_id = u.id
                  WHERE tb.id = ?";

        if ($stmt = $conn->prepare($query)) {
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $result = $stmt->get_result();
            $booking = $result->fetch_assoc();

            if ($booking) {
                $response = [
                    'booking' => $booking,
                    'driver_position' => [
                        'vehicle_current_lat' => $booking['vehicle_current_lat'],
                        'vehicle_current_lng' => $booking['vehicle_current_lng'],
                    ]
                ];
            } else {
                http_response_code(404); // Not Found
                $response['message'] = 'Booking not found';
            }

            $stmt->close();
        } else {
            http_response_code(500); // Internal Server Error
            $response['message'] = 'Database query failed: ' . $conn->error;
        }
    } else {
        http_response_code(400); // Bad Request
        $response['message'] = 'Invalid request';
    }
} catch (Exception $e) {
    http_response_code(500); // Internal Server Error
    $response['message'] = 'Server error: ' . $e->getMessage();
}

echo json_encode($response);
$conn->close();
?>
