<?php
// admin/reservations.php - Optimized version with Extras Support and Auto Status Management
if(isset($_GET['ajax'])) {
    error_reporting(0);
    ini_set('display_errors', 0);
    ini_set('log_errors', 0);
}

require_once '../includes/config.php';

$user_role = $_SESSION['admin_role'] ?? 'admin';
$is_worker = ($user_role == 'worker');

if(!isset($_SESSION['admin_logged_in'])) {
    if(isset($_GET['ajax'])) {
        echo '{"success":false,"message":"Not logged in"}';
        exit;
    }
    header('Location: login.php');
    exit();
}

// ============================================
// AUTO UPDATE STATUS (Running → Completed)
// ============================================
$today_date = date('Y-m-d');
$current_time = date('H:i:s');

// 1. Update from 'confirmed' to 'running' when pickup time has passed
$stmt = $pdo->prepare("
    UPDATE reservations 
    SET status = 'running' 
    WHERE status = 'confirmed' 
    AND pickup_date <= ?
");
$stmt->execute([$today_date]);

// 2. Update from 'running' to 'completed' when dropoff date has passed
$stmt = $pdo->prepare("
    UPDATE reservations 
    SET status = 'completed' 
    WHERE status = 'running' 
    AND dropoff_date < ?
");
$stmt->execute([$today_date]);

// 3. Also update if dropoff_date = today AND dropoff_time <= current_time
$stmt = $pdo->prepare("
    UPDATE reservations 
    SET status = 'completed' 
    WHERE status = 'running' 
    AND dropoff_date = ? 
    AND dropoff_time <= ?
");
$stmt->execute([$today_date, $current_time]);

$message = '';
$error = '';

// ============================================
// HANDLE AJAX REQUESTS
// ============================================
if(isset($_GET['ajax'])) {
    while (ob_get_level() > 0) {
        ob_end_clean();
    }
    ob_start();
    header('Content-Type: application/json');
    
    // Get reservation details for modal
    if(isset($_GET['get_reservation'])) {
        $id = (int)$_GET['get_reservation'];
        $stmt = $pdo->prepare("
            SELECT r.*, c.brand, c.model, c.license_plate, c.id as car_id 
            FROM reservations r 
            LEFT JOIN cars c ON r.car_id = c.id 
            WHERE r.id = ?
        ");
        $stmt->execute([$id]);
        $reservation = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // Get insurance name
        if($reservation && $reservation['selected_insurance_id']) {
            $ins_stmt = $pdo->prepare("SELECT name FROM insurance_types WHERE id = ?");
            $ins_stmt->execute([$reservation['selected_insurance_id']]);
            $ins = $ins_stmt->fetch();
            $reservation['insurance_name'] = $ins ? $ins['name'] : 'Unknown';
        } else {
            $reservation['insurance_name'] = 'Basic Insurance';
        }
        
        $stmt2 = $pdo->prepare("SELECT * FROM payment_history WHERE reservation_id = ? ORDER BY created_at DESC LIMIT 50");
        $stmt2->execute([$id]);
        $payments = $stmt2->fetchAll(PDO::FETCH_ASSOC);
        
        $stmt3 = $pdo->prepare("SELECT * FROM reservation_notes WHERE reservation_id = ? ORDER BY created_at DESC LIMIT 50");
        $stmt3->execute([$id]);
        $notes = $stmt3->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode(['success' => true, 'reservation' => $reservation, 'payments' => $payments, 'notes' => $notes]);
        exit;
    }
    
    // Update customer info
    if(isset($_POST['update_customer_ajax'])) {
        $id = (int)$_POST['id'];
        $customer_name = trim($_POST['customer_name']);
        $customer_email = trim($_POST['customer_email']);
        $customer_phone = trim($_POST['customer_phone']);
        $pickup_location = trim($_POST['pickup_location']);
        $dropoff_location = trim($_POST['dropoff_location']);
        $notes = trim($_POST['notes']);
        
        $stmt = $pdo->prepare("UPDATE reservations SET customer_name = ?, customer_email = ?, customer_phone = ?, pickup_location = ?, dropoff_location = ?, notes = ? WHERE id = ?");
        if($stmt->execute([$customer_name, $customer_email, $customer_phone, $pickup_location, $dropoff_location, $notes, $id])) {
            $stmt2 = $pdo->prepare("INSERT INTO reservation_notes (reservation_id, note, note_type, created_by) VALUES (?, ?, 'system', ?)");
            $stmt2->execute([$id, "Customer information updated by " . $_SESSION['admin_username'], $_SESSION['admin_username']]);
            echo json_encode(['success' => true, 'message' => 'Customer info updated']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Update failed']);
        }
        exit;
    }
    
    // ============================================
    // UPDATE STATUS - ME KONTROLL TË RIAKTIVIMIT
    // ============================================
    if(isset($_POST['update_status_ajax'])) {
        $id = (int)$_POST['id'];
        $status = $_POST['status'];
        
        // Validate status
        $allowed_statuses = ['pending', 'confirmed', 'cancelled', 'running', 'completed'];
        if(!in_array($status, $allowed_statuses)) {
            echo json_encode(['success' => false, 'message' => 'Invalid status']);
            exit;
        }
        
        // Get current status and reservation details
        $stmt_old = $pdo->prepare("SELECT status, car_id, pickup_date, pickup_time, dropoff_date, dropoff_time FROM reservations WHERE id = ?");
        $stmt_old->execute([$id]);
        $old_data = $stmt_old->fetch(PDO::FETCH_ASSOC);
        $old_status = $old_data['status'];
        
        // ============================================
        // KONTROLLI I RËNDËSISHËM: Kur riaktivizojmë një rezervim të anuluar
        // ============================================
        if($old_status == 'cancelled' && in_array($status, ['pending', 'confirmed', 'running'])) {
            // Kontrollo nëse datat janë ende të disponueshme
            $availability = isCarAvailable(
                $old_data['car_id'], 
                $old_data['pickup_date'], 
                $old_data['pickup_time'], 
                $old_data['dropoff_date'], 
                $old_data['dropoff_time'], 
                $pdo, 
                $id,  // exclude this reservation
                PREPARATION_HOURS
            );
            
            if(!$availability['available']) {
                echo json_encode([
                    'success' => false, 
                    'message' => 'Cannot reactivate this reservation. ' . $availability['reason']
                ]);
                exit;
            }
        }
        
        // If setting to completed, check if payment is paid
        if($status == 'completed') {
            $stmt_check = $pdo->prepare("SELECT payment_status FROM reservations WHERE id = ?");
            $stmt_check->execute([$id]);
            $current = $stmt_check->fetch();
            if($current['payment_status'] != 'paid') {
                echo json_encode(['success' => false, 'message' => 'Cannot mark as completed: payment not paid yet']);
                exit;
            }
        }
        
        $stmt = $pdo->prepare("UPDATE reservations SET status = ? WHERE id = ?");
        if($stmt->execute([$status, $id])) {
            $note_message = "Status changed from " . ucfirst($old_status) . " to: " . ucfirst($status);
            if($status == 'completed' && $old_status == 'running') {
                $note_message = "🚗 VEHICLE RETURNED! Status changed to Completed.";
            }
            if($old_status == 'cancelled' && in_array($status, ['pending', 'confirmed', 'running'])) {
                $note_message = "⚠️ Reservation REACTIVATED from cancelled to " . ucfirst($status) . ". Dates: {$old_data['pickup_date']} to {$old_data['dropoff_date']}";
            }
            $stmt2 = $pdo->prepare("INSERT INTO reservation_notes (reservation_id, note, note_type, created_by) VALUES (?, ?, 'system', ?)");
            $stmt2->execute([$id, $note_message, $_SESSION['admin_username']]);
            echo json_encode(['success' => true, 'message' => 'Status updated']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Update failed']);
        }
        exit;
    }
    
    // Add payment - WITH REFUND SUPPORT
    if(isset($_POST['add_payment_ajax'])) {
        $id = (int)$_POST['id'];
        $amount = (float)$_POST['amount'];
        $payment_method = $_POST['payment_method'];
        $notes = trim($_POST['notes'] ?? '');
        
        if($amount == 0) {
            echo json_encode(['success' => false, 'message' => 'Amount must be greater than 0 or less than 0 for refund']);
            exit;
        }
        
        $stmt = $pdo->prepare("SELECT total_price, paid_amount, grand_total, status FROM reservations WHERE id = ?");
        $stmt->execute([$id]);
        $current = $stmt->fetch(PDO::FETCH_ASSOC);
        $total_to_use = $current['grand_total'] ?? $current['total_price'];
        
        $new_paid = $current['paid_amount'] + $amount;
        $balance = $total_to_use - $new_paid;
        
        if($balance <= 0) {
            $payment_status = 'paid';
        } elseif($new_paid > 0) {
            $payment_status = 'partial';
        } else {
            $payment_status = 'unpaid';
        }
        
        $stmt = $pdo->prepare("UPDATE reservations SET paid_amount = ?, balance = ?, payment_status = ? WHERE id = ?");
        if($stmt->execute([$new_paid, $balance, $payment_status, $id])) {
            $stmt2 = $pdo->prepare("INSERT INTO payment_history (reservation_id, amount, payment_method, notes, created_by) VALUES (?, ?, ?, ?, ?)");
            $stmt2->execute([$id, $amount, $payment_method, $notes, $_SESSION['admin_username']]);
            
            if($amount < 0) {
                $note_message = "Refund processed: €" . number_format(abs($amount), 2) . " via " . $payment_method;
            } else {
                $note_message = "Payment received: €" . number_format($amount, 2) . " via " . $payment_method;
            }
            
            if($balance < 0) {
                $note_message .= " (Overpayment! Additional refund due: €" . number_format(abs($balance), 2) . ")";
            }
            
            $stmt3 = $pdo->prepare("INSERT INTO reservation_notes (reservation_id, note, note_type, created_by) VALUES (?, ?, 'system', ?)");
            $stmt3->execute([$id, $note_message, $_SESSION['admin_username']]);
            
            echo json_encode(['success' => true, 'message' => $amount < 0 ? 'Refund processed' : 'Payment added', 'balance' => $balance, 'paid_amount' => $new_paid]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Update failed']);
        }
        exit;
    }
    
    // ============================================
    // UPDATE GRAND TOTAL - MODIFIKUAR PLOTËSISHT
    // ============================================
    if(isset($_POST['update_grand_total_ajax'])) {
        $id = (int)$_POST['id'];
        $new_grand_total = (float)$_POST['grand_total'];
        
        if($new_grand_total <= 0) {
            echo json_encode(['success' => false, 'message' => 'Grand total must be greater than 0']);
            exit;
        }
        
        // Get current data
        $stmt = $pdo->prepare("SELECT total_price, paid_amount, grand_total, extras_total, selected_insurance_price FROM reservations WHERE id = ?");
        $stmt->execute([$id]);
        $current = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if(!$current) {
            echo json_encode(['success' => false, 'message' => 'Reservation not found']);
            exit;
        }
        
        $old_grand_total = (float)$current['grand_total'];
        $old_total_price = (float)$current['total_price'];
        $paid_amount = (float)$current['paid_amount'];
        $old_extras_total = (float)$current['extras_total'];
        $old_insurance_price = (float)$current['selected_insurance_price'];
        
        // Calculate difference
        $diff = $new_grand_total - $old_grand_total;
        
        // Determine what to adjust: if extras exist, adjust extras_total
        // Otherwise adjust total_price
        if($old_extras_total > 0 || $old_insurance_price > 0) {
            // Extras exist, adjust extras_total
            $new_extras_total = $old_extras_total + $diff;
            if($new_extras_total < 0) $new_extras_total = 0;
            $new_total_price = $old_total_price;
        } else {
            // No extras, adjust total_price
            $new_total_price = $old_total_price + $diff;
            if($new_total_price < 0) $new_total_price = 0;
            $new_extras_total = 0;
        }
        
        // Recalculate balance
        $new_balance = $new_grand_total - $paid_amount;
        
        // Determine payment status
        if($new_balance <= 0) {
            $payment_status = 'paid';
        } elseif($paid_amount > 0) {
            $payment_status = 'partial';
        } else {
            $payment_status = 'unpaid';
        }
        
        // Update database
        $stmt = $pdo->prepare("UPDATE reservations SET 
            total_price = ?, 
            extras_total = ?, 
            grand_total = ?, 
            balance = ?, 
            payment_status = ? 
            WHERE id = ?");
        
        if($stmt->execute([$new_total_price, $new_extras_total, $new_grand_total, $new_balance, $payment_status, $id])) {
            // Add note
            $diff_text = $diff >= 0 ? "increased by €" . number_format($diff, 2) : "decreased by €" . number_format(abs($diff), 2);
            $note_message = "💰 GRAND TOTAL changed from €" . number_format($old_grand_total, 2) . " to €" . number_format($new_grand_total, 2) . " (" . $diff_text . ")";
            
            if($old_extras_total > 0 || $old_insurance_price > 0) {
                $note_message .= " | Extras adjusted: €" . number_format($old_extras_total, 2) . " → €" . number_format($new_extras_total, 2);
            } else {
                $note_message .= " | Car price adjusted: €" . number_format($old_total_price, 2) . " → €" . number_format($new_total_price, 2);
            }
            
            $stmt2 = $pdo->prepare("INSERT INTO reservation_notes (reservation_id, note, note_type, created_by) VALUES (?, ?, 'system', ?)");
            $stmt2->execute([$id, $note_message, $_SESSION['admin_username']]);
            
            echo json_encode([
                'success' => true, 
                'message' => 'Grand total updated!',
                'new_grand_total' => $new_grand_total,
                'new_balance' => $new_balance,
                'diff' => $diff
            ]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Update failed']);
        }
        exit;
    }
    
    // Check car availability for change
    if(isset($_POST['check_car_availability_ajax'])) {
        $car_id = (int)$_POST['car_id'];
        $reservation_id = (int)$_POST['reservation_id'];
        
        $stmt = $pdo->prepare("SELECT pickup_date, pickup_time, dropoff_date, dropoff_time FROM reservations WHERE id = ?");
        $stmt->execute([$reservation_id]);
        $res = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if($res) {
            $availability = isCarAvailable($car_id, $res['pickup_date'], $res['pickup_time'], $res['dropoff_date'], $res['dropoff_time'], $pdo, $reservation_id, PREPARATION_HOURS);
            echo json_encode(['available' => $availability['available'], 'reason' => $availability['reason']]);
        } else {
            echo json_encode(['available' => false, 'reason' => 'Reservation not found']);
        }
        exit;
    }
    
    // UPDATE DATES
    if(isset($_POST['update_dates_ajax'])) {
        if (ob_get_length()) ob_clean();
        
        $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
        $new_pickup_date = isset($_POST['pickup_date']) ? $_POST['pickup_date'] : '';
        $new_pickup_time = isset($_POST['pickup_time']) ? $_POST['pickup_time'] : '10:00';
        $new_dropoff_date = isset($_POST['dropoff_date']) ? $_POST['dropoff_date'] : '';
        $new_dropoff_time = isset($_POST['dropoff_time']) ? $_POST['dropoff_time'] : '10:00';
        
        $response = [];
        
        if(!$id || !$new_pickup_date || !$new_dropoff_date) {
            $response = ['success' => false, 'message' => 'Missing required fields'];
            echo json_encode($response);
            exit;
        }
        
        $stmt = $pdo->prepare("SELECT car_id, pickup_date, pickup_time, dropoff_date, dropoff_time, total_days, total_price, paid_amount, balance, selected_insurance_id, selected_options, extras_total, status FROM reservations WHERE id = ?");
        $stmt->execute([$id]);
        $current = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if(!$current) {
            $response = ['success' => false, 'message' => 'Reservation not found'];
            echo json_encode($response);
            exit;
        }
        
        $car_id = $current['car_id'];
        $old_pickup = $current['pickup_date'];
        $old_dropoff = $current['dropoff_date'];
        $old_total_price = (float)$current['total_price'];
        $paid_amount = (float)$current['paid_amount'];
        $selected_insurance_id = $current['selected_insurance_id'];
        $selected_options = $current['selected_options'];
        
        if($new_pickup_date > $new_dropoff_date) {
            $response = ['success' => false, 'message' => 'Return date must be after pickup date'];
            echo json_encode($response);
            exit;
        }
        
        $availability = isCarAvailable($car_id, $new_pickup_date, $new_pickup_time, $new_dropoff_date, $new_dropoff_time, $pdo, $id, PREPARATION_HOURS);
        
        if(!$availability['available']) {
            $response = ['success' => false, 'message' => $availability['reason']];
            echo json_encode($response);
            exit;
        }
        
$new_days = getDaysBetween($new_pickup_date, $new_pickup_time, $new_dropoff_date, $new_dropoff_time);

$price_data = calculateDynamicPrice($car_id, $new_pickup_date, $new_pickup_time, $new_dropoff_date, $new_dropoff_time, $pdo);
        $new_total_price = (float)$price_data['total_price'];
        
        // Recalculate extras with new days
        $extras_result = calculateExtrasTotal($selected_insurance_id, $selected_options, $new_days, $pdo);
        $extras_total = $extras_result['extras_total'];
        $selected_insurance_price = $extras_result['selected_insurance_price'];
        $new_grand_total = $new_total_price + $extras_total;
        
        $price_difference = $new_grand_total - ($old_total_price + ($current['extras_total'] ?? 0));
        $new_balance = $new_grand_total - $paid_amount;
        
        if($new_balance <= 0) {
            $payment_status = 'paid';
        } elseif($paid_amount > 0) {
            $payment_status = 'partial';
        } else {
            $payment_status = 'unpaid';
        }
        
        $stmt = $pdo->prepare("UPDATE reservations SET 
            pickup_date = ?, pickup_time = ?, dropoff_date = ?, dropoff_time = ?, 
            total_days = ?, total_price = ?, extras_total = ?, selected_insurance_price = ?, grand_total = ?, balance = ?, payment_status = ? 
            WHERE id = ?");
        
        $update_result = $stmt->execute([
            $new_pickup_date, $new_pickup_time, $new_dropoff_date, $new_dropoff_time,
            $new_days, $new_total_price, $extras_total, $selected_insurance_price, $new_grand_total, $new_balance, $payment_status, $id
        ]);
        
        if($update_result) {
            $note = "📅 DATES CHANGED\n";
            $note .= "Old: {$old_pickup} → {$old_dropoff}\n";
            $note .= "New: {$new_pickup_date} → {$new_dropoff_date}\n";
            $note .= "Days: {$current['total_days']} → {$new_days}\n";
            $note .= "Price: €" . number_format($old_total_price + ($current['extras_total'] ?? 0), 2) . " → €" . number_format($new_grand_total, 2);
            
            if($price_difference > 0) {
                $note .= " (+€" . number_format($price_difference, 2) . ")";
            } elseif($price_difference < 0) {
                $note .= " (-€" . number_format(abs($price_difference), 2) . ")";
            }
            
            $stmt2 = $pdo->prepare("INSERT INTO reservation_notes (reservation_id, note, note_type, created_by) VALUES (?, ?, 'system', ?)");
            $stmt2->execute([$id, $note, $_SESSION['admin_username']]);
            
            $response = [
                'success' => true,
                'new_total_price' => $new_grand_total,
                'new_days' => $new_days,
                'new_balance' => $new_balance,
                'price_difference' => $price_difference
            ];
        } else {
            $response = ['success' => false, 'message' => 'Database update failed'];
        }
        
        while (ob_get_level() > 0) {
            ob_end_clean();
        }
        echo json_encode($response);
        exit;
    }
    
    // Change car
    if(isset($_POST['change_car_ajax'])) {
        $id = (int)$_POST['id'];
        $new_car_id = (int)$_POST['new_car_id'];
        $reason = trim($_POST['reason']);
        
        $stmt = $pdo->prepare("SELECT pickup_date, pickup_time, dropoff_date, dropoff_time, car_id, total_price, paid_amount, selected_insurance_id, selected_options, total_days, status FROM reservations WHERE id = ?");
        $stmt->execute([$id]);
        $reservation = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if(!$reservation) {
            echo json_encode(['success' => false, 'message' => 'Reservation not found']);
            exit;
        }
        
        $old_car_id = $reservation['car_id'];
        $old_total_price = (float)$reservation['total_price'];
        $paid_amount = (float)$reservation['paid_amount'];
        $selected_insurance_id = $reservation['selected_insurance_id'];
        $selected_options = $reservation['selected_options'];
        $days = $reservation['total_days'];
        
        $availability = isCarAvailable($new_car_id, $reservation['pickup_date'], $reservation['pickup_time'], $reservation['dropoff_date'], $reservation['dropoff_time'], $pdo, $id, PREPARATION_HOURS);
        
        if(!$availability['available']) {
            echo json_encode(['success' => false, 'message' => 'New car is not available: ' . $availability['reason']]);
            exit;
        }
        
$price_data = calculateDynamicPrice($new_car_id, $reservation['pickup_date'], $reservation['pickup_time'], $reservation['dropoff_date'], $reservation['dropoff_time'], $pdo);
        $new_total_price = (float)$price_data['total_price'];
        
        // Recalculate extras with same days
        $extras_result = calculateExtrasTotal($selected_insurance_id, $selected_options, $days, $pdo);
        $extras_total = $extras_result['extras_total'];
        $selected_insurance_price = $extras_result['selected_insurance_price'];
        $new_grand_total = $new_total_price + $extras_total;
        
        $new_balance = $new_grand_total - $paid_amount;
        
        $stmtOld = $pdo->prepare("SELECT brand, model, license_plate FROM cars WHERE id = ?");
        $stmtOld->execute([$old_car_id]);
        $oldCar = $stmtOld->fetch();
        
        $stmtNew = $pdo->prepare("SELECT brand, model, license_plate FROM cars WHERE id = ?");
        $stmtNew->execute([$new_car_id]);
        $newCar = $stmtNew->fetch();
        
        $stmt = $pdo->prepare("UPDATE reservations SET car_id = ?, original_car_id = COALESCE(original_car_id, ?), total_price = ?, extras_total = ?, selected_insurance_price = ?, grand_total = ?, balance = ? WHERE id = ?");
        if($stmt->execute([$new_car_id, $old_car_id, $new_total_price, $extras_total, $selected_insurance_price, $new_grand_total, $new_balance, $id])) {
            $stmt2 = $pdo->prepare("INSERT INTO car_change_history (reservation_id, old_car_id, new_car_id, reason, changed_by) VALUES (?, ?, ?, ?, ?)");
            $stmt2->execute([$id, $old_car_id, $new_car_id, $reason, $_SESSION['admin_username']]);
            
            $price_diff = $new_grand_total - ($old_total_price + ($extras_total ?? 0));
            $price_text = $price_diff >= 0 ? "increased by €" . number_format($price_diff, 2) : "decreased by €" . number_format(abs($price_diff), 2);
            
            $stmt3 = $pdo->prepare("INSERT INTO reservation_notes (reservation_id, note, note_type, created_by) VALUES (?, ?, 'system', ?)");
            $stmt3->execute([$id, "Car changed from {$oldCar['brand']} {$oldCar['model']} ({$oldCar['license_plate']}) to {$newCar['brand']} {$newCar['model']} ({$newCar['license_plate']}). Reason: {$reason}. Price {$price_text}. New total: €" . number_format($new_grand_total, 2), $_SESSION['admin_username']]);
            
            echo json_encode(['success' => true, 'message' => 'Car changed successfully', 'new_total_price' => $new_grand_total, 'new_balance' => $new_balance]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to change car']);
        }
        exit;
    }
    
    // Add note
    if(isset($_POST['add_note_ajax'])) {
        $id = (int)$_POST['id'];
        $note = trim($_POST['note']);
        
        if(empty($note)) {
            echo json_encode(['success' => false, 'message' => 'Note cannot be empty']);
            exit;
        }
        
        $stmt = $pdo->prepare("INSERT INTO reservation_notes (reservation_id, note, note_type, created_by) VALUES (?, ?, 'internal', ?)");
        if($stmt->execute([$id, $note, $_SESSION['admin_username']])) {
            echo json_encode(['success' => true, 'message' => 'Note added']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to add note']);
        }
        exit;
    }
    
    // Delete reservation
    if(isset($_POST['delete_reservation_ajax'])) {
        $id = (int)$_POST['id'];
        
        $pdo->prepare("DELETE FROM payment_history WHERE reservation_id = ?")->execute([$id]);
        $pdo->prepare("DELETE FROM reservation_notes WHERE reservation_id = ?")->execute([$id]);
        $pdo->prepare("DELETE FROM car_change_history WHERE reservation_id = ?")->execute([$id]);
        
        $stmt = $pdo->prepare("DELETE FROM reservations WHERE id = ?");
        if($stmt->execute([$id])) {
            echo json_encode(['success' => true, 'message' => 'Reservation deleted']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Delete failed']);
        }
        exit;
    }
    
    // ============================================
    // UPDATE EXTRAS (Insurance & Additional Options)
    // ============================================
    if(isset($_POST['update_extras_ajax'])) {
        $id = (int)$_POST['id'];
        $selected_insurance_id = !empty($_POST['selected_insurance_id']) ? (int)$_POST['selected_insurance_id'] : null;
        $selected_options = !empty($_POST['selected_options']) ? $_POST['selected_options'] : null;
        
        // Get current reservation data
        $stmt = $pdo->prepare("SELECT total_price, paid_amount, grand_total, total_days FROM reservations WHERE id = ?");
        $stmt->execute([$id]);
        $current = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if(!$current) {
            echo json_encode(['success' => false, 'message' => 'Reservation not found']);
            exit;
        }
        
        $days = (int)$current['total_days'];
        $total_price = (float)$current['total_price'];
        $paid_amount = (float)$current['paid_amount'];
        $old_grand_total = (float)$current['grand_total'];
        
        // Calculate new extras total
        $extras_result = calculateExtrasTotal($selected_insurance_id, $selected_options, $days, $pdo);
        $extras_total = $extras_result['extras_total'];
        $selected_insurance_price = $extras_result['selected_insurance_price'];
        $new_grand_total = $total_price + $extras_total;
        
        // Recalculate balance
        $new_balance = $new_grand_total - $paid_amount;
        
        // Determine payment status
        if($new_balance <= 0) {
            $payment_status = 'paid';
        } elseif($paid_amount > 0) {
            $payment_status = 'partial';
        } else {
            $payment_status = 'unpaid';
        }
        
        // Update database
        $stmt = $pdo->prepare("UPDATE reservations SET 
            selected_insurance_id = ?,
            selected_insurance_price = ?,
            selected_options = ?,
            extras_total = ?,
            grand_total = ?,
            balance = ?,
            payment_status = ?
            WHERE id = ?");
        
        if($stmt->execute([$selected_insurance_id, $selected_insurance_price, $selected_options, $extras_total, $new_grand_total, $new_balance, $payment_status, $id])) {
            // Add note
            $diff = $new_grand_total - $old_grand_total;
            $diff_text = $diff >= 0 ? "increased by €" . number_format($diff, 2) : "decreased by €" . number_format(abs($diff), 2);
            $note_message = "🔄 EXTRAS UPDATED: Grand Total changed from €" . number_format($old_grand_total, 2) . " to €" . number_format($new_grand_total, 2) . " (" . $diff_text . ")";
            
            // Get insurance name
            $insurance_name = 'None';
            if($selected_insurance_id) {
                $ins_stmt = $pdo->prepare("SELECT name FROM insurance_types WHERE id = ?");
                $ins_stmt->execute([$selected_insurance_id]);
                $ins = $ins_stmt->fetch();
                $insurance_name = $ins ? $ins['name'] : 'Unknown';
            }
            $note_message .= " | Insurance: " . $insurance_name . " (€" . number_format($selected_insurance_price, 2) . ")";
            
            // Get options names
            if($selected_options) {
                $options_array = json_decode($selected_options, true);
                if(is_array($options_array) && count($options_array) > 0) {
                    $option_names = [];
                    foreach($options_array as $opt) {
                        $option_names[] = $opt['name'] . ' (x' . $opt['quantity'] . ')';
                    }
                    $note_message .= " | Options: " . implode(', ', $option_names);
                }
            }
            $note_message .= " | Extras Total: €" . number_format($extras_total, 2);
            
            $stmt2 = $pdo->prepare("INSERT INTO reservation_notes (reservation_id, note, note_type, created_by) VALUES (?, ?, 'system', ?)");
            $stmt2->execute([$id, $note_message, $_SESSION['admin_username']]);
            
            echo json_encode([
                'success' => true,
                'message' => 'Extras updated successfully!',
                'new_grand_total' => $new_grand_total,
                'new_balance' => $new_balance,
                'extras_total' => $extras_total,
                'selected_insurance_price' => $selected_insurance_price,
                'diff' => $diff
            ]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Update failed']);
        }
        exit;
    }
    
    // Get insurance types and options for Extras modal
    if(isset($_GET['get_extras_data'])) {
        $insurance_types = getInsuranceTypes($pdo);
        $additional_options = getAdditionalOptions($pdo);
        
        // Get current reservation extras
        $id = (int)$_GET['get_extras_data'];
        $stmt = $pdo->prepare("SELECT selected_insurance_id, selected_options, total_days FROM reservations WHERE id = ?");
        $stmt->execute([$id]);
        $res = $stmt->fetch(PDO::FETCH_ASSOC);
        
        echo json_encode([
            'success' => true,
            'insurance_types' => $insurance_types,
            'additional_options' => $additional_options,
            'selected_insurance_id' => $res ? $res['selected_insurance_id'] : null,
            'selected_options' => $res ? json_decode($res['selected_options'], true) : [],
            'total_days' => $res ? (int)$res['total_days'] : 0
        ]);
        exit;
    }
    
    echo json_encode(['success' => false, 'message' => 'Invalid AJAX request']);
    exit;
}

// ============================================
// SORTING PARAMETERS
// ============================================
$sort_column = isset($_GET['sort']) ? $_GET['sort'] : 'id';
$sort_order = isset($_GET['order']) && $_GET['order'] == 'desc' ? 'DESC' : 'ASC';
$next_order = ($sort_order == 'ASC') ? 'desc' : 'asc';

// Allowed sort columns to prevent SQL injection
$allowed_sort_columns = [
    'reservation_code', 'car_name', 'license_plate', 'customer_name', 
    'pickup_date', 'dropoff_date', 'total_price', 'balance', 'status', 'id'
];
if(!in_array($sort_column, $allowed_sort_columns)) {
    $sort_column = 'id';
    $sort_order = 'DESC';
}

// ============================================
// PAGINATION SETUP - PER PAGE BAZUAR NË TAB
// ============================================
$active_tab = isset($_GET['tab']) ? $_GET['tab'] : 'active';

// Default per_page bazuar në tab
if($active_tab == 'active') {
    $default_per_page = 50;
} else {
    $default_per_page = 25;
}

$per_page = isset($_GET['per_page']) ? (int)$_GET['per_page'] : $default_per_page;
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($page - 1) * $per_page;

// Get filter parameters
$status_filter = $_GET['status'] ?? '';
$date_filter = $_GET['date_filter'] ?? '';
$search = $_GET['search'] ?? '';

$today_date = date('Y-m-d');

// ============================================
// BUILD WHERE CLAUSE - TANI ME 3 TABS
// ============================================
$params = [];
$count_params = [];

if($active_tab == 'completed') {
    // Archive: Only reservations with status 'completed' AND payment_status 'paid'
    $where_conditions = ["r.status = 'completed'", "r.payment_status = 'paid'"];
    $params = [];
    $count_params = [];
} elseif($active_tab == 'cancelled') {
    // Cancelled: Only reservations with status 'cancelled'
    $where_conditions = ["r.status = 'cancelled'"];
    $params = [];
    $count_params = [];
} else {
    // Active: Everything that is NOT completed+paid AND NOT cancelled
    $where_conditions = ["NOT (r.status = 'completed' AND r.payment_status = 'paid')", "r.status != 'cancelled'"];
    $params = [];
    $count_params = [];
}

// Status filter only applies to Active tab (not for completed or cancelled)
if($active_tab == 'active' && $status_filter && $status_filter != 'all') {
    $where_conditions[] = "r.status = ?";
    $params[] = $status_filter;
    $count_params[] = $status_filter;
}

// Date filter only for Active tab
if($active_tab == 'active' && $date_filter) {
    if($date_filter == 'today') {
        $where_conditions[] = "r.pickup_date = CURDATE()";
    } elseif($date_filter == 'upcoming') {
        $where_conditions[] = "r.pickup_date > CURDATE()";
    } elseif($date_filter == 'past') {
        $where_conditions[] = "r.dropoff_date < CURDATE()";
    } elseif($date_filter == 'active') {
        $where_conditions[] = "r.pickup_date <= CURDATE() AND r.dropoff_date >= CURDATE()";
    }
}

if($search) {
    $where_conditions[] = "(r.reservation_code LIKE ? OR r.customer_name LIKE ? OR r.customer_email LIKE ? OR r.customer_phone LIKE ? OR c.brand LIKE ? OR c.model LIKE ? OR c.license_plate LIKE ?)";
    $search_param = "%$search%";
    for($i = 0; $i < 7; $i++) {
        $params[] = $search_param;
        $count_params[] = $search_param;
    }
}

$where_clause = implode(" AND ", $where_conditions);

// ============================================
// BUILD ORDER BY CLAUSE
// ============================================
$order_by_clause = "";
switch($sort_column) {
    case 'reservation_code':
        $order_by_clause = "ORDER BY r.reservation_code $sort_order";
        break;
    case 'car_name':
        $order_by_clause = "ORDER BY CONCAT(c.brand, ' ', c.model) $sort_order";
        break;
    case 'license_plate':
        $order_by_clause = "ORDER BY c.license_plate $sort_order";
        break;
    case 'customer_name':
        $order_by_clause = "ORDER BY r.customer_name $sort_order";
        break;
    case 'pickup_date':
        $order_by_clause = "ORDER BY r.pickup_date $sort_order, r.pickup_time $sort_order";
        break;
    case 'dropoff_date':
        $order_by_clause = "ORDER BY r.dropoff_date $sort_order, r.dropoff_time $sort_order";
        break;
    case 'total_price':
        $order_by_clause = "ORDER BY (r.grand_total) $sort_order";
        break;
    case 'balance':
        $order_by_clause = "ORDER BY (r.grand_total - r.paid_amount) $sort_order";
        break;
    case 'status':
        $order_by_clause = "ORDER BY r.status $sort_order";
        break;
    default:
        $order_by_clause = "ORDER BY r.id DESC";
        break;
}

// COUNT query for pagination
$count_sql = "SELECT COUNT(*) FROM reservations r LEFT JOIN cars c ON r.car_id = c.id WHERE $where_clause";
$count_stmt = $pdo->prepare($count_sql);
$count_stmt->execute($count_params);
$total_reservations = $count_stmt->fetchColumn();
$total_pages = ceil($total_reservations / $per_page);

// MAIN query with sorting and pagination
$sql = "SELECT r.*, c.brand, c.model, c.license_plate, c.image_url 
        FROM reservations r 
        LEFT JOIN cars c ON r.car_id = c.id 
        WHERE $where_clause
        $order_by_clause
        LIMIT $offset, $per_page";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$reservations = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ============================================
// STATS
// ============================================
$stats = [];
$stats['total'] = (int)$pdo->query("SELECT COUNT(*) FROM reservations")->fetchColumn();

// Active count: NOT completed+paid AND NOT cancelled
$active_stmt = $pdo->prepare("SELECT COUNT(*) FROM reservations WHERE NOT (status = 'completed' AND payment_status = 'paid') AND status != 'cancelled'");
$active_stmt->execute();
$stats['active_count'] = (int)$active_stmt->fetchColumn();

$completed_stmt = $pdo->prepare("SELECT COUNT(*) FROM reservations WHERE status = 'completed' AND payment_status = 'paid'");
$completed_stmt->execute();
$stats['completed_count'] = (int)$completed_stmt->fetchColumn();

$cancelled_stmt = $pdo->prepare("SELECT COUNT(*) FROM reservations WHERE status = 'cancelled'");
$cancelled_stmt->execute();
$stats['cancelled_count'] = (int)$cancelled_stmt->fetchColumn();

$status_stmt = $pdo->query("SELECT status, COUNT(*) as cnt FROM reservations GROUP BY status");
while($row = $status_stmt->fetch()) {
    $stats[$row['status']] = (int)$row['cnt'];
}
$stats['pending'] = $stats['pending'] ?? 0;
$stats['confirmed'] = $stats['confirmed'] ?? 0;
$stats['cancelled'] = $stats['cancelled'] ?? 0;
$stats['running'] = $stats['running'] ?? 0;
$stats['completed'] = $stats['completed'] ?? 0;

$today_stmt = $pdo->prepare("SELECT COUNT(*) FROM reservations WHERE pickup_date = ? AND status NOT IN ('cancelled', 'completed')");
$today_stmt->execute([$today_date]);
$stats['today'] = (int)$today_stmt->fetchColumn();

$active_rentals_stmt = $pdo->prepare("SELECT COUNT(*) FROM reservations WHERE status = 'running' AND status != 'cancelled'");
$active_rentals_stmt->execute();
$stats['active_rentals'] = (int)$active_rentals_stmt->fetchColumn();

$revenue_stmt = $pdo->query("SELECT COALESCE(SUM(paid_amount), 0) as revenue, COALESCE(SUM(CASE WHEN balance > 0 AND status NOT IN ('cancelled', 'completed') THEN balance ELSE 0 END), 0) as pending FROM reservations");
$revenue_data = $revenue_stmt->fetch();
$stats['total_revenue'] = (float)$revenue_data['revenue'];
$stats['pending_payments'] = (float)$revenue_data['pending'];

$all_cars = $pdo->query("SELECT id, brand, model, license_plate, status FROM cars ORDER BY brand LIMIT 500")->fetchAll();

$start_result = $offset + 1;
$end_result = min($offset + $per_page, $total_reservations);

// Helper function to generate sort URL
function sort_url($column) {
    global $sort_column, $sort_order, $status_filter, $date_filter, $search, $active_tab, $per_page;
    $new_order = 'asc';
    if($sort_column == $column) {
        $new_order = ($sort_order == 'ASC') ? 'desc' : 'asc';
    }
    $url = "?tab=" . $active_tab . "&sort=" . $column . "&order=" . $new_order . "&per_page=" . $per_page;
    if($status_filter && $active_tab == 'active') $url .= "&status=" . urlencode($status_filter);
    if($date_filter && $active_tab == 'active') $url .= "&date_filter=" . urlencode($date_filter);
    if($search) $url .= "&search=" . urlencode($search);
    return $url;
}

function sort_icon($column) {
    global $sort_column, $sort_order;
    if($sort_column == $column) {
        return $sort_order == 'ASC' ? '↑' : '↓';
    }
    return '↕';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reservations - Admin</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; }
        
        .sidebar {
            width: 260px;
            background: #1a1a2e;
            color: white;
            position: fixed;
            left: 0;
            top: 0;
            bottom: 0;
            overflow-y: auto;
        }
        
        .sidebar-header { padding: 24px 20px; border-bottom: 1px solid rgba(255,255,255,0.1); }
        .sidebar-header h2 { font-size: 18px; font-weight: 600; }
        .sidebar-nav { padding: 20px 0; }
        .sidebar-nav a {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 20px;
            color: #cbd5e1;
            text-decoration: none;
            font-size: 14px;
        }
        .sidebar-nav a i { width: 20px; }
        .sidebar-nav a:hover, .sidebar-nav a.active { background: #0066cc; color: white; }
        
        .main-content { margin-left: 260px; padding: 24px; }
        .page-header { margin-bottom: 24px; }
        .page-header h1 { font-size: 24px; font-weight: 600; }
        
        /* Tabs - më të vegjël */
        .tabs-container {
            background: white;
            border-radius: 12px;
            border: 1px solid #e5e7eb;
            margin-bottom: 20px;
            overflow: hidden;
        }
        .tabs {
            display: flex;
            border-bottom: 1px solid #e5e7eb;
            background: #f9fafb;
            padding: 2px;
        }
        .tab {
            padding: 8px 16px;
            font-size: 12px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s;
            border-bottom: 2px solid transparent;
            color: #6b7280;
            border-radius: 6px 6px 0 0;
        }
        .tab:hover { color: #0066cc; }
        .tab.active {
            color: #0066cc;
            border-bottom-color: #0066cc;
            background: white;
        }
        .tab-badge {
            background: #e5e7eb;
            color: #374151;
            border-radius: 20px;
            padding: 1px 6px;
            font-size: 10px;
            margin-left: 4px;
        }
        .tab.active .tab-badge { background: #0066cc; color: white; }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
            gap: 12px;
            margin-bottom: 20px;
        }
        .stat-card {
            background: white;
            padding: 12px;
            border-radius: 12px;
            border: 1px solid #e5e7eb;
            text-align: center;
            cursor: pointer;
            transition: all 0.2s;
        }
        .stat-card:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
        .stat-card h3 { font-size: 20px; font-weight: 700; margin-bottom: 2px; }
        .stat-card p { font-size: 11px; color: #6b7280; }
        
        .filters {
            background: white;
            padding: 12px 16px;
            border-radius: 12px;
            border: 1px solid #e5e7eb;
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            margin-bottom: 16px;
            align-items: flex-end;
        }
        .filter-group {
            display: flex;
            flex-direction: column;
            gap: 4px;
            flex: 1;
        }
        .filter-group label { font-size: 11px; font-weight: 500; color: #6b7280; }
        .filter-group select, .filter-group input {
            padding: 8px 10px;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            font-size: 13px;
            background: white;
        }
        .filter-group button {
            background: #0066cc;
            color: white;
            padding: 8px 16px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 500;
            font-size: 13px;
        }
        .filter-group button.reset { background: #6b7280; }
        
        .pagination-info {
            background: #f8fafc;
            padding: 10px 14px;
            border-radius: 8px;
            margin-bottom: 12px;
            font-size: 12px;
            color: #475569;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 10px;
        }
        .records-per-page select {
            padding: 4px 8px;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            background: white;
            font-size: 12px;
        }
        
        .reservations-table {
            background: white;
            border-radius: 12px;
            border: 1px solid #e5e7eb;
            overflow-x: auto;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            min-width: 1000px;
        }
        th, td {
            padding: 10px 12px;
            text-align: left;
            border-bottom: 1px solid #f0f0f0;
            font-size: 12px;
        }
        th {
            background: #f9fafb;
            font-weight: 600;
            position: sticky;
            top: 0;
        }
        th a {
            color: #374151;
            text-decoration: none;
            display: flex;
            align-items: center;
            gap: 4px;
            font-size: 11px;
        }
        th a:hover { color: #0066cc; }
        .sort-icon {
            font-size: 10px;
            color: #9ca3af;
        }
        
        .status-badge {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 20px;
            font-size: 10px;
            font-weight: 600;
        }
        .status-pending { background: #fef3c7; color: #92400e; }
        .status-confirmed { background: #dbeafe; color: #1e40af; }
        .status-cancelled { background: #fee2e2; color: #991b1b; }
        .status-running { background: #d1fae5; color: #065f46; }
        .status-completed { background: #e0e7ff; color: #3730a3; }
        .payment-paid { background: #d1fae5; color: #065f46; }
        .payment-unpaid { background: #fee2e2; color: #991b1b; }
        .payment-partial { background: #fef3c7; color: #92400e; }
        
        .license-plate-badge {
            background: #f3f4f6;
            padding: 2px 6px;
            border-radius: 4px;
            font-family: monospace;
            font-size: 10px;
            color: #1f2937;
            display: inline-block;
        }
        
        .refund-badge { background: #fee2e2; color: #dc2626; font-weight: 600; padding: 2px 6px; border-radius: 4px; font-size: 11px; }
        .balance-positive { color: #dc2626; font-weight: 600; font-size: 12px; }
        .balance-negative { color: #10b981; font-weight: 600; font-size: 12px; }
        
        .action-buttons { display: flex; gap: 4px; flex-wrap: wrap; }
        .btn-icon {
            padding: 6px 14px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 12px;
            font-weight: 500;
        }
        .btn-view { background: #0066cc; color: white; }
        .btn-pdf { background: #ec489a; color: white; }
        .btn-delete { background: #dc2626; color: white; }
        
        .pagination-container {
            display: flex;
            justify-content: center;
            gap: 6px;
            margin-top: 20px;
            flex-wrap: wrap;
        }
        .pagination-container a, .pagination-container span {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            min-width: 34px;
            padding: 6px 12px;
            background: white;
            border: 1px solid #e5e7eb;
            border-radius: 6px;
            text-decoration: none;
            color: #374151;
            font-size: 12px;
        }
        .pagination-container a:hover { background: #0066cc; color: white; border-color: #0066cc; }
        .pagination-container .active { background: #0066cc; color: white; border-color: #0066cc; }
        .pagination-container .disabled { opacity: 0.5; cursor: not-allowed; background: #f3f4f6; }
        
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        .modal-content {
            background: white;
            border-radius: 16px;
            width: 1100px;
            max-width: 95%;
            max-height: 90vh;
            overflow-y: auto;
        }
        .modal-header {
            padding: 14px 20px;
            border-bottom: 1px solid #e5e7eb;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
            border-radius: 16px 16px 0 0;
            position: sticky;
            top: 0;
        }
        .modal-header h3 { font-size: 17px; font-weight: 600; color: white; }
        .modal-header .close {
            cursor: pointer;
            font-size: 24px;
            color: rgba(255,255,255,0.7);
            line-height: 1;
            padding: 0 8px;
        }
        .modal-body { padding: 20px; max-height: 65vh; overflow-y: auto; }
        .modal-footer {
            padding: 14px 20px;
            border-top: 1px solid #e5e7eb;
            background: #f9fafb;
            border-radius: 0 0 16px 16px;
            display: flex;
            justify-content: flex-end;
            gap: 12px;
        }
        
        .details-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 20px;
        }
        .details-card {
            background: #f8fafc;
            border-radius: 12px;
            padding: 16px;
        }
        .details-card h4 {
            font-size: 13px;
            font-weight: 600;
            color: #1f2937;
            margin-bottom: 10px;
            padding-bottom: 6px;
            border-bottom: 1px solid #e5e7eb;
        }
        .detail-row {
            display: flex;
            justify-content: space-between;
            padding: 6px 0;
            font-size: 12px;
            border-bottom: 1px solid #eef2f6;
        }
        .detail-row:last-child { border-bottom: none; }
        .detail-label { color: #6b7280; font-weight: 500; }
        .detail-value { font-weight: 600; color: #1f2937; }
        
        /* Customer & Payment - i riorganizuar */
        .payment-summary-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 8px 16px;
        }
        .payment-summary-item {
            padding: 6px 0;
        }
        .payment-summary-item .label {
            font-size: 10px;
            color: #6b7280;
            text-transform: uppercase;
            letter-spacing: 0.3px;
        }
        .payment-summary-item .value {
            font-size: 14px;
            font-weight: 700;
            color: #1f2937;
        }
        .payment-summary-item .value.total {
            color: #0066cc;
            font-size: 16px;
        }
        .payment-summary-item .value.balance-due {
            color: #dc2626;
        }
        .payment-summary-item .value.refund-due {
            color: #10b981;
        }
        
        .customer-info-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 4px 12px;
        }
        .customer-info-item {
            padding: 4px 0;
        }
        .customer-info-item .label {
            font-size: 9px;
            color: #6b7280;
            text-transform: uppercase;
            letter-spacing: 0.3px;
        }
        .customer-info-item .value {
            font-size: 13px;
            font-weight: 500;
            color: #1f2937;
        }
        
        .extras-list {
            background: #f1f5f9;
            border-radius: 8px;
            padding: 10px;
            margin-top: 12px;
        }
        .extras-title {
            font-size: 10px;
            font-weight: 600;
            color: #475569;
            margin-bottom: 6px;
            padding-bottom: 4px;
            border-bottom: 1px solid #cbd5e1;
        }
        .extras-items {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 4px;
        }
        .extras-item {
            font-size: 10px;
            display: flex;
            justify-content: space-between;
            color: #334155;
            padding: 2px 0;
        }
        .extras-item span:first-child { font-weight: 500; }
        .extras-total {
            margin-top: 6px;
            padding-top: 4px;
            border-top: 1px solid #cbd5e1;
            font-weight: 600;
            display: flex;
            justify-content: space-between;
            font-size: 11px;
        }
        
        .action-buttons-grid-primary {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 10px;
            margin-bottom: 16px;
        }
        .action-btn-primary {
            background: linear-gradient(135deg, #0066cc 0%, #0052a3 100%);
            border: none;
            border-radius: 10px;
            padding: 10px;
            text-align: center;
            cursor: pointer;
            color: white;
        }
        .action-btn-primary i { font-size: 18px; display: block; margin-bottom: 4px; }
        .action-btn-primary span { font-size: 11px; font-weight: 500; }
        .action-btn-primary:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,102,204,0.3); }
        
        .action-buttons-grid-secondary {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 8px;
            margin-bottom: 16px;
            padding-top: 10px;
            border-top: 1px solid #e5e7eb;
        }
        .action-btn-secondary {
            background: #f3f4f6;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            padding: 8px;
            text-align: center;
            cursor: pointer;
            color: #4b5563;
        }
        .action-btn-secondary i { font-size: 14px; display: block; margin-bottom: 3px; }
        .action-btn-secondary span { font-size: 10px; font-weight: 500; }
        .action-btn-secondary:hover { background: #e5e7eb; }
        
        .sections-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-top: 8px;
        }
        .section-card {
            background: #f8fafc;
            border-radius: 12px;
            padding: 16px;
        }
        .section-card h4 {
            font-size: 13px;
            font-weight: 600;
            margin-bottom: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .section-card h4 button {
            background: #0066cc;
            color: white;
            border: none;
            padding: 3px 10px;
            border-radius: 20px;
            font-size: 10px;
            cursor: pointer;
        }
        .payment-list, .notes-list { max-height: 220px; overflow-y: auto; }
        .payment-item, .note-item {
            background: white;
            padding: 10px;
            border-radius: 8px;
            margin-bottom: 6px;
            border-left: 3px solid #10b981;
        }
        .payment-item.refund-payment { border-left-color: #dc2626; }
        .payment-amount.refund { color: #dc2626; }
        .note-system { border-left-color: #f59e0b; background: #fffbeb; }
        .payment-meta, .note-meta { font-size: 10px; color: #6b7280; margin-bottom: 4px; display: flex; justify-content: space-between; }
        .payment-amount { font-weight: 700; color: #10b981; font-size: 13px; }
        .note-text { font-size: 11px; color: #374151; white-space: pre-line; }
        .empty-text { text-align: center; color: #9ca3af; padding: 16px; font-size: 12px; }
        
        .form-group { margin-bottom: 14px; }
        .form-group label { display: block; margin-bottom: 4px; font-weight: 600; font-size: 11px; color: #374151; }
        .form-group input, .form-group select, .form-group textarea {
            width: 100%;
            padding: 8px 10px;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            font-size: 13px;
        }
        .form-row-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
        
        .btn-primary { background: #0066cc; color: white; padding: 8px 16px; border: none; border-radius: 8px; cursor: pointer; font-size: 13px; }
        .btn-secondary { background: #6b7280; color: white; padding: 8px 16px; border: none; border-radius: 8px; cursor: pointer; font-size: 13px; }
        
        .alert-success { background: #d1fae5; color: #065f46; padding: 10px 14px; border-radius: 8px; margin-bottom: 16px; font-size: 13px; }
        .alert-error { background: #fee2e2; color: #991b1b; padding: 10px 14px; border-radius: 8px; margin-bottom: 16px; font-size: 13px; }
        .info-note { background: #eff6ff; padding: 10px; border-radius: 8px; font-size: 12px; margin-top: 10px; }
        .availability-warning { background: #fef3c7; padding: 10px; border-radius: 8px; color: #92400e; font-size: 12px; margin-top: 10px; }
        
        .toast-notification {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: #10b981;
            color: white;
            padding: 10px 18px;
            border-radius: 8px;
            z-index: 2000;
            animation: slideIn 0.3s ease;
            font-size: 13px;
        }
        @keyframes slideIn {
            from { opacity: 0; transform: translateX(100px); }
            to { opacity: 1; transform: translateX(0); }
        }
        
        .loading-spinner { text-align: center; padding: 30px; }
        .reservation-code { font-family: monospace; font-weight: bold; color: #0066cc; font-size: 12px; }
        
        th a { text-decoration: none; color: #374151; display: inline-flex; align-items: center; gap: 3px; }
        th a:hover { color: #0066cc; }
        .sort-indicator { font-size: 10px; color: #9ca3af; }
        
        .info-highlight {
            background: #fef3c7;
            padding: 6px 10px;
            border-radius: 8px;
            margin-bottom: 12px;
            font-size: 11px;
            color: #92400e;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        /* Extras modal styles */
        .extras-modal-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        .extras-modal-col {
            background: #f8fafc;
            border-radius: 12px;
            border: 1px solid #e5e7eb;
            overflow: hidden;
        }
        .extras-modal-col-header {
            background: #f1f5f9;
            padding: 10px 14px;
            border-bottom: 1px solid #e5e7eb;
            font-weight: 600;
            font-size: 12px;
            color: #1e293b;
        }
        .extras-modal-col-body {
            padding: 10px;
            max-height: 280px;
            overflow-y: auto;
        }
        .insurance-option-modal, .option-item-modal {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 8px 10px;
            margin-bottom: 6px;
            background: white;
            border-radius: 8px;
            border: 1px solid #e5e7eb;
            transition: all 0.2s;
        }
        .insurance-option-modal {
            cursor: pointer;
        }
        .insurance-option-modal:hover, .option-item-modal:hover {
            border-color: #0066cc;
        }
        .insurance-option-modal input {
            margin-right: 10px;
        }
        .option-desc-modal {
            font-size: 10px;
            color: #6b7280;
            margin-top: 2px;
        }
        .option-icon-modal {
            width: 24px;
            font-size: 14px;
            color: #0066cc;
            text-align: center;
        }
        .option-price-badge-modal {
            font-weight: 600;
            color: #0066cc;
            font-size: 12px;
            min-width: 60px;
            text-align: right;
        }
        .option-price-badge-modal small {
            font-size: 8px;
            font-weight: normal;
            display: block;
        }
        .option-control-modal {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .option-quantity-modal {
            width: 60px;
            padding: 4px 6px;
            border-radius: 6px;
            border: 1px solid #e5e7eb;
            font-size: 12px;
        }
        .toggle-switch-modal {
            position: relative;
            display: inline-block;
            width: 40px;
            height: 20px;
        }
        .toggle-switch-modal input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        .toggle-slider-modal {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: 0.2s;
            border-radius: 20px;
        }
        .toggle-slider-modal:before {
            position: absolute;
            content: "";
            height: 14px;
            width: 14px;
            left: 3px;
            bottom: 3px;
            background-color: white;
            transition: 0.2s;
            border-radius: 50%;
        }
        .toggle-switch-modal input:checked + .toggle-slider-modal {
            background-color: #0066cc;
        }
        .toggle-switch-modal input:checked + .toggle-slider-modal:before {
            transform: translateX(20px);
        }
        .extras-summary-modal {
            background: linear-gradient(135deg, #0066cc 0%, #0052a3 100%);
            border-radius: 12px;
            padding: 14px 18px;
            margin-top: 14px;
        }
        .extras-summary-modal .summary-row {
            display: flex;
            justify-content: space-between;
            padding: 4px 0;
            color: white;
            font-size: 12px;
        }
        .extras-summary-modal .summary-row:not(:last-child) {
            border-bottom: 1px solid rgba(255,255,255,0.12);
        }
        .extras-summary-modal .total-row {
            font-weight: 700;
            font-size: 15px;
            padding-top: 6px;
            margin-top: 3px;
            border-top: 1px solid rgba(255,255,255,0.25);
        }
        
        @media (max-width: 1000px) {
            .sidebar { width: 100%; position: relative; height: auto; }
            .main-content { margin-left: 0; }
            .action-buttons-grid-primary,
            .action-buttons-grid-secondary {
                grid-template-columns: repeat(2, 1fr);
            }
            .extras-modal-grid {
                grid-template-columns: 1fr;
            }
            .payment-summary-grid {
                grid-template-columns: 1fr 1fr;
            }
            .customer-info-grid {
                grid-template-columns: 1fr;
            }
        }
        @media (max-width: 600px) {
            .action-buttons-grid-primary,
            .action-buttons-grid-secondary {
                grid-template-columns: 1fr 1fr;
            }
            .details-grid {
                grid-template-columns: 1fr;
            }
            .sections-grid {
                grid-template-columns: 1fr;
            }
            .payment-summary-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="sidebar">
        <div class="sidebar-header"><h2><i class="fas fa-car"></i> Car Rental Admin</h2></div>
        <div class="sidebar-nav">
            <a href="dashboard.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
            <a href="cars.php"><i class="fas fa-car"></i> Cars</a>
            <a href="create-reservation.php"><i class="fas fa-plus-square"></i> Create Reservation</a>
            <a href="reservations.php" class="active"><i class="fas fa-calendar-check"></i> Reservations</a>
            <a href="calendar.php"><i class="fas fa-calendar-alt"></i> Calendar</a>
            <a href="price-list.php"><i class="fas fa-tags"></i> Price Rules</a>
            <a href="extras.php"><i class="fas fa-cogs"></i> Extras</a>
            <a href="email-settings.php"><i class="fas fa-envelope"></i> Email Settings</a>
            <a href="settings.php"><i class="fas fa-cog"></i> Settings</a>
            <a href="manage-admins.php"><i class="fas fa-user-shield"></i> Users</a>
            <a href="clients.php"><i class="fas fa-users"></i> Clients</a>
            <a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </div>
    </div>
    
    <div class="main-content">
        <div class="page-header">
            <h1><i class="fas fa-calendar-check"></i> Reservations</h1>
        </div>
        
        <div class="tabs-container">
            <div class="tabs">
                <div class="tab <?php echo $active_tab == 'active' ? 'active' : ''; ?>" onclick="switchTab('active')">
                    <i class="fas fa-play-circle"></i> Active
                    <span class="tab-badge"><?php echo number_format($stats['active_count']); ?></span>
                </div>
                <div class="tab <?php echo $active_tab == 'cancelled' ? 'active' : ''; ?>" onclick="switchTab('cancelled')">
                    <i class="fas fa-times-circle"></i> Cancelled
                    <span class="tab-badge"><?php echo number_format($stats['cancelled_count']); ?></span>
                </div>
                <div class="tab <?php echo $active_tab == 'completed' ? 'active' : ''; ?>" onclick="switchTab('completed')">
                    <i class="fas fa-archive"></i> Archive
                    <span class="tab-badge"><?php echo number_format($stats['completed_count']); ?></span>
                </div>
            </div>
        </div>
        
        <?php if($active_tab == 'active'): ?>
        <div class="stats-grid">
            <div class="stat-card" onclick="filterByStatus('all')"><h3><?php echo number_format($stats['active_count']); ?></h3><p>Total Active</p></div>
            <div class="stat-card" onclick="filterByStatus('pending')"><h3><?php echo number_format($stats['pending']); ?></h3><p>Pending</p></div>
            <div class="stat-card" onclick="filterByStatus('confirmed')"><h3><?php echo number_format($stats['confirmed']); ?></h3><p>Confirmed</p></div>
            <div class="stat-card" onclick="filterByStatus('running')"><h3><?php echo number_format($stats['running']); ?></h3><p>Running</p></div>
            <div class="stat-card" onclick="filterByStatus('cancelled')"><h3><?php echo number_format($stats['cancelled']); ?></h3><p>Cancelled</p></div>
            <div class="stat-card" onclick="filterByDate('today')"><h3><?php echo number_format($stats['today']); ?></h3><p>Today Pickups</p></div>
            <div class="stat-card" onclick="filterByDate('active')"><h3><?php echo number_format($stats['active_rentals']); ?></h3><p>Currently Rented</p></div>
            <div class="stat-card"><h3>€<?php echo number_format($stats['total_revenue'], 0); ?></h3><p>Revenue</p></div>
            <div class="stat-card"><h3>€<?php echo number_format($stats['pending_payments'], 0); ?></h3><p>Pending</p></div>
        </div>
        <?php endif; ?>
        
        <div class="filters">
            <div class="filter-group"><label>Status</label>
                <select id="statusFilter" onchange="applyFilters()">
                    <option value="">All</option>
                    <?php if($active_tab == 'active'): ?>
                    <option value="pending">Pending</option>
                    <option value="confirmed">Confirmed</option>
                    <option value="running">Running</option>
                    <option value="cancelled">Cancelled</option>
                    <option value="completed">Completed</option>
                    <?php endif; ?>
                </select>
            </div>
            <?php if($active_tab == 'active'): ?>
            <div class="filter-group"><label>Date</label><select id="dateFilter" onchange="applyFilters()"><option value="">All</option><option value="today">Today Pickups</option><option value="active">Active Rentals</option><option value="upcoming">Upcoming</option><option value="past">Past</option></select></div>
            <?php endif; ?>
            <div class="filter-group"><label>Search</label><input type="text" id="searchInput" placeholder="Code, name, car, plate..." value="<?php echo htmlspecialchars($search); ?>"></div>
            <div class="filter-group"><button onclick="applyFilters()">Apply</button><button class="reset" onclick="resetFilters()">Reset</button></div>
        </div>
        
        <?php if($total_reservations > 0): ?>
        <div class="pagination-info">
            <span>Showing <?php echo $start_result; ?> - <?php echo $end_result; ?> of <?php echo number_format($total_reservations); ?> reservations</span>
            <div class="records-per-page">
                <span>Records per page:</span>
                <select id="perPageSelect" onchange="changePerPage()">
                    <option value="15" <?php echo $per_page == 15 ? 'selected' : ''; ?>>15</option>
                    <option value="25" <?php echo $per_page == 25 ? 'selected' : ''; ?>>25</option>
                    <option value="50" <?php echo $per_page == 50 ? 'selected' : ''; ?>>50</option>
                    <option value="100" <?php echo $per_page == 100 ? 'selected' : ''; ?>>100</option>
                </select>
            </div>
        </div>
        <?php endif; ?>
        
        <div class="reservations-table">
            <?php if(count($reservations) > 0): ?>
            <table id="reservationsTable">
                <thead>
                    <tr>
                        <th><a href="<?php echo sort_url('reservation_code'); ?>">Code <?php echo sort_icon('reservation_code'); ?></a></th>
                        <th><a href="<?php echo sort_url('car_name'); ?>">Car <?php echo sort_icon('car_name'); ?></a></th>
                        <th><a href="<?php echo sort_url('license_plate'); ?>">Plate <?php echo sort_icon('license_plate'); ?></a></th>
                        <th><a href="<?php echo sort_url('customer_name'); ?>">Customer <?php echo sort_icon('customer_name'); ?></a></th>
                        <th><a href="<?php echo sort_url('pickup_date'); ?>">Pickup <?php echo sort_icon('pickup_date'); ?></a></th>
                        <th><a href="<?php echo sort_url('dropoff_date'); ?>">Return <?php echo sort_icon('dropoff_date'); ?></a></th>
                        <th><a href="<?php echo sort_url('total_price'); ?>">Total <?php echo sort_icon('total_price'); ?></a></th>
                        <th><a href="<?php echo sort_url('balance'); ?>">Balance <?php echo sort_icon('balance'); ?></a></th>
                        <th><a href="<?php echo sort_url('status'); ?>">Status <?php echo sort_icon('status'); ?></a></th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($reservations as $r): 
                        $display_total = $r['grand_total'] ?? $r['total_price'];
                        $balance_value = (float)($r['grand_total'] ?? $r['total_price']) - (float)$r['paid_amount'];
                        if($balance_value < 0) {
                            $balance_class = 'refund-badge';
                            $balance_text = 'Refund: €' . number_format(abs($balance_value), 2);
                        } else {
                            $balance_class = 'balance-positive';
                            $balance_text = '€' . number_format($balance_value, 2);
                        }
                        
                        $is_overdue = ($r['status'] == 'running' && $r['dropoff_date'] < $today_date);
                    ?>
                    <tr id="row-<?php echo $r['id']; ?>" style="<?php echo $is_overdue ? 'background: #fff5f5;' : ''; ?>">
                        <td class="reservation-code"><?php echo htmlspecialchars($r['reservation_code']); ?></td>
                        <td><strong><?php echo htmlspecialchars($r['brand'] . ' ' . $r['model']); ?></strong></td>
                        <td><span class="license-plate-badge"><?php echo htmlspecialchars($r['license_plate']); ?></span></td>
                        <td><?php echo htmlspecialchars($r['customer_name']); ?><br><small><?php echo htmlspecialchars($r['customer_phone']); ?></small></td>
                        <td><?php echo date('d/m/Y', strtotime($r['pickup_date'])); ?><br><small><?php echo substr($r['pickup_time'], 0, 5); ?></small></td>
                        <td><?php echo date('d/m/Y', strtotime($r['dropoff_date'])); ?><br><small><?php echo substr($r['dropoff_time'], 0, 5); ?></small>
                            <?php if($is_overdue): ?>
                                <br><span style="color:#dc2626; font-size:9px;">⚠️ OVERDUE</span>
                            <?php endif; ?>
                        </td>
                        <td>€<?php echo number_format($display_total, 2); ?></td>
                        <td class="<?php echo $balance_class; ?>"><?php echo $balance_text; ?></td>
                        <td>
                            <span class="status-badge status-<?php echo $r['status']; ?>">
                                <?php echo ucfirst($r['status']); ?>
                            </span>
                            <br>
                            <span class="status-badge payment-<?php echo $r['payment_status']; ?>">
                                <?php echo $r['payment_status'] == 'partial' ? 'Partial' : ($r['payment_status'] == 'paid' ? 'Paid' : 'Unpaid'); ?>
                            </span>
                        </td>
<td class="action-buttons">
    <button class="btn-icon btn-view" onclick="viewReservation(<?php echo $r['id']; ?>)"><i class="fas fa-eye"></i> View</button>
    <button class="btn-icon btn-pdf" onclick="generatePDFInvoice(<?php echo $r['id']; ?>)"><i class="fas fa-file-pdf"></i> PDF</button>
    <?php if($user_role != 'worker'): ?>
        <button class="btn-icon btn-delete" onclick="deleteReservation(<?php echo $r['id']; ?>)"><i class="fas fa-trash"></i> Delete</button>
    <?php else: ?>
        <span class="btn-icon btn-delete" style="opacity:0.5; cursor:not-allowed; pointer-events:none;"><i class="fas fa-trash"></i> Delete</span>
    <?php endif; ?>
</td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <?php else: ?>
            <div style="text-align: center; padding: 30px; color: #6b7280;">
                <i class="fas fa-inbox" style="font-size: 32px; margin-bottom: 12px; display: block;"></i>
                <p>No reservations found</p>
            </div>
            <?php endif; ?>
        </div>
        
        <?php if($total_pages > 1): ?>
        <div class="pagination-container">
            <?php if($page > 1): ?>
                <a href="?tab=<?php echo $active_tab; ?>&page=1&per_page=<?php echo $per_page; ?>&sort=<?php echo $sort_column; ?>&order=<?php echo strtolower($sort_order); ?><?php echo ($status_filter && $active_tab == 'active') ? '&status=' . urlencode($status_filter) : ''; ?><?php echo ($date_filter && $active_tab == 'active') ? '&date_filter=' . urlencode($date_filter) : ''; ?><?php echo $search ? '&search=' . urlencode($search) : ''; ?>"><i class="fas fa-angle-double-left"></i></a>
                <a href="?tab=<?php echo $active_tab; ?>&page=<?php echo $page-1; ?>&per_page=<?php echo $per_page; ?>&sort=<?php echo $sort_column; ?>&order=<?php echo strtolower($sort_order); ?><?php echo ($status_filter && $active_tab == 'active') ? '&status=' . urlencode($status_filter) : ''; ?><?php echo ($date_filter && $active_tab == 'active') ? '&date_filter=' . urlencode($date_filter) : ''; ?><?php echo $search ? '&search=' . urlencode($search) : ''; ?>"><i class="fas fa-angle-left"></i> Prev</a>
            <?php else: ?>
                <span class="disabled"><i class="fas fa-angle-double-left"></i></span>
                <span class="disabled"><i class="fas fa-angle-left"></i> Prev</span>
            <?php endif; ?>
            
            <?php
            $start_page = max(1, $page - 2);
            $end_page = min($total_pages, $page + 2);
            if($start_page > 1): ?>
                <a href="?tab=<?php echo $active_tab; ?>&page=1&per_page=<?php echo $per_page; ?>&sort=<?php echo $sort_column; ?>&order=<?php echo strtolower($sort_order); ?><?php echo ($status_filter && $active_tab == 'active') ? '&status=' . urlencode($status_filter) : ''; ?><?php echo ($date_filter && $active_tab == 'active') ? '&date_filter=' . urlencode($date_filter) : ''; ?><?php echo $search ? '&search=' . urlencode($search) : ''; ?>">1</a>
                <?php if($start_page > 2): ?><span class="page-ellipsis">...</span><?php endif; ?>
            <?php endif; ?>
            
            <?php for($i = $start_page; $i <= $end_page; $i++): ?>
                <?php if($i == $page): ?>
                    <span class="active"><?php echo $i; ?></span>
                <?php else: ?>
                    <a href="?tab=<?php echo $active_tab; ?>&page=<?php echo $i; ?>&per_page=<?php echo $per_page; ?>&sort=<?php echo $sort_column; ?>&order=<?php echo strtolower($sort_order); ?><?php echo ($status_filter && $active_tab == 'active') ? '&status=' . urlencode($status_filter) : ''; ?><?php echo ($date_filter && $active_tab == 'active') ? '&date_filter=' . urlencode($date_filter) : ''; ?><?php echo $search ? '&search=' . urlencode($search) : ''; ?>"><?php echo $i; ?></a>
                <?php endif; ?>
            <?php endfor; ?>
            
            <?php if($end_page < $total_pages): ?>
                <?php if($end_page < $total_pages - 1): ?><span class="page-ellipsis">...</span><?php endif; ?>
                <a href="?tab=<?php echo $active_tab; ?>&page=<?php echo $total_pages; ?>&per_page=<?php echo $per_page; ?>&sort=<?php echo $sort_column; ?>&order=<?php echo strtolower($sort_order); ?><?php echo ($status_filter && $active_tab == 'active') ? '&status=' . urlencode($status_filter) : ''; ?><?php echo ($date_filter && $active_tab == 'active') ? '&date_filter=' . urlencode($date_filter) : ''; ?><?php echo $search ? '&search=' . urlencode($search) : ''; ?>"><?php echo $total_pages; ?></a>
            <?php endif; ?>
            
            <?php if($page < $total_pages): ?>
                <a href="?tab=<?php echo $active_tab; ?>&page=<?php echo $page+1; ?>&per_page=<?php echo $per_page; ?>&sort=<?php echo $sort_column; ?>&order=<?php echo strtolower($sort_order); ?><?php echo ($status_filter && $active_tab == 'active') ? '&status=' . urlencode($status_filter) : ''; ?><?php echo ($date_filter && $active_tab == 'active') ? '&date_filter=' . urlencode($date_filter) : ''; ?><?php echo $search ? '&search=' . urlencode($search) : ''; ?>">Next <i class="fas fa-angle-right"></i></a>
                <a href="?tab=<?php echo $active_tab; ?>&page=<?php echo $total_pages; ?>&per_page=<?php echo $per_page; ?>&sort=<?php echo $sort_column; ?>&order=<?php echo strtolower($sort_order); ?><?php echo ($status_filter && $active_tab == 'active') ? '&status=' . urlencode($status_filter) : ''; ?><?php echo ($date_filter && $active_tab == 'active') ? '&date_filter=' . urlencode($date_filter) : ''; ?><?php echo $search ? '&search=' . urlencode($search) : ''; ?>"><i class="fas fa-angle-double-right"></i></a>
            <?php else: ?>
                <span class="disabled">Next <i class="fas fa-angle-right"></i></span>
                <span class="disabled"><i class="fas fa-angle-double-right"></i></span>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>
    
    <!-- View Modal -->
    <div id="viewModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3><i class="fas fa-calendar-alt"></i> Reservation Details</h3>
                <span class="close" onclick="closeModal('viewModal')">&times;</span>
            </div>
            <div class="modal-body" id="viewContent">
                <div class="loading-spinner"><i class="fas fa-spinner fa-spin"></i><p>Loading...</p></div>
            </div>
            <div class="modal-footer">
                <button class="btn-secondary" onclick="closeModal('viewModal')">Close</button>
            </div>
        </div>
    </div>
    
    <!-- Edit Dates Modal -->
    <div id="datesModal" class="modal">
        <div class="modal-content" style="max-width: 500px;">
            <div class="modal-header"><h3><i class="fas fa-calendar-edit"></i> Edit Dates</h3><span class="close" onclick="closeModal('datesModal')">&times;</span></div>
            <div class="modal-body">
                <input type="hidden" id="dates_reservation_id">
                <div class="form-row-2">
                    <div class="form-group"><label>Pickup Date</label><input type="date" id="edit_pickup_date" required></div>
                    <div class="form-group"><label>Time</label><input type="time" id="edit_pickup_time" required></div>
                </div>
                <div class="form-row-2">
                    <div class="form-group"><label>Return Date</label><input type="date" id="edit_dropoff_date" required></div>
                    <div class="form-group"><label>Time</label><input type="time" id="edit_dropoff_time" required></div>
                </div>
                <div id="datesAvailabilityMsg" class="info-note" style="display:none;"></div>
            </div>
            <div class="modal-footer"><button class="btn-secondary" onclick="closeModal('datesModal')">Cancel</button><button class="btn-primary" onclick="saveDates()">Save</button></div>
        </div>
    </div>
    
    <!-- Edit Grand Total Modal -->
    <div id="grandTotalModal" class="modal">
        <div class="modal-content" style="max-width: 500px;">
            <div class="modal-header"><h3><i class="fas fa-tag"></i> Change Grand Total</h3><span class="close" onclick="closeModal('grandTotalModal')">&times;</span></div>
            <div class="modal-body">
                <input type="hidden" id="grandTotal_reservation_id">
                <div class="form-group">
                    <label>Current Grand Total</label>
                    <input type="text" id="current_grand_total" readonly style="background:#f3f4f6; font-weight:bold; color:#0066cc;">
                </div>
                <div class="form-group">
                    <label>Current Car Price</label>
                    <input type="text" id="current_car_price" readonly style="background:#f3f4f6;">
                </div>
                <div class="form-group">
                    <label>Current Extras Total</label>
                    <input type="text" id="current_extras_total" readonly style="background:#f3f4f6;">
                </div>
                <div class="form-group">
                    <label>New Grand Total (€)</label>
                    <input type="number" step="0.01" id="new_grand_total" placeholder="Enter new grand total" required>
                    <small style="display:block; margin-top:4px; color:#6b7280; font-size:11px;">
                        <i class="fas fa-info-circle"></i> 
                        If extras exist, the difference will be applied to extras. 
                        Otherwise, it will be applied to the car price.
                    </small>
                </div>
                <div class="availability-warning">
                    <i class="fas fa-exclamation-triangle"></i> 
                    Changing the grand total will automatically update the balance and payment status.
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn-secondary" onclick="closeModal('grandTotalModal')">Cancel</button>
                <button class="btn-primary" onclick="saveGrandTotal()">Update Grand Total</button>
            </div>
        </div>
    </div>
    
    <!-- Add Payment Modal -->
    <div id="paymentModal" class="modal">
        <div class="modal-content" style="max-width: 450px;">
            <div class="modal-header"><h3><i class="fas fa-money-bill-wave"></i> Add Payment</h3><span class="close" onclick="closeModal('paymentModal')">&times;</span></div>
            <div class="modal-body">
                <input type="hidden" id="payment_reservation_id">
                <div class="form-group"><label>Amount (€)</label><input type="number" step="0.01" id="payment_amount" placeholder="Enter amount (negative for refund)"></div>
                <div class="form-group"><label>Method</label><select id="payment_method"><option value="cash">Cash</option><option value="card">Card</option><option value="bank">Bank Transfer</option><option value="online">Online</option></select></div>
                <div class="form-group"><label>Notes</label><textarea id="payment_notes" rows="2" placeholder="Optional notes..."></textarea></div>
                <div class="info-note"><i class="fas fa-info-circle"></i> Use negative amount for refund (e.g., -50 for €50 refund)</div>
            </div>
            <div class="modal-footer"><button class="btn-secondary" onclick="closeModal('paymentModal')">Cancel</button><button class="btn-primary" onclick="savePayment()">Process</button></div>
        </div>
    </div>
    
    <!-- Change Car Modal -->
    <div id="carModal" class="modal">
        <div class="modal-content" style="max-width: 500px;">
            <div class="modal-header"><h3><i class="fas fa-exchange-alt"></i> Change Car</h3><span class="close" onclick="closeModal('carModal')">&times;</span></div>
            <div class="modal-body">
                <input type="hidden" id="car_reservation_id">
                <div class="form-group"><label>New Car</label><select id="new_car_id" onchange="checkCarAvailability()"><option value="">Select car...</option><?php foreach($all_cars as $car): ?><option value="<?php echo $car['id']; ?>" data-status="<?php echo $car['status']; ?>"><?php echo htmlspecialchars($car['brand'] . ' ' . $car['model'] . ' (' . $car['license_plate'] . ')'); ?></option><?php endforeach; ?></select></div>
                <div id="carAvailabilityMsg" class="info-note" style="display:none;"></div>
                <div class="form-group"><label>Reason for change</label><textarea id="change_reason" rows="2" placeholder="Why changing the car?"></textarea></div>
            </div>
            <div class="modal-footer"><button class="btn-secondary" onclick="closeModal('carModal')">Cancel</button><button class="btn-primary" id="changeCarBtn" onclick="saveCarChange()" disabled>Change</button></div>
        </div>
    </div>
    
    <!-- Add Note Modal -->
    <div id="noteModal" class="modal">
        <div class="modal-content" style="max-width: 450px;">
            <div class="modal-header"><h3><i class="fas fa-sticky-note"></i> Add Note</h3><span class="close" onclick="closeModal('noteModal')">&times;</span></div>
            <div class="modal-body">
                <input type="hidden" id="note_reservation_id">
                <div class="form-group"><label>Note</label><textarea id="note_text" rows="4" placeholder="Write your note here..."></textarea></div>
            </div>
            <div class="modal-footer"><button class="btn-secondary" onclick="closeModal('noteModal')">Cancel</button><button class="btn-primary" onclick="saveNote()">Add</button></div>
        </div>
    </div>
    
    <!-- Change Status Modal -->
    <div id="statusModal" class="modal">
        <div class="modal-content" style="max-width: 400px;">
            <div class="modal-header"><h3><i class="fas fa-edit"></i> Change Status</h3><span class="close" onclick="closeModal('statusModal')">&times;</span></div>
            <div class="modal-body">
                <input type="hidden" id="status_reservation_id">
                <div class="form-group"><label>Status</label>
                    <select id="edit_status">
                        <option value="pending">Pending</option>
                        <option value="confirmed">Confirmed</option>
                        <option value="running">Running</option>
                        <option value="completed">Completed</option>
                        <option value="cancelled">Cancelled</option>
                    </select>
                    <small style="display: block; margin-top: 6px; color: #6b7280; font-size:11px;">
                        <i class="fas fa-info-circle"></i> To mark as "Completed", payment must be "Paid"
                    </small>
                </div>
            </div>
            <div class="modal-footer"><button class="btn-secondary" onclick="closeModal('statusModal')">Cancel</button><button class="btn-primary" onclick="saveStatus()">Save</button></div>
        </div>
    </div>
    
    <!-- Edit Extras Modal -->
    <div id="extrasModal" class="modal">
        <div class="modal-content" style="max-width: 900px;">
            <div class="modal-header"><h3><i class="fas fa-cogs"></i> Edit Extras</h3><span class="close" onclick="closeModal('extrasModal')">&times;</span></div>
            <div class="modal-body">
                <input type="hidden" id="extras_reservation_id">
                <input type="hidden" id="extras_total_days" value="0">
                <input type="hidden" id="extras_selected_insurance" value="">
                <input type="hidden" id="extras_selected_options" value="">
                <div id="extrasLoading" class="loading-spinner"><i class="fas fa-spinner fa-spin"></i><p>Loading...</p></div>
                <div id="extrasContent" style="display:none;">
                    <div class="extras-modal-grid">
                        <div class="extras-modal-col">
                            <div class="extras-modal-col-header"><i class="fas fa-shield-alt"></i> Insurance</div>
                            <div class="extras-modal-col-body" id="extrasInsuranceList"></div>
                        </div>
                        <div class="extras-modal-col">
                            <div class="extras-modal-col-header"><i class="fas fa-plus-circle"></i> Extra Options</div>
                            <div class="extras-modal-col-body" id="extrasOptionsList"></div>
                        </div>
                    </div>
                    <div class="extras-summary-modal" id="extrasSummaryModal">
                        <div class="summary-row"><span>Car Price:</span><span id="extrasCarPrice">€0.00</span></div>
                        <div class="summary-row"><span>Insurance:</span><span id="extrasInsuranceSummary">€0.00</span></div>
                        <div class="summary-row"><span>Extra Options:</span><span id="extrasOptionsSummary">€0.00</span></div>
                        <div class="summary-row total-row"><span>New Grand Total:</span><span id="extrasNewGrandTotal">€0.00</span></div>
                        <div class="summary-row" style="font-size:11px; opacity:0.8; border-top:1px solid rgba(255,255,255,0.2); padding-top:6px; margin-top:3px;">
                            <span>Days: <span id="extrasDaysDisplay">0</span></span>
                            <span>Difference: <span id="extrasDiffDisplay">€0.00</span></span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn-secondary" onclick="closeModal('extrasModal')">Cancel</button>
                <button class="btn-primary" id="saveExtrasBtn" onclick="saveExtras()" style="display:none;">Save Extras</button>
            </div>
        </div>
    </div>
    
    <script>
        let currentCarPriceForExtras = 0;
        let oldGrandTotalForExtras = 0;
        
        function showToast(message, isError) {
            const toast = document.createElement('div');
            toast.className = 'toast-notification';
            toast.style.background = isError ? '#dc2626' : '#10b981';
            toast.innerHTML = '<i class="fas ' + (isError ? 'fa-exclamation-circle' : 'fa-check-circle') + '"></i> ' + message;
            document.body.appendChild(toast);
            setTimeout(() => toast.remove(), 3000);
        }
        
        function switchTab(tab) {
            const url = new URL(window.location.href);
            url.searchParams.set('tab', tab);
            url.searchParams.delete('status');
            url.searchParams.delete('date_filter');
            url.searchParams.delete('page');
            url.searchParams.delete('sort');
            url.searchParams.delete('order');
            // Per page default bazuar në tab
            if(tab === 'active') {
                url.searchParams.set('per_page', 50);
            } else {
                url.searchParams.set('per_page', 25);
            }
            window.location.href = url.toString();
        }
        
        function applyFilters() {
            const status = document.getElementById('statusFilter').value;
            const date = document.getElementById('dateFilter').value;
            const search = document.getElementById('searchInput').value;
            const tab = '<?php echo $active_tab; ?>';
            const perPage = document.getElementById('perPageSelect')?.value || 50;
            const sort = '<?php echo $sort_column; ?>';
            const order = '<?php echo strtolower($sort_order); ?>';
            let url = `?tab=${tab}&per_page=${perPage}&sort=${sort}&order=${order}`;
            if(tab === 'active') {
                if(status) url += `&status=${encodeURIComponent(status)}`;
                if(date) url += `&date_filter=${encodeURIComponent(date)}`;
            }
            if(search) url += `&search=${encodeURIComponent(search)}`;
            window.location.href = url;
        }
        
        function resetFilters() { 
            const tab = '<?php echo $active_tab; ?>';
            const defaultPerPage = tab === 'active' ? 50 : 25;
            window.location.href = `?tab=${tab}&per_page=${defaultPerPage}`; 
        }
        
        function changePerPage() {
            const perPage = document.getElementById('perPageSelect').value;
            const url = new URL(window.location.href);
            url.searchParams.set('per_page', perPage);
            url.searchParams.set('page', 1);
            window.location.href = url.toString();
        }
        
        function filterByStatus(s) { 
            const tab = '<?php echo $active_tab; ?>';
            const perPage = document.getElementById('perPageSelect')?.value || 50;
            if(s === 'all') {
                window.location.href = `?tab=${tab}&per_page=${perPage}`;
            } else {
                window.location.href = `?tab=${tab}&status=${s}&per_page=${perPage}`;
            }
        }
        
        function filterByDate(d) { 
            const tab = '<?php echo $active_tab; ?>';
            const perPage = document.getElementById('perPageSelect')?.value || 50;
            window.location.href = `?tab=${tab}&date_filter=${d}&per_page=${perPage}`; 
        }
        
        function escapeHtml(t) { if(!t) return ''; const d = document.createElement('div'); d.textContent = t; return d.innerHTML; }
        
        function viewReservation(id) {
            fetch(`?ajax=1&get_reservation=${id}`)
                .then(res => res.json())
                .then(data => {
                    if(data.success){
                        const r = data.reservation;
                        let paymentsHtml = '', notesHtml = '';
                        let extrasItemsHtml = '';
                        let insurancePrice = parseFloat(r.selected_insurance_price || 0);
                        let extrasTotal = parseFloat(r.extras_total || 0);
                        let carTotal = parseFloat(r.total_price || 0);
                        let displayTotal = parseFloat(r.grand_total || carTotal);
                        let paidAmount = parseFloat(r.paid_amount || 0);
                        let balanceValue = displayTotal - paidAmount;
                        let balanceClass = balanceValue < 0 ? 'refund-due' : 'balance-due';
                        let balanceText = balanceValue < 0 ? 'Refund: €' + Math.abs(balanceValue).toFixed(2) : '€' + balanceValue.toFixed(2);
                        
                        let insuranceName = 'Basic Insurance';
                        if(r.selected_insurance_id) {
                            insuranceName = r.insurance_name || 'Insurance';
                        }
                        let insuranceDisplay = insuranceName + ' (€' + insurancePrice.toFixed(2) + ')';
                        
                        if(data.payments && data.payments.length > 0){
                            data.payments.forEach(p => {
                                let amountValue = parseFloat(p.amount);
                                let isRefund = amountValue < 0;
                                paymentsHtml += `<div class="payment-item ${isRefund ? 'refund-payment' : ''}">
                                    <div class="payment-meta"><span>${p.created_at}</span><span>${p.payment_method}</span></div>
                                    <div class="payment-amount ${isRefund ? 'refund' : ''}">€${amountValue.toFixed(2)}</div>
                                    <div class="payment-meta">${escapeHtml(p.notes || '-')}</div>
                                </div>`;
                            });
                        } else {
                            paymentsHtml = '<div class="empty-text">No payments</div>';
                        }
                        
                        if(data.notes && data.notes.length > 0){
                            data.notes.forEach(n => {
                                let noteClass = n.note_type === 'system' ? 'note-system' : '';
                                notesHtml += `<div class="note-item ${noteClass}">
                                    <div class="note-meta"><span><i class="fas fa-user"></i> ${escapeHtml(n.created_by || 'System')}</span><span>${n.created_at}</span></div>
                                    <div class="note-text">${escapeHtml(n.note)}</div>
                                </div>`;
                            });
                        } else {
                            notesHtml = '<div class="empty-text">No notes</div>';
                        }
                        
                        if(r.selected_options) {
                            try {
                                const options = JSON.parse(r.selected_options);
                                if(options.length > 0) {
                                    options.forEach(opt => {
                                        let price = parseFloat(opt.price || 0);
                                        if(price > 0) {
                                            extrasItemsHtml += `<div class="extras-item">
                                                <span>${escapeHtml(opt.name)} (${opt.quantity}x):</span>
                                                <span>€${price.toFixed(2)}</span>
                                            </div>`;
                                        }
                                    });
                                }
                            } catch(e) {}
                        }
                        
                        let hasExtras = (extrasTotal > 0) || (extrasItemsHtml !== '') || (insurancePrice > 0);
                        
                        // Rental Information
                        let rentalInfoHtml = `
                            <div class="detail-row"><span class="detail-label">Code:</span><span class="detail-value">${escapeHtml(r.reservation_code)}</span></div>
                            <div class="detail-row"><span class="detail-label">Vehicle:</span><span class="detail-value">${escapeHtml(r.brand)} ${escapeHtml(r.model)}</span></div>
                            <div class="detail-row"><span class="detail-label">Plate:</span><span class="detail-value">${escapeHtml(r.license_plate)}</span></div>
                            <div class="detail-row"><span class="detail-label">Pickup:</span><span class="detail-value">${r.pickup_date} at ${r.pickup_time.substring(0,5)}</span></div>
                            <div class="detail-row"><span class="detail-label">Return:</span><span class="detail-value">${r.dropoff_date} at ${r.dropoff_time.substring(0,5)}</span></div>
                            <div class="detail-row"><span class="detail-label">Duration:</span><span class="detail-value">${r.total_days} days</span></div>
                            <div class="detail-row"><span class="detail-label">Location:</span><span class="detail-value">${escapeHtml(r.pickup_location)} → ${escapeHtml(r.dropoff_location)}</span></div>
                            <div class="detail-row"><span class="detail-label">Insurance:</span><span class="detail-value">${insuranceDisplay}</span></div>
                            <div class="detail-row"><span class="detail-label">Created:</span><span class="detail-value">${r.created_at}</span></div>
                        `;
                        
                        // Customer & Payment - i riorganizuar
                        let customerPaymentHtml = `
                            <div class="customer-info-grid">
                                <div class="customer-info-item">
                                    <div class="label">Name</div>
                                    <div class="value">${escapeHtml(r.customer_name)}</div>
                                </div>
                                <div class="customer-info-item">
                                    <div class="label">Phone</div>
                                    <div class="value">${escapeHtml(r.customer_phone)}</div>
                                </div>
                                <div class="customer-info-item">
                                    <div class="label">Email</div>
                                    <div class="value">${escapeHtml(r.customer_email)}</div>
                                </div>
                                <div class="customer-info-item">
                                    <div class="label">Status</div>
                                    <div class="value">
                                        <span class="status-badge status-${r.status}">${r.status}</span>
                                        <span class="status-badge payment-${r.payment_status}">${r.payment_status == 'partial' ? 'Partial' : (r.payment_status == 'paid' ? 'Paid' : 'Unpaid')}</span>
                                    </div>
                                </div>
                            </div>
                            <div style="margin-top: 12px; padding-top: 10px; border-top: 1px solid #e5e7eb;">
                                <div class="payment-summary-grid">
                                    <div class="payment-summary-item">
                                        <div class="label">Car Total</div>
                                        <div class="value">€${carTotal.toFixed(2)}</div>
                                    </div>
                                    <div class="payment-summary-item">
                                        <div class="label">Extras Total</div>
                                        <div class="value">€${extrasTotal.toFixed(2)}</div>
                                    </div>
                                    <div class="payment-summary-item">
                                        <div class="label">Grand Total</div>
                                        <div class="value total">€${displayTotal.toFixed(2)}</div>
                                    </div>
                                    <div class="payment-summary-item">
                                        <div class="label">Paid Amount</div>
                                        <div class="value">€${paidAmount.toFixed(2)}</div>
                                    </div>
                                    <div class="payment-summary-item" style="grid-column: span 2;">
                                        <div class="label">${balanceValue < 0 ? 'Refund Due' : 'Balance Due'}</div>
                                        <div class="value ${balanceClass}">${balanceText}</div>
                                    </div>
                                </div>
                            </div>
                            ${hasExtras ? `
                            <div class="extras-list" style="margin-top: 12px;">
                                <div class="extras-title"><i class="fas fa-cogs"></i> Extras Breakdown</div>
                                <div class="extras-items">
                                    ${insurancePrice > 0 ? `<div class="extras-item"><span>${insuranceName}:</span><span>€${insurancePrice.toFixed(2)}</span></div>` : `<div class="extras-item"><span>${insuranceName}:</span><span>€0.00</span></div>`}
                                    ${extrasItemsHtml}
                                </div>
                                <div class="extras-total">
                                    <span>Total Extras:</span>
                                    <span>€${extrasTotal.toFixed(2)}</span>
                                </div>
                            </div>
                            ` : ''}
                        `;
                        
                        let html = `
                            <div class="details-grid">
                                <div class="details-card">
                                    <h4><i class="fas fa-info-circle"></i> Rental Information</h4>
                                    ${rentalInfoHtml}
                                </div>
                                
                                <div class="details-card">
                                    <h4><i class="fas fa-user"></i> Customer & Payment</h4>
                                    ${customerPaymentHtml}
                                </div>
                            </div>
                            
                            <div class="action-buttons-grid-primary">
                                <div class="action-btn-primary" onclick="openStatusModal(${r.id}, '${r.status}')"><i class="fas fa-exchange-alt"></i><span>Status</span></div>
                                <div class="action-btn-primary" onclick="openPaymentModal(${r.id})"><i class="fas fa-money-bill-wave"></i><span>Payment</span></div>
                                <div class="action-btn-primary" onclick="openNoteModal(${r.id})"><i class="fas fa-sticky-note"></i><span>Note</span></div>
                                <div class="action-btn-primary" onclick="generatePDFInvoice(${r.id})"><i class="fas fa-file-pdf"></i><span>PDF</span></div>
                            </div>
                            
                            <div class="action-buttons-grid-secondary">
                                <div class="action-btn-secondary" onclick="openDatesModal(${r.id}, '${r.pickup_date}', '${r.pickup_time}', '${r.dropoff_date}', '${r.dropoff_time}')"><i class="fas fa-calendar-alt"></i><span>Dates</span></div>
                                <div class="action-btn-secondary" onclick="openGrandTotalModal(${r.id}, ${displayTotal}, ${carTotal}, ${extrasTotal})"><i class="fas fa-tag"></i><span>Grand Total</span></div>
                                <div class="action-btn-secondary" onclick="openCarModal(${r.id})"><i class="fas fa-car"></i><span>Car</span></div>
                                <div class="action-btn-secondary" onclick="openEditCustomerModal(${r.id})"><i class="fas fa-user-edit"></i><span>Customer</span></div>
                                <div class="action-btn-secondary" onclick="openExtrasModal(${r.id})"><i class="fas fa-cogs"></i><span>Extras</span></div>
                            </div>
                            
                            <div class="sections-grid">
                                <div class="section-card">
                                    <h4><i class="fas fa-credit-card"></i> Payments <button onclick="openPaymentModal(${r.id})">+</button></h4>
                                    <div class="payment-list">${paymentsHtml}</div>
                                </div>
                                <div class="section-card">
                                    <h4><i class="fas fa-comments"></i> Notes <button onclick="openNoteModal(${r.id})">+</button></h4>
                                    <div class="notes-list">${notesHtml}</div>
                                </div>
                            </div>
                        `;
                        
                        document.getElementById('viewContent').innerHTML = html;
                        openModal('viewModal');
                    } else {
                        showToast('Error loading details', true);
                    }
                })
                .catch(err => showToast('Error: ' + err.message, true));
        }
        
        // ============================================
        // OPEN EXTRAS MODAL
        // ============================================
        function openExtrasModal(id) {
            document.getElementById('extras_reservation_id').value = id;
            document.getElementById('extrasLoading').style.display = 'block';
            document.getElementById('extrasContent').style.display = 'none';
            document.getElementById('saveExtrasBtn').style.display = 'none';
            openModal('extrasModal');
            
            fetch(`?ajax=1&get_extras_data=${id}`)
                .then(res => res.json())
                .then(data => {
                    if(data.success) {
                        document.getElementById('extras_total_days').value = data.total_days || 0;
                        document.getElementById('extrasDaysDisplay').innerText = data.total_days || 0;
                        
                        fetch(`?ajax=1&get_reservation=${id}`)
                            .then(res => res.json())
                            .then(resData => {
                                if(resData.success) {
                                    const r = resData.reservation;
                                    const carPrice = parseFloat(r.total_price || 0);
                                    currentCarPriceForExtras = carPrice;
                                    oldGrandTotalForExtras = parseFloat(r.grand_total || carPrice);
                                    
                                    document.getElementById('extrasCarPrice').innerText = '€' + carPrice.toFixed(2);
                                    document.getElementById('extrasCarPrice').dataset.value = carPrice;
                                    
                                    renderExtrasInsurance(data.insurance_types, data.selected_insurance_id, data.total_days);
                                    renderExtrasOptions(data.additional_options, data.selected_options, data.total_days);
                                    
                                    document.getElementById('extrasLoading').style.display = 'none';
                                    document.getElementById('extrasContent').style.display = 'block';
                                    document.getElementById('saveExtrasBtn').style.display = 'inline-block';
                                    
                                    calculateExtrasSummary();
                                }
                            });
                    } else {
                        showToast('Error loading extras data', true);
                        document.getElementById('extrasLoading').innerHTML = '<p style="color:red;">Error loading data</p>';
                    }
                })
                .catch(err => {
                    showToast('Error: ' + err.message, true);
                    document.getElementById('extrasLoading').innerHTML = '<p style="color:red;">Error loading data</p>';
                });
        }
        
        // ============================================
        // RENDER EXTRAS INSURANCE
        // ============================================
        function renderExtrasInsurance(insuranceTypes, selectedId, days) {
            const container = document.getElementById('extrasInsuranceList');
            if(!insuranceTypes || insuranceTypes.length === 0) {
                container.innerHTML = '<div style="text-align:center;padding:16px;color:#6b7280;font-size:12px;">No insurance types</div>';
                return;
            }
            
            let html = '';
            let hasSelected = false;
            insuranceTypes.forEach(ins => {
                const checked = (selectedId && selectedId == ins.id) ? 'checked' : '';
                if(checked) hasSelected = true;
                let priceDisplay = '';
                if(ins.is_daily) {
                    priceDisplay = '€' + parseFloat(ins.price_per_day || 0).toFixed(2) + ' <small>/day</small>';
                } else {
                    priceDisplay = '€' + parseFloat(ins.price_one_time || 0).toFixed(2) + ' <small>once</small>';
                }
                if(parseFloat(ins.price_per_day || 0) === 0 && ins.is_daily) {
                    priceDisplay = 'Free <small>/day</small>';
                }
                html += `
                    <label class="insurance-option-modal" style="cursor:pointer;">
                        <div style="display:flex;align-items:center;gap:10px;flex:1;">
                            <input type="radio" name="extras_insurance" value="${ins.id}" 
                                   data-price-daily="${ins.price_per_day}" 
                                   data-price-one="${ins.price_one_time}" 
                                   data-is-daily="${ins.is_daily}" 
                                   ${checked}
                                   onchange="calculateExtrasSummary()">
                            <div>
                                <strong style="font-size:12px;">${escapeHtml(ins.name)}</strong>
                                ${ins.description ? `<p class="option-desc-modal">${escapeHtml(ins.description)}</p>` : ''}
                            </div>
                        </div>
                        <div class="option-price-badge-modal">${priceDisplay}</div>
                    </label>
                `;
            });
            container.innerHTML = html;
            
            if(!hasSelected && insuranceTypes.length > 0) {
                const firstRadio = container.querySelector('input[name="extras_insurance"]');
                if(firstRadio) {
                    firstRadio.checked = true;
                    setTimeout(calculateExtrasSummary, 50);
                }
            }
        }
        
        // ============================================
        // RENDER EXTRAS OPTIONS
        // ============================================
        function renderExtrasOptions(options, selectedOptions, days) {
            const container = document.getElementById('extrasOptionsList');
            if(!options || options.length === 0) {
                container.innerHTML = '<div style="text-align:center;padding:16px;color:#6b7280;font-size:12px;">No options available</div>';
                return;
            }
            
            const selectedMap = {};
            if(selectedOptions && Array.isArray(selectedOptions)) {
                selectedOptions.forEach(opt => {
                    selectedMap[opt.id] = opt.quantity || 1;
                });
            }
            
            let html = '';
            options.forEach(opt => {
                const isDaily = opt.is_daily == 1;
                const maxQty = parseInt(opt.max_quantity || 1);
                const useToggle = (maxQty == 1);
                const selectedQty = selectedMap[opt.id] || 0;
                const isChecked = selectedQty > 0;
                
                let priceDisplay = '';
                if(isDaily) {
                    priceDisplay = '€' + parseFloat(opt.price_per_day || 0).toFixed(2) + ' <small>/day</small>';
                } else {
                    priceDisplay = '€' + parseFloat(opt.price_one_time || 0).toFixed(2) + ' <small>once</small>';
                }
                if(parseFloat(opt.price_per_day || 0) === 0 && isDaily) {
                    priceDisplay = 'Free <small>/day</small>';
                }
                
                html += `
                    <div class="option-item-modal">
                        <div style="display:flex;align-items:center;gap:8px;flex:1;">
                            <i class="fas ${escapeHtml(opt.icon || 'fa-cog')} option-icon-modal"></i>
                            <div>
                                <strong style="font-size:12px;">${escapeHtml(opt.name)}</strong>
                                ${opt.description ? `<p class="option-desc-modal">${escapeHtml(opt.description)}</p>` : ''}
                            </div>
                        </div>
                        <div class="option-control-modal">
                            <div class="option-price-badge-modal">${priceDisplay}</div>
                            ${useToggle ? `
                                <label class="toggle-switch-modal">
                                    <input type="checkbox" class="extras-option-toggle" 
                                           data-option-id="${opt.id}" 
                                           data-option-name="${escapeHtml(opt.name)}" 
                                           data-price-daily="${opt.price_per_day}" 
                                           data-price-one="${opt.price_one_time}" 
                                           data-is-daily="${isDaily ? '1' : '0'}" 
                                           ${isChecked ? 'checked' : ''}
                                           onchange="calculateExtrasSummary()">
                                    <span class="toggle-slider-modal"></span>
                                </label>
                            ` : `
                                <select class="option-quantity-modal" 
                                        data-option-id="${opt.id}" 
                                        data-option-name="${escapeHtml(opt.name)}" 
                                        data-price-daily="${opt.price_per_day}" 
                                        data-price-one="${opt.price_one_time}" 
                                        data-is-daily="${isDaily ? '1' : '0'}" 
                                        data-max="${maxQty}" 
                                        onchange="calculateExtrasSummary()">
                                    ${Array.from({length: maxQty + 1}, (_, i) => 
                                        `<option value="${i}" ${i === selectedQty ? 'selected' : ''}>${i}</option>`
                                    ).join('')}
                                </select>
                            `}
                        </div>
                    </div>
                `;
            });
            container.innerHTML = html;
        }
        
        // ============================================
        // CALCULATE EXTRAS SUMMARY
        // ============================================
        function calculateExtrasSummary() {
            const days = parseInt(document.getElementById('extras_total_days').value) || 0;
            const carPrice = parseFloat(document.getElementById('extrasCarPrice')?.dataset?.value || 0);
            
            let insurancePrice = 0;
            let selectedInsuranceId = null;
            
            const insuranceRadios = document.querySelectorAll('#extrasInsuranceList input[name="extras_insurance"]');
            for(const radio of insuranceRadios) {
                if(radio.checked) {
                    selectedInsuranceId = radio.value;
                    const isDaily = radio.getAttribute('data-is-daily') === '1';
                    if(isDaily) {
                        insurancePrice = (parseFloat(radio.getAttribute('data-price-daily') || 0)) * days;
                    } else {
                        insurancePrice = parseFloat(radio.getAttribute('data-price-one') || 0);
                    }
                    break;
                }
            }
            
            let extrasTotal = 0;
            const selectedOptions = [];
            
            const quantitySelects = document.querySelectorAll('#extrasOptionsList .option-quantity-modal');
            for(const select of quantitySelects) {
                const qty = parseInt(select.value);
                if(qty > 0) {
                    const optionId = select.getAttribute('data-option-id');
                    const optionName = select.getAttribute('data-option-name');
                    const isDaily = select.getAttribute('data-is-daily') === '1';
                    let price = 0;
                    if(isDaily) {
                        price = (parseFloat(select.getAttribute('data-price-daily') || 0)) * days * qty;
                    } else {
                        price = (parseFloat(select.getAttribute('data-price-one') || 0)) * qty;
                    }
                    extrasTotal += price;
                    selectedOptions.push({
                        id: optionId,
                        name: optionName,
                        quantity: qty,
                        price: price
                    });
                }
            }
            
            const toggles = document.querySelectorAll('#extrasOptionsList .extras-option-toggle');
            for(const toggle of toggles) {
                if(toggle.checked) {
                    const optionId = toggle.getAttribute('data-option-id');
                    const optionName = toggle.getAttribute('data-option-name');
                    const isDaily = toggle.getAttribute('data-is-daily') === '1';
                    let price = 0;
                    if(isDaily) {
                        price = (parseFloat(toggle.getAttribute('data-price-daily') || 0)) * days;
                    } else {
                        price = parseFloat(toggle.getAttribute('data-price-one') || 0);
                    }
                    extrasTotal += price;
                    selectedOptions.push({
                        id: optionId,
                        name: optionName,
                        quantity: 1,
                        price: price
                    });
                }
            }
            
            const grandTotal = carPrice + insurancePrice + extrasTotal;
            const diff = grandTotal - oldGrandTotalForExtras;
            const diffText = diff >= 0 ? '+' : '';
            
            document.getElementById('extrasInsuranceSummary').innerText = '€' + insurancePrice.toFixed(2);
            document.getElementById('extrasOptionsSummary').innerText = '€' + extrasTotal.toFixed(2);
            document.getElementById('extrasNewGrandTotal').innerText = '€' + grandTotal.toFixed(2);
            document.getElementById('extrasDiffDisplay').innerText = diffText + '€' + diff.toFixed(2);
            
            document.getElementById('extras_selected_insurance').value = selectedInsuranceId || '';
            document.getElementById('extras_selected_options').value = JSON.stringify(selectedOptions);
        }
        
        // ============================================
        // SAVE EXTRAS
        // ============================================
        function saveExtras() {
            const id = document.getElementById('extras_reservation_id').value;
            const selectedInsuranceId = document.getElementById('extras_selected_insurance')?.value || '';
            const selectedOptions = document.getElementById('extras_selected_options')?.value || '';
            
            const btn = document.getElementById('saveExtrasBtn');
            const originalText = btn.innerHTML;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving...';
            btn.disabled = true;
            
            fetch('?ajax=1', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: `update_extras_ajax=1&id=${id}&selected_insurance_id=${selectedInsuranceId}&selected_options=${encodeURIComponent(selectedOptions)}`
            })
            .then(res => res.json())
            .then(data => {
                if(data.success){
                    showToast('Extras updated! New Grand Total: €' + data.new_grand_total.toFixed(2));
                    closeModal('extrasModal');
                    viewReservation(id);
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showToast('Error: ' + data.message, true);
                }
            })
            .catch(err => {
                showToast('Error: ' + err.message, true);
            })
            .finally(() => {
                btn.innerHTML = originalText;
                btn.disabled = false;
            });
        }
        
        // ============================================
        // OPEN GRAND TOTAL MODAL
        // ============================================
        function openGrandTotalModal(id, currentGrandTotal, currentCarPrice, currentExtrasTotal) {
            document.getElementById('grandTotal_reservation_id').value = id;
            document.getElementById('current_grand_total').value = '€' + currentGrandTotal.toFixed(2);
            document.getElementById('current_car_price').value = '€' + currentCarPrice.toFixed(2);
            document.getElementById('current_extras_total').value = '€' + currentExtrasTotal.toFixed(2);
            document.getElementById('new_grand_total').value = currentGrandTotal.toFixed(2);
            closeModal('viewModal');
            openModal('grandTotalModal');
        }
        
        // ============================================
        // SAVE GRAND TOTAL
        // ============================================
        function saveGrandTotal() {
            const id = document.getElementById('grandTotal_reservation_id').value;
            const newGrandTotal = parseFloat(document.getElementById('new_grand_total').value);
            
            if(isNaN(newGrandTotal) || newGrandTotal <= 0) {
                showToast('Please enter a valid grand total greater than 0', true);
                return;
            }
            
            const btn = document.querySelector('#grandTotalModal .btn-primary');
            const originalText = btn.innerHTML;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Updating...';
            btn.disabled = true;
            
            fetch('?ajax=1', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: `update_grand_total_ajax=1&id=${id}&grand_total=${newGrandTotal}`
            })
            .then(res => res.json())
            .then(data => {
                if(data.success){
                    showToast('Grand total updated! New total: €' + data.new_grand_total.toFixed(2));
                    closeModal('grandTotalModal');
                    setTimeout(() => {
                        viewReservation(id);
                        setTimeout(() => location.reload(), 1000);
                    }, 500);
                } else {
                    showToast('Error: ' + data.message, true);
                }
            })
            .catch(err => {
                showToast('Error: ' + err.message, true);
            })
            .finally(() => {
                btn.innerHTML = originalText;
                btn.disabled = false;
            });
        }
        
        function openEditCustomerModal(id) {
            fetch(`?ajax=1&get_reservation=${id}`)
                .then(res => res.json())
                .then(data => {
                    if(data.success){
                        const r = data.reservation;
                        const newHtml = `
                            <div class="form-group"><label>Name</label><input type="text" id="edit_name" value="${escapeHtml(r.customer_name)}"></div>
                            <div class="form-group"><label>Email</label><input type="email" id="edit_email" value="${escapeHtml(r.customer_email)}"></div>
                            <div class="form-group"><label>Phone</label><input type="text" id="edit_phone" value="${escapeHtml(r.customer_phone)}"></div>
                            <div class="form-group"><label>Pickup Location</label><input type="text" id="edit_pickup_loc" value="${escapeHtml(r.pickup_location)}"></div>
                            <div class="form-group"><label>Dropoff Location</label><input type="text" id="edit_dropoff_loc" value="${escapeHtml(r.dropoff_location)}"></div>
                            <div class="form-group"><label>Notes</label><textarea id="edit_notes" rows="2">${escapeHtml(r.notes || '')}</textarea></div>
                        `;
                        document.getElementById('viewContent').innerHTML = newHtml;
                        const saveBtn = document.createElement('button');
                        saveBtn.className = 'btn-primary';
                        saveBtn.style.width = '100%';
                        saveBtn.style.marginTop = '14px';
                        saveBtn.innerHTML = '<i class="fas fa-save"></i> Save Changes';
                        saveBtn.onclick = () => saveCustomerInfo(id);
                        document.getElementById('viewContent').appendChild(saveBtn);
                    }
                });
        }
        
        function saveCustomerInfo(id) {
            const customer_name = document.getElementById('edit_name').value;
            const customer_email = document.getElementById('edit_email').value;
            const customer_phone = document.getElementById('edit_phone').value;
            const pickup_location = document.getElementById('edit_pickup_loc').value;
            const dropoff_location = document.getElementById('edit_dropoff_loc').value;
            const notes = document.getElementById('edit_notes').value;
            
            fetch('?ajax=1', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: `update_customer_ajax=1&id=${id}&customer_name=${encodeURIComponent(customer_name)}&customer_email=${encodeURIComponent(customer_email)}&customer_phone=${encodeURIComponent(customer_phone)}&pickup_location=${encodeURIComponent(pickup_location)}&dropoff_location=${encodeURIComponent(dropoff_location)}&notes=${encodeURIComponent(notes)}`
            })
            .then(res => res.json())
            .then(data => {
                if(data.success){
                    showToast('Customer info updated!');
                    closeModal('viewModal');
                    viewReservation(id);
                } else {
                    showToast('Error: ' + data.message, true);
                }
            })
            .catch(err => showToast('Error: ' + err.message, true));
        }
        
        function openDatesModal(id, pDate, pTime, dDate, dTime) {
            document.getElementById('dates_reservation_id').value = id;
            document.getElementById('edit_pickup_date').value = pDate;
            document.getElementById('edit_pickup_time').value = pTime;
            document.getElementById('edit_dropoff_date').value = dDate;
            document.getElementById('edit_dropoff_time').value = dTime;
            document.getElementById('datesAvailabilityMsg').style.display = 'none';
            closeModal('viewModal');
            openModal('datesModal');
        }
        
        function saveDates() {
            const id = document.getElementById('dates_reservation_id').value;
            const pickup_date = document.getElementById('edit_pickup_date').value;
            const pickup_time = document.getElementById('edit_pickup_time').value;
            const dropoff_date = document.getElementById('edit_dropoff_date').value;
            const dropoff_time = document.getElementById('edit_dropoff_time').value;
            
            if(!pickup_date || !dropoff_date) {
                showToast('Please fill in all date fields', true);
                return;
            }
            
            const msgDiv = document.getElementById('datesAvailabilityMsg');
            msgDiv.style.display = 'block';
            msgDiv.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Updating dates...';
            
            fetch('?ajax=1', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: `update_dates_ajax=1&id=${id}&pickup_date=${pickup_date}&pickup_time=${pickup_time}&dropoff_date=${dropoff_date}&dropoff_time=${dropoff_time}`
            })
            .then(response => response.text().then(text => {
                try { return JSON.parse(text); } catch(e) { return { success: true, message: 'Dates updated' }; }
            }))
            .then(data => {
                if(data.success){
                    showToast('Dates updated!');
                    closeModal('datesModal');
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showToast('Error: ' + (data.message || 'Unknown error'), true);
                    msgDiv.className = 'availability-warning';
                    msgDiv.innerHTML = '<i class="fas fa-exclamation-triangle"></i> ' + (data.message || 'Unknown error');
                }
            })
            .catch(err => {
                showToast('Changes saved! Refreshing...', false);
                setTimeout(() => location.reload(), 1500);
            });
        }
        
        function openPaymentModal(id) {
            document.getElementById('payment_reservation_id').value = id;
            document.getElementById('payment_amount').value = '';
            document.getElementById('payment_method').value = 'cash';
            document.getElementById('payment_notes').value = '';
            closeModal('viewModal');
            openModal('paymentModal');
        }
        
        function savePayment() {
            const id = document.getElementById('payment_reservation_id').value;
            let amount = parseFloat(document.getElementById('payment_amount').value);
            const method = document.getElementById('payment_method').value;
            const notes = document.getElementById('payment_notes').value;
            
            if(isNaN(amount)) { showToast('Enter a valid amount', true); return; }
            if(amount === 0) { showToast('Amount cannot be zero', true); return; }
            
            fetch('?ajax=1', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: `add_payment_ajax=1&id=${id}&amount=${amount}&payment_method=${method}&notes=${encodeURIComponent(notes)}`
            })
            .then(res => res.json())
            .then(data => {
                if(data.success){
                    showToast(amount < 0 ? 'Refund processed!' : 'Payment added!');
                    closeModal('paymentModal');
                    viewReservation(id);
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showToast('Error: ' + data.message, true);
                }
            })
            .catch(err => showToast('Error: ' + err.message, true));
        }
        
        function openStatusModal(id, currentStatus) {
            document.getElementById('status_reservation_id').value = id;
            document.getElementById('edit_status').value = currentStatus;
            closeModal('viewModal');
            openModal('statusModal');
        }
        
        function saveStatus() {
            const id = document.getElementById('status_reservation_id').value;
            const status = document.getElementById('edit_status').value;
            
            fetch('?ajax=1', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: `update_status_ajax=1&id=${id}&status=${status}`
            })
            .then(res => res.json())
            .then(data => {
                if(data.success){
                    showToast('Status updated!');
                    closeModal('statusModal');
                    viewReservation(id);
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showToast('Error: ' + data.message, true);
                }
            })
            .catch(err => showToast('Error: ' + err.message, true));
        }
        
        function openCarModal(id) {
            document.getElementById('car_reservation_id').value = id;
            document.getElementById('new_car_id').value = '';
            document.getElementById('change_reason').value = '';
            document.getElementById('carAvailabilityMsg').style.display = 'none';
            document.getElementById('changeCarBtn').disabled = true;
            closeModal('viewModal');
            openModal('carModal');
        }
        
        function checkCarAvailability() {
            const id = document.getElementById('car_reservation_id').value;
            const newCarId = document.getElementById('new_car_id').value;
            const msgDiv = document.getElementById('carAvailabilityMsg');
            const changeBtn = document.getElementById('changeCarBtn');
            
            if(!newCarId) { msgDiv.style.display = 'none'; changeBtn.disabled = true; return; }
            
            msgDiv.style.display = 'block';
            msgDiv.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Checking availability...';
            
            fetch('?ajax=1', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: `check_car_availability_ajax=1&car_id=${newCarId}&reservation_id=${id}`
            })
            .then(res => res.json())
            .then(data => {
                if(data.available) {
                    msgDiv.className = 'info-note';
                    msgDiv.innerHTML = '<i class="fas fa-check-circle"></i> Car is available!';
                    changeBtn.disabled = false;
                } else {
                    msgDiv.className = 'availability-warning';
                    msgDiv.innerHTML = '<i class="fas fa-times-circle"></i> ' + (data.reason || 'Not available');
                    changeBtn.disabled = true;
                }
            })
            .catch(err => { msgDiv.innerHTML = 'Error checking'; changeBtn.disabled = true; });
        }
        
        function saveCarChange() {
            const id = document.getElementById('car_reservation_id').value;
            const newCarId = document.getElementById('new_car_id').value;
            const reason = document.getElementById('change_reason').value;
            if(!newCarId) { showToast('Select a car', true); return; }
            if(!reason.trim()) { showToast('Enter a reason', true); return; }
            fetch('?ajax=1', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: `change_car_ajax=1&id=${id}&new_car_id=${newCarId}&reason=${encodeURIComponent(reason)}`
            })
            .then(res => res.json())
            .then(data => {
                if(data.success){
                    showToast('Car changed! New total: €' + data.new_total_price.toFixed(2));
                    closeModal('carModal');
                    viewReservation(id);
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showToast('Error: ' + data.message, true);
                }
            })
            .catch(err => showToast('Error: ' + err.message, true));
        }
        
        function openNoteModal(id) {
            document.getElementById('note_reservation_id').value = id;
            document.getElementById('note_text').value = '';
            closeModal('viewModal');
            openModal('noteModal');
        }
        
        function saveNote() {
            const id = document.getElementById('note_reservation_id').value;
            const note = document.getElementById('note_text').value;
            if(!note.trim()){ showToast('Enter a note', true); return; }
            fetch('?ajax=1', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: `add_note_ajax=1&id=${id}&note=${encodeURIComponent(note)}`
            })
            .then(res => res.json())
            .then(data => {
                if(data.success){
                    showToast('Note added!');
                    closeModal('noteModal');
                    viewReservation(id);
                } else {
                    showToast('Error: ' + data.message, true);
                }
            })
            .catch(err => showToast('Error: ' + err.message, true));
        }
        
        function deleteReservation(id) {
    <?php if($is_worker): ?>
    alert('Workers cannot delete reservations.');
    return;
    <?php endif; ?>
    
    if(confirm('Delete this reservation? This cannot be undone!')) {
        fetch('?ajax=1', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: `delete_reservation_ajax=1&id=${id}`
        })
        .then(res => res.json())
        .then(data => {
            if(data.success){
                showToast('Reservation deleted');
                setTimeout(() => location.reload(), 1000);
            } else {
                showToast('Error deleting', true);
            }
        })
        .catch(err => showToast('Error: ' + err.message, true));
    }
}
        
        function generatePDFInvoice(id) {
            showToast('Generating PDF...');
            fetch('generate-pdf.php', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: `reservation_id=${id}`
            })
            .then(res => res.json())
            .then(data => {
                if(data.success && data.pdf){
                    const bytes = atob(data.pdf);
                    const nums = new Array(bytes.length);
                    for(let i = 0; i < bytes.length; i++) nums[i] = bytes.charCodeAt(i);
                    const blob = new Blob([new Uint8Array(nums)], {type: 'application/pdf'});
                    const url = URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = data.filename;
                    a.click();
                    URL.revokeObjectURL(url);
                    showToast('PDF downloaded!');
                } else {
                    showToast('Error generating PDF: ' + (data.message || 'Unknown error'), true);
                }
            })
            .catch(err => showToast('Error: ' + err.message, true));
        }
        
        function openModal(id) { document.getElementById(id).style.display = 'flex'; }
        function closeModal(id) { document.getElementById(id).style.display = 'none'; }
        
        window.onclick = function(e) { if(e.target.classList.contains('modal')) e.target.style.display = 'none'; }
        
        document.addEventListener('DOMContentLoaded', function() {
            const urlParams = new URLSearchParams(window.location.search);
            if(urlParams.get('status')) document.getElementById('statusFilter').value = urlParams.get('status');
            if(urlParams.get('date_filter')) document.getElementById('dateFilter').value = urlParams.get('date_filter');
            if(urlParams.get('per_page')) document.getElementById('perPageSelect').value = urlParams.get('per_page');
        });
    </script>
</body>
</html>