<?php
include '../cn.php';
ini_set('display_errors', 1);
error_reporting(E_ALL);

// 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 users uc ON uc.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
            uc.Username 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.fare,
        rentedcars.addifare,
        rentedcars.status,
        rentedcars.pickup,
        rentedcars.Destination,
        rentedcars.PaymentStatus,
        rentedcars.voucher_number,
        rentedcars.PaymentReference,
        rentedcars.bookingsource,
        rentedcars.last_canceler_id,
        driver.driver_name,
        cars.car_name,
        app_users.Name AS AppUserName,
        u.Username AS AdminUsername,
        uc.Username AS CancellerUsername
    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 users uc ON uc.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
        uc.Username LIKE '%$search%'
    )";
}

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

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

// 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';
    }
    $row['total_amount'] = $row['fare'] + $row['addifare'];

    // Handle last_cancelled_by field
    $lastCancelledBy = 'Never Cancelled';
    if (!empty($row['last_canceler_id'])) {
        if (!empty($row['CancellerUsername'])) {
            $lastCancelledBy = htmlspecialchars($row['CancellerUsername']);
        } else {
            $lastCancelledBy = 'User ID: ' . $row['last_canceler_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, // ADDED THIS FIELD
        'booking_date' => $row['booking_date'] ?? '',
        'rent_start_date' => $row['rent_start_date'] ?? '',
        'car_title' => htmlspecialchars($row['car_name'] ?? ''),
        'pickup' => htmlspecialchars($row['pickup'] ?? ''),
        'Destination' => htmlspecialchars($row['Destination'] ?? ''),
        'customer_name' => htmlspecialchars($row['AppUserName'] ?? $row['AdminUsername'] ?? ''),
        'total_amount' => (!empty($row['total_amount']) ? $row['total_amount'].' AED' : ''),
        'PaymentStatus' => (!empty($row['PaymentStatus']) ? '('.$row['PaymentStatus'].')' : ''),
        'voucher_number' => htmlspecialchars($row['voucher_number'] ?? ''),
        'PaymentReference' => htmlspecialchars($row['PaymentReference'] ?? ''),
        'source_info' => htmlspecialchars($row['bookingsource'] ?? ''),
        'delete_action' => '<a href="ajax/delete-booking.php?id='.$row['id'].'" 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
header('Content-Type: application/json');
echo json_encode([
    "draw" => $draw,
    "recordsTotal" => get_total_records($connect),
    "recordsFiltered" => get_filtered_records($connect, $search),
    "data" => $bookings
]);