<?php
require_once 'db.php'; // Adjust the path as necessary

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

$method = $_SERVER['REQUEST_METHOD'];
$response = array();

try {
    switch ($method) {
        case 'GET':
            if (isset($_GET['id'])) {
                // Fetch a single trip booking with additional data
                $id = intval($_GET['id']);
                $stmt = $conn->prepare("SELECT * FROM new_trip_booking WHERE id = ?");
                $stmt->bind_param("i", $id);
                $stmt->execute();
                $result = $stmt->get_result();
                $booking = $result->fetch_assoc();

                if ($booking) {
                    // Fetch the user's name
                    $user_stmt = $conn->prepare("SELECT name FROM users WHERE id = ?");
                    $user_stmt->bind_param("i", $booking['user_id']);
                    $user_stmt->execute();
                    $user_result = $user_stmt->get_result();
                    $user = $user_result->fetch_assoc();

                    // Fetch the driver's name if available
                    $driver = null;
                    if ($booking['driver'] != null) {
                        $driver_stmt = $conn->prepare("SELECT driver_name, phone FROM registered_vehicles WHERE id = ?");
                        $driver_stmt->bind_param("i", $booking['driver']);
                        $driver_stmt->execute();
                        $driver_result = $driver_stmt->get_result();
                        $driver = $driver_result->fetch_assoc();
                    }

                    $response = [
                        'booking' => $booking,
                        'user_name' => $user['name'],
                        'driver_name' => $driver ? $driver['driver_name'] : null,
                        'driver_phone' => $driver ? $driver['phone'] : null,
                    ];
                } else {
                    $response['error'] = 'Booking not found.';
                }
            } elseif (isset($_GET['entity']) && $_GET['entity'] == 'drivers') {
                // Fetch all drivers
                $result = $conn->query("SELECT id, driver_name, phone FROM registered_vehicles");
                $drivers = [];
                while ($row = $result->fetch_assoc()) {
                    $drivers[] = $row;
                }
                $response = $drivers;
            } else {
                // Fetch all trip bookings
                $result = $conn->query("SELECT * FROM new_trip_booking order by id DESC");
                $bookings = [];
                while ($row = $result->fetch_assoc()) {
                    // Fetch the user's name
                    $user_stmt = $conn->prepare("SELECT name, phone FROM users WHERE id = ?");
                    $user_stmt->bind_param("i", $row['user_id']);
                    $user_stmt->execute();
                    $user_result = $user_stmt->get_result();
                    $user = $user_result->fetch_assoc();

                    // Fetch the driver's name if available
                    $driver = null;
                    if ($row['driver']) {
                        $driver_stmt = $conn->prepare("SELECT driver_name, phone FROM registered_vehicles WHERE id = ?");
                        $driver_stmt->bind_param("i", $row['driver']);
                        $driver_stmt->execute();
                        $driver_result = $driver_stmt->get_result();
                        $driver = $driver_result->fetch_assoc();
                    }

                    $bookings[] = [
                        'booking' => $row,
                        'user_name' => $user ? $user['name'] : null,
                        'driver_name' => $driver ? $driver['driver_name'] : null,
                        'driver_phone' => $driver ? $driver['phone'] : null,
                    ];
                }
                $response = $bookings;
            }
            break;

        case 'POST':
            // Add a new trip booking
            $data = json_decode(file_get_contents("php://input"), true);
            $stmt = $conn->prepare("INSERT INTO new_trip_booking (user_id, pickup_latitude, pickup_longitude, dropoff_latitude, dropoff_longitude, vehicle_type, distance, estimated_time, total_cost, payment_method, status, created_at, driver, scheduled_date_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("iddiddsdssssss", $data['user_id'], $data['pickup_latitude'], $data['pickup_longitude'], $data['dropoff_latitude'], $data['dropoff_longitude'], $data['vehicle_type'], $data['distance'], $data['estimated_time'], $data['total_cost'], $data['payment_method'], $data['status'], $data['created_at'], $data['driver'], $data['scheduled_date_time']);
            if ($stmt->execute()) {
                $response['message'] = 'Trip booking added successfully';
            } else {
                $response['error'] = 'Failed to add trip booking';
            }
            break;

        case 'PUT':
            // Update an existing trip booking
            $data = json_decode(file_get_contents("php://input"), true);
            $stmt = $conn->prepare("UPDATE new_trip_booking SET status = ?, driver = ? WHERE id = ?");
            $stmt->bind_param("sii", $data['status'], $data['driver'], $data['id']);
            if ($stmt->execute()) {
                $response['message'] = 'Trip booking updated successfully';
            } else {
                $response['error'] = 'Failed to update trip booking';
            }
            break;

        case 'DELETE':
            // Delete a trip booking
            $id = $_GET['id'];
            $stmt = $conn->prepare("DELETE FROM new_trip_booking WHERE id = ?");
            $stmt->bind_param("i", $id);
            if ($stmt->execute()) {
                $response['message'] = 'Trip booking deleted successfully';
            } else {
                $response['error'] = 'Failed to delete trip booking';
            }
            break;

        case 'OPTIONS':
            // Handle preflight requests
            http_response_code(204);
            exit();

        default:
            http_response_code(405); // Method Not Allowed
            $response['error'] = 'Method not allowed';
            break;
    }
} catch (Exception $e) {
    http_response_code(500); // Internal Server Error
    $response['error'] = $e->getMessage();
}

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