<?php
// Prevent any output before JSON
ob_start();

include '../cn.php';

// Suppress errors for production (they break JSON)
ini_set('display_errors', 0);
error_reporting(0);

// Clear any accidental output from cn.php
ob_end_clean();

// Set JSON header immediately
header('Content-Type: application/json');

try {
    // Get parameters
    $start = isset($_GET['start']) ? intval($_GET['start']) : 0;
    $length = isset($_GET['length']) ? intval($_GET['length']) : 10;
    $search = isset($_GET['search']['value']) ? mysqli_real_escape_string($connect, $_GET['search']['value']) : '';
    $draw = isset($_GET['draw']) ? intval($_GET['draw']) : 1;

    $bookings = [];

    // Get total record count without filters
    function get_total_records($connect) {
        $result = mysqli_query($connect, "SELECT COUNT(*) as total FROM rentedcars");
        if ($result) {
            $row = mysqli_fetch_assoc($result);
            return $row['total'];
        }
        return 0;
    }

    // Get filtered record count
    function get_filtered_records($connect, $search) {
        if (empty($search)) {
            return get_total_records($connect);
        }
        
        $query = "SELECT COUNT(*) as total FROM rentedcars
            LEFT JOIN driver ON driver.driver_id = rentedcars.driver_id
            LEFT JOIN cars ON cars.car_id = rentedcars.car_id
            LEFT JOIN app_users ON app_users.id = rentedcars.AppUser
            LEFT JOIN users u ON u.Id = rentedcars.user_id
            LEFT JOIN driver dc ON dc.driver_id = rentedcars.last_canceler_id
            WHERE 
                rentedcars.id LIKE '%$search%' OR
                rentedcars.BookingNumber LIKE '%$search%' OR
                rentedcars.status LIKE '%$search%' OR
                driver.driver_name LIKE '%$search%' OR
                rentedcars.pickup LIKE '%$search%' OR
                rentedcars.Destination LIKE '%$search%' OR
                cars.car_name LIKE '%$search%' OR
                rentedcars.PaymentStatus LIKE '%$search%' OR
                rentedcars.voucher_number LIKE '%$search%' OR
                rentedcars.PaymentReference LIKE '%$search%' OR
                app_users.Name LIKE '%$search%' OR
                u.Username LIKE '%$search%' OR
                dc.driver_name LIKE '%$search%'";
        
        $result = mysqli_query($connect, $query);
        if ($result) {
            $row = mysqli_fetch_assoc($result);
            return $row['total'];
        }
        return 0;
    }

    // Main query
    $sql = "SELECT 
            rentedcars.id,
            rentedcars.BookingNumber,
            rentedcars.booking_date,
            rentedcars.rent_start_date,
            rentedcars.total_amount,
            rentedcars.status,
            rentedcars.pickup,
            rentedcars.Destination,
            rentedcars.PaymentStatus,
            rentedcars.voucher_number,
            rentedcars.PaymentReference,
            rentedcars.bookingsource,
            rentedcars.driver_id,
            rentedcars.last_canceler_id,
            driver.driver_name,
            cars.car_name AS car_title,
            app_users.Name AS customer_name,
            u.Username AS admin_username,
            dc.driver_name AS CancellerName
        FROM rentedcars
        INNER JOIN cars ON cars.car_id = rentedcars.car_id
        LEFT JOIN driver ON driver.driver_id = rentedcars.driver_id
        LEFT JOIN app_users ON app_users.id = rentedcars.AppUser
        LEFT JOIN users u ON u.Id = rentedcars.user_id
        LEFT JOIN driver dc ON dc.driver_id = rentedcars.last_canceler_id
        WHERE 1=1";

    // Apply search filter if exists
    if (!empty($search)) {
        $sql .= " AND (
            rentedcars.id LIKE '%$search%' OR
            rentedcars.BookingNumber LIKE '%$search%' OR
            rentedcars.status LIKE '%$search%' OR
            driver.driver_name LIKE '%$search%' OR
            rentedcars.pickup LIKE '%$search%' OR
            rentedcars.Destination LIKE '%$search%' OR
            cars.car_name LIKE '%$search%' OR
            rentedcars.PaymentStatus LIKE '%$search%' OR
            rentedcars.voucher_number LIKE '%$search%' OR
            rentedcars.PaymentReference LIKE '%$search%' OR
            app_users.Name LIKE '%$search%' OR
            u.Username LIKE '%$search%' OR
            dc.driver_name LIKE '%$search%'
        )";
    }

    $sql .= " ORDER BY rentedcars.booking_date DESC LIMIT $start, $length";

    $result = mysqli_query($connect, $sql);

    if (!$result) {
        throw new Exception(mysqli_error($connect));
    }

    // Format data for DataTables
    while ($row = mysqli_fetch_assoc($result)) {
        // Determine status color
        $statusColor = 'green';
        if (!empty($row['status'])) {
            $statusLower = strtolower($row['status']);
            if ($statusLower === 'pending') $statusColor = 'red';
            elseif ($statusLower === 'assigned') $statusColor = 'blue';
            elseif ($statusLower === 'in-progress') $statusColor = 'green';
        }
        
        // Handle last_cancelled_by field
        $lastCancelledBy = 'Never Cancelled';
        if (!empty($row['last_canceler_id'])) {
            if (!empty($row['CancellerName'])) {
                $lastCancelledBy = htmlspecialchars($row['CancellerName']);
            } else {
                $lastCancelledBy = 'Unknown Driver';
            }
        }
        
        // Format booking source
        $sourceInfo = '';
        if ($row['bookingsource'] == 'Driver' && !empty($row['driver_name'])) {
            $sourceInfo = htmlspecialchars($row['driver_name']) . ' (Driver)';
        } elseif (($row['bookingsource'] == 'User' || $row['bookingsource'] == 'Admin') && !empty($row['admin_username'])) {
            $sourceInfo = htmlspecialchars($row['admin_username']) . ' (' . $row['bookingsource'] . ')';
        }
        
        // Format delete button based on driver_id
        $deleteUrl = 'ajax/delete-booking.php?id=' . $row['id'];
        if (!empty($row['driver_id'])) {
            $deleteUrl .= '&driver_id=' . $row['driver_id'];
        }

        $bookings[] = [
            'actions' => '<a href="booking-detail.php?id='.$row['id'].'" class="btn btn-theme button-1 ctm-border-radius text-white btn-sm float-center">
                            <i class="fa fa-reply" aria-hidden="true"></i>
                          </a>',
            'BookingNumber' => '<h2 class="ml-2"><a href="#">'.htmlspecialchars($row['BookingNumber'] ?? '').'</a></h2>',
            'driver_status' => htmlspecialchars($row['driver_name'] ?? '') . 
                              ' <a style="color:'.$statusColor.'; font-weight:bold;">('.
                              htmlspecialchars($row['status'] ?? '').')</a>',
            'last_cancelled_by' => $lastCancelledBy,
            'booking_date' => !empty($row['booking_date']) ? date('d.m.Y H:i a', strtotime($row['booking_date'])) : '',
            'rent_start_date' => !empty($row['rent_start_date']) ? date('d.m.Y H:i a', strtotime($row['rent_start_date'])) : '',
            'car_title' => htmlspecialchars($row['car_title'] ?? ''),
            'pickup' => htmlspecialchars($row['pickup'] ?? ''),
            'Destination' => htmlspecialchars($row['Destination'] ?? ''),
            'customer_name' => htmlspecialchars($row['customer_name'] ?? ''),
            'total_amount' => !empty($row['total_amount']) ? $row['total_amount'].' AED' : '',
            'payment_info' => !empty($row['PaymentStatus']) ? '('.htmlspecialchars($row['PaymentStatus']).')' : '',
            'voucher_number' => htmlspecialchars($row['voucher_number'] ?? ''),
            'PaymentReference' => htmlspecialchars($row['PaymentReference'] ?? ''),
            'source_info' => $sourceInfo,
            'delete_action' => '<a href="'.$deleteUrl.'" class="btn btn-danger button-1 ctm-border-radius text-white btn-sm float-center">
                                 <i class="fa fa-trash" aria-hidden="true"></i>
                               </a>'
        ];
    }

    // Return JSON response
    echo json_encode([
        "draw" => $draw,
        "recordsTotal" => get_total_records($connect),
        "recordsFiltered" => get_filtered_records($connect, $search),
        "data" => $bookings
    ]);

} catch (Exception $e) {
    // Return error as valid JSON
    echo json_encode([
        "draw" => 1,
        "recordsTotal" => 0,
        "recordsFiltered" => 0,
        "data" => [],
        "error" => $e->getMessage()
    ]);
}