<?php
header('Access-Control-Allow-Origin: *');
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET, POST, 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");

require_once 'db.php';

$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
$search = isset($_GET['search']) ? $_GET['search'] : '';
$order = isset($_GET['order']) ? $_GET['order'] : 'desc';
$offset = ($page - 1) * $limit;

$response = array();

try {
    $searchQuery = '';
    if ($search) {
        $searchTerm = '%' . $conn->real_escape_string($search) . '%';
        $searchQuery = "WHERE u.name LIKE '$searchTerm' OR b.vehicle_type LIKE '$searchTerm' OR d.driver_name LIKE '$searchTerm'";
    }
    $sql = "SELECT SQL_CALC_FOUND_ROWS b.*, u.name,u.phone as user_phone, d.driver_name, d.phone  
            FROM new_trip_booking b 
            LEFT JOIN users u ON b.user_id = u.id 
            LEFT JOIN registered_vehicles d ON b.driver = d.id 
            $searchQuery 
            ORDER BY b.id $order 
            LIMIT $limit OFFSET $offset";
    $result = $conn->query($sql);

    if (!$result) {
        throw new Exception("Query Error: " . $conn->error);
    }

    $bookings = array();
    while ($row = $result->fetch_assoc()) {
        $bookings[] = array('booking' => $row, 'name' => $row['name'], 'driver_name' => $row['driver_name'],'user_phone' => $row['user_phone'], 'driver_phone' => $row['phone']);
    }

    // Get total count for pagination
    $resultTotal = $conn->query("SELECT FOUND_ROWS() AS total");
    if (!$resultTotal) {
        throw new Exception("Total Count Query Error: " . $conn->error);
    }

    $totalRow = $resultTotal->fetch_assoc();
    $totalCount = $totalRow['total'];

    $response = array('bookings' => $bookings, 'totalCount' => $totalCount);

} catch (Exception $e) {
    $response['error'] = $e->getMessage();
}

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