<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once '../includes/config.php';
if(!isset($_SESSION['admin_logged_in'])) {
    header('Location: login.php');
    exit();
}

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

// ============================================
// HANDLE AJAX REQUEST FOR AVAILABLE CARS
// ============================================
if(isset($_GET['ajax_available_cars'])) {
    header('Content-Type: application/json');
    
    $pickup_date = $_GET['pickup_date'] ?? date('Y-m-d');
    $pickup_time = $_GET['pickup_time'] ?? '10:00';
    $dropoff_date = $_GET['dropoff_date'] ?? date('Y-m-d', strtotime('+3 days'));
    $dropoff_time = $_GET['dropoff_time'] ?? '10:00';
    
    $all_cars = $pdo->query("SELECT id, brand, model, license_plate, image_url, status FROM cars WHERE status = 'available' ORDER BY brand")->fetchAll();
    $available_cars = [];
    
    foreach($all_cars as $car) {
        $availability = isCarAvailable($car['id'], $pickup_date, $pickup_time, $dropoff_date, $dropoff_time, $pdo, null, PREPARATION_HOURS);
        if($availability['available']) {
            $car['base_price'] = getCarBasePrice($car['id'], $pdo);
            $available_cars[] = $car;
        }
    }
    
    echo json_encode(['cars' => $available_cars]);
    exit();
}

// Get ALL cars with their details
$all_cars = $pdo->query("SELECT id, brand, model, license_plate, image_url, status FROM cars WHERE status = 'available' ORDER BY brand")->fetchAll();

$prefill_car_id = isset($_GET['car_id']) ? (int)$_GET['car_id'] : 0;
$prefill_pickup_date = isset($_GET['pickup_date']) ? $_GET['pickup_date'] : date('Y-m-d');
$prefill_dropoff_date = isset($_GET['dropoff_date']) ? $_GET['dropoff_date'] : date('Y-m-d', strtotime('+3 days'));
$prefill_pickup_time = isset($_GET['pickup_time']) ? $_GET['pickup_time'] : '10:00';
$prefill_dropoff_time = isset($_GET['dropoff_time']) ? $_GET['dropoff_time'] : '10:00';

// Get available cars for current dates (for initial display)
$available_cars = [];
foreach($all_cars as $car) {
    $availability = isCarAvailable($car['id'], $prefill_pickup_date, $prefill_pickup_time, $prefill_dropoff_date, $prefill_dropoff_time, $pdo, null, PREPARATION_HOURS);
    if($availability['available']) {
        $car['base_price'] = getCarBasePrice($car['id'], $pdo);
        $available_cars[] = $car;
    }
}

// Get insurance types and additional options for extras
$insurance_types = getInsuranceTypes($pdo);
$additional_options = getAdditionalOptions($pdo);

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $car_id = (int)$_POST['car_id'];
    $pickup_location = trim($_POST['pickup_location']);
    $dropoff_location = trim($_POST['dropoff_location']);
    $pickup_date = $_POST['pickup_date'];
    $pickup_time = $_POST['pickup_time'];
    $dropoff_date = $_POST['dropoff_date'];
    $dropoff_time = $_POST['dropoff_time'];
    $customer_name = trim($_POST['customer_name']);
    $customer_email = trim($_POST['customer_email']);
    $customer_phone = trim($_POST['customer_phone']);
    $notes = trim($_POST['notes'] ?? '');
    $status = $_POST['status'];
    
    // Get extras
    $selected_insurance_id = !empty($_POST['selected_insurance_id']) ? (int)$_POST['selected_insurance_id'] : null;
    $selected_options = !empty($_POST['selected_options']) ? $_POST['selected_options'] : null;
    
    $errors = [];
    if(empty($car_id)) $errors[] = "Please select a car";
    if(empty($customer_name)) $errors[] = "Customer name is required";
    if(empty($customer_email) || !filter_var($customer_email, FILTER_VALIDATE_EMAIL)) $errors[] = "Valid email is required";
    if(empty($customer_phone)) $errors[] = "Phone number is required";
    if(empty($pickup_location)) $errors[] = "Pickup location is required";
    if(empty($dropoff_location)) $errors[] = "Dropoff location is required";
    
    if($pickup_date > $dropoff_date) {
        $errors[] = "Return date must be after pickup date";
    }
    
    if($pickup_date == $dropoff_date && $pickup_time >= $dropoff_time) {
        $errors[] = "For the same day, return time must be after pickup time";
    }
    
    if(empty($errors)) {
        // Perdor funksionin e ri me ore
        $price_data = calculateDynamicPrice($car_id, $pickup_date, $pickup_time, $dropoff_date, $dropoff_time, $pdo);
        $days = $price_data['days'];
        $total_price = $price_data['total_price'];
        
        // Calculate 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'];
        $grand_total = $total_price + $extras_total;
        
        $availability = isCarAvailable($car_id, $pickup_date, $pickup_time, $dropoff_date, $dropoff_time, $pdo, null, PREPARATION_HOURS);
        
        if(!$availability['available']) {
            $error = "Car is not available: " . $availability['reason'];
        } else {
            $reservation_code = generateReservationCode($pdo);
            $balance = $grand_total;
            
            $sql = "INSERT INTO reservations (reservation_code, car_id, pickup_location, dropoff_location, pickup_date, pickup_time, dropoff_date, dropoff_time, total_days, total_price, balance, customer_name, customer_email, customer_phone, notes, status, payment_status, selected_insurance_id, selected_insurance_price, selected_options, extras_total, grand_total, original_total_price) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'unpaid', ?, ?, ?, ?, ?, ?)";
            $stmt = $pdo->prepare($sql);
            
            try {
                if($stmt->execute([$reservation_code, $car_id, $pickup_location, $dropoff_location, $pickup_date, $pickup_time, $dropoff_date, $dropoff_time, $days, $total_price, $balance, $customer_name, $customer_email, $customer_phone, $notes, $status, $selected_insurance_id, $selected_insurance_price, $selected_options, $extras_total, $grand_total, $total_price])) {
                    $reservation_id = $pdo->lastInsertId();
                    $note = "Reservation created manually by admin: " . $_SESSION['admin_username'];
                    $stmt2 = $pdo->prepare("INSERT INTO reservation_notes (reservation_id, note, note_type, created_by) VALUES (?, ?, 'system', ?)");
                    $stmt2->execute([$reservation_id, $note, $_SESSION['admin_username']]);
                    
                    // ============================================
                    // SEND EMAILS
                    // ============================================
                    // Get car data for email
                    $car_stmt = $pdo->prepare("SELECT * FROM cars WHERE id = ?");
                    $car_stmt->execute([$car_id]);
                    $car_data_email = $car_stmt->fetch(PDO::FETCH_ASSOC);
                    
                    // Prepare booking data for email
                    $booking_data_email = [
                        'reservation_code' => $reservation_code,
                        'customer_name' => $customer_name,
                        'customer_email' => $customer_email,
                        'customer_phone' => $customer_phone,
                        'pickup_location' => $pickup_location,
                        'dropoff_location' => $dropoff_location,
                        'pickup_date' => $pickup_date,
                        'pickup_time' => $pickup_time,
                        'dropoff_date' => $dropoff_date,
                        'dropoff_time' => $dropoff_time,
                        'total_days' => $days,
                        'notes' => $notes,
                        'created_at' => date('Y-m-d H:i:s')
                    ];
                    
                    $price_data_email = [
                        'grand_total' => $grand_total,
                        'total_price' => $total_price,
                        'extras_total' => $extras_total
                    ];
                    
                    // Include email functions and send emails
                    if(file_exists('../includes/email-functions.php')) {
                        require_once '../includes/email-functions.php';
                        $email_result = sendBookingEmails($booking_data_email, $car_data_email, $price_data_email);
                        if($email_result) {
                            error_log("Emails sent successfully for reservation: " . $reservation_code);
                        } else {
                            error_log("Failed to send some emails for reservation: " . $reservation_code);
                        }
                    } else {
                        error_log("email-functions.php not found - emails not sent");
                    }
                    // ============================================
                    
                    $message = "Reservation created successfully! Reservation code: <strong>" . $reservation_code . "</strong>";
                    
                    $_POST = array();
                    $prefill_car_id = 0;
                    $prefill_pickup_date = date('Y-m-d');
                    $prefill_dropoff_date = date('Y-m-d', strtotime('+3 days'));
                    
                    // Refresh available cars
                    $available_cars = [];
                    foreach($all_cars as $car) {
                        $availability = isCarAvailable($car['id'], $prefill_pickup_date, $prefill_pickup_time, $prefill_dropoff_date, $prefill_dropoff_time, $pdo, null, PREPARATION_HOURS);
                        if($availability['available']) {
                            $car['base_price'] = getCarBasePrice($car['id'], $pdo);
                            $available_cars[] = $car;
                        }
                    }
                } else {
                    $error = "Error creating reservation";
                }
            } catch (PDOException $e) {
                $error = "Database error: " . $e->getMessage();
            }
        }
    } else {
        $error = implode("<br>", $errors);
    }
}

// Get selected car details for display
$selected_car_details = null;
if($prefill_car_id > 0) {
    $stmt = $pdo->prepare("SELECT * FROM cars WHERE id = ?");
    $stmt->execute([$prefill_car_id]);
    $selected_car_details = $stmt->fetch(PDO::FETCH_ASSOC);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title>Create Reservation - 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: #f5f7fb; 
        }
        
        /* Sidebar */
        .sidebar {
            width: 260px;
            background: #1a1a2e;
            color: white;
            position: fixed;
            left: 0;
            top: 0;
            bottom: 0;
            overflow-y: auto;
            z-index: 100;
        }
        .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;
            transition: all 0.2s;
        }
        .sidebar-nav a i { width: 20px; }
        .sidebar-nav a:hover, .sidebar-nav a.active { background: #0066cc; color: white; }
        
        /* Main Content */
        .main-content { margin-left: 260px; padding: 24px; }
        .page-header { margin-bottom: 24px; }
        .page-header h1 { font-size: 24px; font-weight: 600; color: #1a1a2e; }
        .page-header p { color: #6b7280; margin-top: 8px; }
        
        /* Form Container */
        .form-container {
            max-width: 1400px;
            margin: 0 auto;
        }
        
        /* Two Column Layout - Top Section */
        .top-section {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 24px;
            margin-bottom: 24px;
        }
        
        /* Bottom Section */
        .bottom-section {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 24px;
        }
        
        /* Cards */
        .card {
            background: white;
            border-radius: 16px;
            border: 1px solid #e5e7eb;
            overflow: hidden;
        }
        .card-header {
            background: #f8fafc;
            padding: 16px 20px;
            border-bottom: 1px solid #e5e7eb;
        }
        .card-header h2 {
            font-size: 16px;
            font-weight: 600;
            color: #1e293b;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .card-header h2 i {
            color: #0066cc;
            font-size: 18px;
        }
        .card-body {
            padding: 20px;
        }
        
        /* Form Groups */
        .form-group {
            margin-bottom: 18px;
        }
        .form-group label {
            display: block;
            margin-bottom: 6px;
            font-weight: 500;
            font-size: 13px;
            color: #374151;
        }
        .form-group label .required {
            color: #dc2626;
            margin-left: 2px;
        }
        .form-group input, 
        .form-group select, 
        .form-group textarea {
            width: 100%;
            padding: 10px 14px;
            border: 1px solid #d1d5db;
            border-radius: 10px;
            font-size: 14px;
            transition: all 0.2s;
        }
        .form-group input:focus, 
        .form-group select:focus, 
        .form-group textarea:focus {
            outline: none;
            border-color: #0066cc;
            box-shadow: 0 0 0 3px rgba(0,102,204,0.1);
        }
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 16px;
        }
        
        /* Car Selection */
        .car-search {
            position: relative;
            margin-bottom: 16px;
        }
        .car-search input {
            width: 100%;
            padding: 12px 16px;
            padding-left: 40px;
            border: 1px solid #d1d5db;
            border-radius: 12px;
            font-size: 14px;
        }
        .car-search i {
            position: absolute;
            left: 14px;
            top: 50%;
            transform: translateY(-50%);
            color: #9ca3af;
        }
        .car-list {
            max-height: 320px;
            overflow-y: auto;
            border: 1px solid #e5e7eb;
            border-radius: 12px;
            background: white;
        }
        .car-item {
            padding: 12px 16px;
            border-bottom: 1px solid #f0f0f0;
            cursor: pointer;
            transition: all 0.2s;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .car-item:hover {
            background: #eff6ff;
        }
        .car-item.selected {
            background: #0066cc;
            color: white;
        }
        .car-item.selected .car-plate {
            background: rgba(255,255,255,0.2);
            color: white;
        }
        .car-item.selected .car-price {
            color: white;
        }
        .car-name {
            font-weight: 500;
            font-size: 14px;
        }
        .car-plate {
            font-size: 11px;
            font-family: monospace;
            background: #f3f4f6;
            padding: 2px 8px;
            border-radius: 6px;
            color: #4b5563;
        }
        .car-price {
            font-size: 12px;
            font-weight: 600;
            color: #0066cc;
        }
        .no-results {
            text-align: center;
            padding: 30px;
            color: #9ca3af;
        }
        .available-cars-count {
            font-size: 12px;
            color: #10b981;
            margin-top: 8px;
            text-align: center;
            padding: 8px;
            background: #d1fae5;
            border-radius: 8px;
        }
        
        /* Selected Car Preview */
        .selected-car-preview {
            background: #f0f9ff;
            border-radius: 12px;
            padding: 16px;
            margin-top: 16px;
            border: 1px solid #bfdbfe;
            display: flex;
            align-items: center;
            gap: 16px;
            flex-wrap: wrap;
        }
        .selected-car-preview-img {
            width: 80px;
            height: 60px;
            object-fit: cover;
            border-radius: 8px;
            background: #e2e8f0;
        }
        .selected-car-preview-info {
            flex: 1;
        }
        .selected-car-preview-name {
            font-weight: 700;
            font-size: 15px;
            margin-bottom: 4px;
        }
        .selected-car-preview-plate {
            font-family: monospace;
            font-size: 12px;
            background: #e2e8f0;
            display: inline-block;
            padding: 2px 8px;
            border-radius: 4px;
        }
        .selected-car-preview-price {
            color: #0066cc;
            font-weight: 600;
            margin-top: 6px;
            font-size: 13px;
        }
        .no-car-selected {
            text-align: center;
            padding: 30px;
            color: #9ca3af;
            background: #f9fafb;
            border-radius: 12px;
            border: 1px dashed #d1d5db;
            margin-top: 16px;
        }
        
        /* Price Summary */
        .price-summary {
            background: linear-gradient(135deg, #0066cc 0%, #0052a3 100%);
            border-radius: 12px;
            padding: 16px 20px;
            margin-top: 20px;
        }
        .price-summary .summary-row {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            color: white;
            font-size: 14px;
        }
        .price-summary .summary-row:not(:last-child) {
            border-bottom: 1px solid rgba(255,255,255,0.2);
        }
        .price-summary .discount-row {
            color: #fbbf24 !important;
        }
        .price-summary .discount-row span:first-child {
            color: #fbbf24;
        }
        .price-summary .discount-row span:last-child {
            color: #fbbf24;
            font-weight: 600;
        }
        .price-summary .total {
            font-weight: 700;
            font-size: 18px;
            padding-top: 10px;
            margin-top: 5px;
            border-top: 1px solid rgba(255,255,255,0.3);
        }
        
        /* Extras Section - Two columns layout */
        .extras-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }
        .extras-col {
            background: #f8fafc;
            border-radius: 12px;
            border: 1px solid #e5e7eb;
            overflow: hidden;
        }
        .extras-col-header {
            background: #f1f5f9;
            padding: 12px 16px;
            border-bottom: 1px solid #e5e7eb;
            font-weight: 600;
            font-size: 13px;
            color: #1e293b;
        }
        .extras-col-header i {
            color: #0066cc;
            margin-right: 8px;
        }
        .extras-col-body {
            padding: 12px;
            max-height: 280px;
            overflow-y: auto;
        }
        
        /* Insurance & Options Items */
        .insurance-option, .option-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 10px 12px;
            margin-bottom: 8px;
            background: white;
            border-radius: 10px;
            border: 1px solid #e5e7eb;
            transition: all 0.2s;
        }
        .insurance-option {
            cursor: pointer;
        }
        .insurance-option:hover, .option-item:hover {
            border-color: #0066cc;
        }
        .insurance-option input {
            margin-right: 12px;
        }
        .option-desc {
            font-size: 11px;
            color: #6b7280;
            margin-top: 3px;
        }
        .option-icon {
            width: 28px;
            font-size: 16px;
            color: #0066cc;
            text-align: center;
        }
        .option-price-badge {
            font-weight: 600;
            color: #0066cc;
            font-size: 13px;
            min-width: 65px;
            text-align: right;
        }
        .option-price-badge small {
            font-size: 9px;
            font-weight: normal;
            display: block;
        }
        .option-control {
            display: flex;
            align-items: center;
            gap: 12px;
        }
        .option-quantity {
            width: 65px;
            padding: 6px;
            border-radius: 8px;
            border: 1px solid #e5e7eb;
        }
        
        /* Toggle Switch */
        .toggle-switch {
            position: relative;
            display: inline-block;
            width: 46px;
            height: 24px;
        }
        .toggle-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        .toggle-slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: 0.2s;
            border-radius: 24px;
        }
        .toggle-slider:before {
            position: absolute;
            content: "";
            height: 18px;
            width: 18px;
            left: 3px;
            bottom: 3px;
            background-color: white;
            transition: 0.2s;
            border-radius: 50%;
        }
        .toggle-switch input:checked + .toggle-slider {
            background-color: #0066cc;
        }
        .toggle-switch input:checked + .toggle-slider:before {
            transform: translateX(22px);
        }
        
        /* Availability Status */
        .availability-status {
            margin-top: 16px;
            padding: 12px 16px;
            border-radius: 10px;
            font-size: 13px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .availability-unavailable {
            background: #fee2e2;
            color: #991b1b;
            border-left: 3px solid #dc2626;
        }
        .availability-available {
            background: #d1fae5;
            color: #065f46;
            border-left: 3px solid #10b981;
        }
        
        /* Buttons */
        .btn-submit {
            width: 100%;
            background: #10b981;
            color: white;
            padding: 14px 24px;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
            margin-top: 20px;
        }
        .btn-submit:hover {
            background: #059669;
            transform: translateY(-1px);
        }
        .btn-submit:disabled {
            background: #9ca3af;
            cursor: not-allowed;
            transform: none;
        }
        
        /* Alerts */
        .alert-success {
            background: #d1fae5;
            color: #065f46;
            padding: 14px 18px;
            border-radius: 12px;
            margin-bottom: 24px;
            border-left: 4px solid #10b981;
        }
        .alert-error {
            background: #fee2e2;
            color: #991b1b;
            padding: 14px 18px;
            border-radius: 12px;
            margin-bottom: 24px;
            border-left: 4px solid #dc2626;
        }
        
        /* Info Note */
        .info-note {
            background: #fef3c7;
            padding: 10px 14px;
            border-radius: 10px;
            font-size: 12px;
            color: #92400e;
            margin-top: 12px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        /* Loading Spinner */
        .loading-spinner {
            display: inline-block;
            width: 16px;
            height: 16px;
            border: 2px solid #f3f4f6;
            border-top: 2px solid #0066cc;
            border-radius: 50%;
            animation: spin 0.8s linear infinite;
            margin-right: 8px;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* Responsive */
        @media (max-width: 1000px) {
            .sidebar {
                width: 100%;
                position: relative;
                height: auto;
            }
            .main-content {
                margin-left: 0;
            }
            .top-section, .bottom-section, .extras-row {
                grid-template-columns: 1fr;
                gap: 16px;
            }
        }
        
        @media (max-width: 640px) {
            .form-row {
                grid-template-columns: 1fr;
                gap: 12px;
            }
            .card-body {
                padding: 16px;
            }
        }
    </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" class="active"><i class="fas fa-plus-square"></i> Create Reservation</a>
            <a href="reservations.php"><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="form-container">
            <div class="page-header">
                <h1><i class="fas fa-plus-square"></i> Create New Reservation</h1>
                <p>Fill in the form below to create a manual reservation for a customer</p>
            </div>
            
            <?php if($message): ?>
                <div class="alert-success">
                    <i class="fas fa-check-circle"></i> <?php echo $message; ?> 
                    <a href="reservations.php" style="color: #065f46; text-decoration: underline; margin-left: 10px;">View all reservations →</a>
                </div>
            <?php endif; ?>
            
            <?php if($error): ?>
                <div class="alert-error">
                    <i class="fas fa-exclamation-circle"></i> <?php echo $error; ?>
                </div>
            <?php endif; ?>
            
            <form method="POST" id="reservationForm">
                <input type="hidden" name="selected_insurance_id" id="selected_insurance_id" value="">
                <input type="hidden" name="selected_options" id="selected_options" value="">
                
                <!-- TOP SECTION: Select Vehicle + Rental Period (Side by Side) -->
                <div class="top-section">
                    <!-- Car Selection Card -->
                    <div class="card">
                        <div class="card-header">
                            <h2><i class="fas fa-car"></i> Select Vehicle</h2>
                        </div>
                        <div class="card-body">
                            <div class="car-search">
                                <i class="fas fa-search"></i>
                                <input type="text" id="carSearchInput" placeholder="Search by brand, model, or license plate..." autocomplete="off">
                            </div>
                            <input type="hidden" name="car_id" id="selected_car_id" value="<?php echo $prefill_car_id; ?>">
                            
                            <div class="car-list" id="carList">
                                <?php foreach($available_cars as $car): 
                                    $searchable = strtolower($car['brand'] . ' ' . $car['model'] . ' ' . $car['license_plate']);
                                ?>
                                <div class="car-item <?php echo ($prefill_car_id == $car['id']) ? 'selected' : ''; ?>" 
                                     data-car-id="<?php echo $car['id']; ?>" 
                                     data-car-name="<?php echo htmlspecialchars($car['brand'] . ' ' . $car['model']); ?>"
                                     data-car-plate="<?php echo htmlspecialchars($car['license_plate']); ?>"
                                     data-car-image="<?php echo $car['image_url']; ?>"
                                     data-car-price="<?php echo $car['base_price']; ?>"
                                     data-searchable="<?php echo $searchable; ?>">
                                    <span class="car-name"><?php echo htmlspecialchars($car['brand'] . ' ' . $car['model']); ?></span>
                                    <div style="display: flex; gap: 8px; align-items: center;">
                                        <span class="car-price">€<?php echo number_format($car['base_price'], 2); ?>/day</span>
                                        <span class="car-plate"><?php echo htmlspecialchars($car['license_plate']); ?></span>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            
                            <div class="available-cars-count" id="availableCarsCount">
                                <i class="fas fa-check-circle"></i> <?php echo count($available_cars); ?> cars available for selected dates
                            </div>
                            
                            <!-- Selected Car Preview -->
                            <div id="selectedCarPreview">
                                <?php if($selected_car_details): 
                                    $base_price = getCarBasePrice($selected_car_details['id'], $pdo);
                                    $img_src = $selected_car_details['image_url'] ? '../' . $selected_car_details['image_url'] : 'https://placehold.co/80x60?text=Car';
                                ?>
                                <div class="selected-car-preview">
                                    <img src="<?php echo $img_src; ?>" class="selected-car-preview-img" onerror="this.src='https://placehold.co/80x60?text=Car'">
                                    <div class="selected-car-preview-info">
                                        <div class="selected-car-preview-name"><?php echo htmlspecialchars($selected_car_details['brand'] . ' ' . $selected_car_details['model']); ?></div>
                                        <div class="selected-car-preview-plate"><?php echo htmlspecialchars($selected_car_details['license_plate']); ?></div>
                                        <div class="selected-car-preview-price">Base price: €<?php echo number_format($base_price, 2); ?>/day</div>
                                    </div>
                                </div>
                                <?php else: ?>
                                <div class="no-car-selected">
                                    <i class="fas fa-info-circle"></i> No car selected. Click on a car above to select.
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Rental Period Card -->
                    <div class="card">
                        <div class="card-header">
                            <h2><i class="fas fa-calendar-alt"></i> Rental Period</h2>
                        </div>
                        <div class="card-body">
                            <div class="form-row">
                                <div class="form-group">
                                    <label>Pickup Date <span class="required">*</span></label>
                                    <input type="date" name="pickup_date" id="pickup_date" required value="<?php echo $prefill_pickup_date; ?>">
                                </div>
                                <div class="form-group">
                                    <label>Pickup Time</label>
                                    <input type="time" name="pickup_time" id="pickup_time" value="<?php echo $prefill_pickup_time; ?>">
                                </div>
                            </div>
                            <div class="form-row">
                                <div class="form-group">
                                    <label>Return Date <span class="required">*</span></label>
                                    <input type="date" name="dropoff_date" id="dropoff_date" required value="<?php echo $prefill_dropoff_date; ?>">
                                </div>
                                <div class="form-group">
                                    <label>Return Time</label>
                                    <input type="time" name="dropoff_time" id="dropoff_time" value="<?php echo $prefill_dropoff_time; ?>">
                                </div>
                            </div>
                            
                            <div class="form-row">
                                <div class="form-group">
                                    <label>Pickup Location <span class="required">*</span></label>
                                    <select name="pickup_location" id="pickup_location" required>
                                        <option value="">Select location</option>
                                        <option value="Tirana Airport">Tirana Airport</option>
                                        <option value="Tirana Center">Tirana Center</option>
                                        <option value="Durres">Durres</option>
                                        <option value="Vlore">Vlore</option>
                                        <option value="Sarande">Sarande</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label>Return Location <span class="required">*</span></label>
                                    <select name="dropoff_location" id="dropoff_location" required>
                                        <option value="">Select location</option>
                                        <option value="same">Same as pickup</option>
                                        <option value="Tirana Airport">Tirana Airport</option>
                                        <option value="Tirana Center">Tirana Center</option>
                                        <option value="Durres">Durres</option>
                                        <option value="Vlore">Vlore</option>
                                        <option value="Sarande">Sarande</option>
                                    </select>
                                </div>
                            </div>
                            
                            <!-- Price Summary -->
                            <div class="price-summary" id="priceSummary">
                                <div class="summary-row">
                                    <span>Daily rate:</span>
                                    <span id="dailyRate">--</span>
                                </div>
                                <div class="summary-row">
                                    <span>Number of days:</span>
                                    <span id="daysCount">--</span>
                                </div>
                                <div class="summary-row">
                                    <span>Subtotal:</span>
                                    <span id="subtotal">--</span>
                                </div>
                                <div class="summary-row discount-row" id="discountRow" style="display: none;">
                                    <span>Discount (<span id="discountPercent">0</span>%):</span>
                                    <span id="discountAmount">-€0.00</span>
                                </div>
                                <div class="summary-row total">
                                    <span>Total Car Price:</span>
                                    <span id="totalCarPrice">--</span>
                                </div>
                                <div class="summary-row" id="insuranceSummaryRow" style="display: none;">
                                    <span>Insurance:</span>
                                    <span id="insuranceSummaryDisplay">€0.00</span>
                                </div>
                                <div class="summary-row" id="extrasSummaryRow" style="display: none;">
                                    <span>Extra options:</span>
                                    <span id="extrasSummaryDisplay">€0.00</span>
                                </div>
                                <div class="summary-row total" style="border-top: 1px solid rgba(255,255,255,0.3); margin-top: 8px;">
                                    <span>Grand Total:</span>
                                    <span id="grandTotalDisplay">--</span>
                                </div>
                            </div>
                            
                            <!-- Availability Status -->
                            <div id="availabilityStatus" class="availability-status" style="display: none;"></div>
                        </div>
                    </div>
                </div>
                
                <!-- MIDDLE SECTION: Extras - Two Columns Layout -->
                <div class="card" style="margin-bottom: 24px;">
                    <div class="card-header">
                        <h2><i class="fas fa-cogs"></i> Extras (Insurance & Additional Options)</h2>
                    </div>
                    <div class="card-body">
                        <div class="extras-row">
                            <!-- Left Column: Insurance -->
                            <div class="extras-col">
                                <div class="extras-col-header">
                                    <i class="fas fa-shield-alt"></i> Insurance Coverage
                                </div>
                                <div class="extras-col-body">
                                    <?php if(count($insurance_types) > 0): ?>
                                        <?php foreach($insurance_types as $ins): ?>
                                        <label class="insurance-option">
                                            <div style="display: flex; align-items: center; gap: 12px; flex: 1;">
                                                <input type="radio" name="insurance_radio" value="<?php echo $ins['id']; ?>" 
                                                       data-price-daily="<?php echo $ins['price_per_day']; ?>" 
                                                       data-price-one="<?php echo $ins['price_one_time']; ?>" 
                                                       data-is-daily="<?php echo $ins['is_daily']; ?>" 
                                                       <?php echo ($ins['price_per_day'] == 0 || ($ins['price_per_day'] === 0.00)) ? 'checked' : ''; ?> 
                                                       onchange="calculateGrandTotal()">
                                                <div>
                                                    <strong><?php echo htmlspecialchars($ins['name']); ?></strong>
                                                    <?php if($ins['description']): ?>
                                                    <p class="option-desc"><?php echo htmlspecialchars($ins['description']); ?></p>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                            <div class="option-price-badge">
                                                <?php if($ins['is_daily']): ?>
                                                    €<?php echo number_format($ins['price_per_day'] ?: 0, 2); ?>
                                                    <small>/day</small>
                                                <?php elseif($ins['price_one_time']): ?>
                                                    €<?php echo number_format($ins['price_one_time'], 2); ?>
                                                    <small>once</small>
                                                <?php else: ?>
                                                    Free
                                                <?php endif; ?>
                                            </div>
                                        </label>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <div style="text-align: center; padding: 20px; color: #6b7280;">
                                            <i class="fas fa-info-circle"></i> No insurance types configured
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <!-- Right Column: Additional Options -->
                            <div class="extras-col">
                                <div class="extras-col-header">
                                    <i class="fas fa-plus-circle"></i> Extra Options
                                </div>
                                <div class="extras-col-body">
                                    <?php if(count($additional_options) > 0): ?>
                                        <?php foreach($additional_options as $opt): 
                                            $is_daily = $opt['is_daily'] == 1;
                                            $max_qty = (int)$opt['max_quantity'];
                                            $use_toggle = ($max_qty == 1);
                                        ?>
                                        <div class="option-item">
                                            <div style="display: flex; align-items: center; gap: 10px; flex: 1;">
                                                <i class="fas <?php echo htmlspecialchars($opt['icon'] ?: 'fa-cog'); ?> option-icon"></i>
                                                <div>
                                                    <strong><?php echo htmlspecialchars($opt['name']); ?></strong>
                                                    <?php if($opt['description']): ?>
                                                    <p class="option-desc"><?php echo htmlspecialchars($opt['description']); ?></p>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                            <div class="option-control">
                                                <div class="option-price-badge">
                                                    <?php if($is_daily): ?>
                                                        €<?php echo number_format($opt['price_per_day'] ?: 0, 2); ?>
                                                        <small>/day</small>
                                                    <?php else: ?>
                                                        €<?php echo number_format($opt['price_one_time'] ?: 0, 2); ?>
                                                        <small>once</small>
                                                    <?php endif; ?>
                                                </div>
                                                
                                                <?php if($use_toggle): ?>
                                                    <label class="toggle-switch">
                                                        <input type="checkbox" class="option-toggle" 
                                                               data-option-id="<?php echo $opt['id']; ?>" 
                                                               data-option-name="<?php echo htmlspecialchars($opt['name']); ?>" 
                                                               data-price-daily="<?php echo $opt['price_per_day']; ?>" 
                                                               data-price-one="<?php echo $opt['price_one_time']; ?>" 
                                                               data-is-daily="<?php echo $is_daily ? '1' : '0'; ?>" 
                                                               onchange="calculateGrandTotal()">
                                                        <span class="toggle-slider"></span>
                                                    </label>
                                                <?php else: ?>
                                                    <select class="option-quantity" 
                                                            data-option-id="<?php echo $opt['id']; ?>" 
                                                            data-option-name="<?php echo htmlspecialchars($opt['name']); ?>" 
                                                            data-price-daily="<?php echo $opt['price_per_day']; ?>" 
                                                            data-price-one="<?php echo $opt['price_one_time']; ?>" 
                                                            data-is-daily="<?php echo $is_daily ? '1' : '0'; ?>" 
                                                            data-max="<?php echo $max_qty; ?>" 
                                                            onchange="calculateGrandTotal()">
                                                        <?php for($i = 0; $i <= $max_qty; $i++): ?>
                                                        <option value="<?php echo $i; ?>"><?php echo $i; ?></option>
                                                        <?php endfor; ?>
                                                    </select>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <div style="text-align: center; padding: 20px; color: #6b7280;">
                                            <i class="fas fa-info-circle"></i> No extra options configured
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- BOTTOM SECTION: Customer Info + Reservation Settings -->
                <div class="bottom-section">
                    <!-- Customer Information Card -->
                    <div class="card">
                        <div class="card-header">
                            <h2><i class="fas fa-user"></i> Customer Information</h2>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label>Full Name <span class="required">*</span></label>
                                <input type="text" name="customer_name" placeholder="Enter customer's full name" required>
                            </div>
                            <div class="form-group">
                                <label>Email Address <span class="required">*</span></label>
                                <input type="email" name="customer_email" placeholder="customer@example.com" required>
                            </div>
                            <div class="form-group">
                                <label>Phone Number <span class="required">*</span></label>
                                <input type="tel" name="customer_phone" placeholder="+355 XX XXX XXX" required>
                            </div>
                            <div class="form-group">
                                <label>Special Requests / Notes</label>
                                <textarea name="notes" rows="3" placeholder="Any special requirements or notes about this reservation..."></textarea>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Reservation Settings Card -->
                    <div class="card">
                        <div class="card-header">
                            <h2><i class="fas fa-tag"></i> Reservation Settings</h2>
                        </div>
                        <div class="card-body">
                            <div class="form-group">
                                <label>Reservation Status</label>
                                <select name="status">
                                    <option value="pending">Pending - Awaiting confirmation</option>
                                    <option value="confirmed">Confirmed - Ready to go</option>
                                </select>
                                <small style="font-size: 11px; color: #6b7280; display: block; margin-top: 4px;">
                                    Set to "Confirmed" if payment has been received
                                </small>
                            </div>
                            
                            <div class="info-note" style="background: #eff6ff; color: #1e40af;">
                                <i class="fas fa-info-circle"></i>
                                <span>A confirmation email will be sent to the customer automatically.</span>
                            </div>
                            
                            <button type="submit" class="btn-submit" id="submitBtn" disabled>
                                <i class="fas fa-save"></i> Create Reservation
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
    
    <script>
        // DOM Elements
        const pickupDate = document.getElementById('pickup_date');
        const dropoffDate = document.getElementById('dropoff_date');
        const pickupTime = document.getElementById('pickup_time');
        const dropoffTime = document.getElementById('dropoff_time');
        const availabilityDiv = document.getElementById('availabilityStatus');
        const submitBtn = document.getElementById('submitBtn');
        let currentCarId = <?php echo $prefill_car_id ?: 0; ?>;
        let currentCarBasePrice = 0;
        let isRefreshingCars = false;
        let currentDays = 0;
        let currentCarTotal = 0;
        let currentDiscountPercent = 0;
        let currentDiscountAmount = 0;
        
        // Car data store
        const carData = {};
        <?php foreach($all_cars as $car): ?>
        carData[<?php echo $car['id']; ?>] = {
            name: '<?php echo addslashes($car['brand'] . ' ' . $car['model']); ?>',
            plate: '<?php echo addslashes($car['license_plate']); ?>',
            image: '<?php echo $car['image_url'] ? "../" . addslashes($car['image_url']) : ""; ?>',
            basePrice: <?php echo getCarBasePrice($car['id'], $pdo); ?>
        };
        <?php endforeach; ?>
        
        // Search filter functionality
        const searchInput = document.getElementById('carSearchInput');
        
        function filterCars() {
            const searchTerm = searchInput.value.toLowerCase();
            const carItems = document.querySelectorAll('.car-item');
            let visibleCount = 0;
            
            carItems.forEach(item => {
                const searchable = item.getAttribute('data-searchable') || '';
                if(searchable.includes(searchTerm)) {
                    item.style.display = 'flex';
                    visibleCount++;
                } else {
                    item.style.display = 'none';
                }
            });
            
            const carList = document.getElementById('carList');
            let noResultsDiv = carList.querySelector('.no-results');
            if(noResultsDiv) noResultsDiv.remove();
            
            if(visibleCount === 0 && searchTerm !== '') {
                noResultsDiv = document.createElement('div');
                noResultsDiv.className = 'no-results';
                noResultsDiv.innerHTML = '<i class="fas fa-search"></i> No cars found matching "' + searchTerm + '"';
                carList.appendChild(noResultsDiv);
            }
        }
        
        searchInput.addEventListener('keyup', filterCars);
        
        // Remove selected class from all cars
        function removeSelectedFromAllCars() {
            document.querySelectorAll('.car-item').forEach(item => {
                item.classList.remove('selected');
            });
        }
        
        // Clear price summary function
        function clearPriceSummary() {
            document.getElementById('dailyRate').innerHTML = '--';
            document.getElementById('daysCount').innerHTML = '--';
            document.getElementById('subtotal').innerHTML = '--';
            document.getElementById('totalCarPrice').innerHTML = '--';
            document.getElementById('grandTotalDisplay').innerHTML = '--';
            document.getElementById('discountRow').style.display = 'none';
            document.getElementById('insuranceSummaryRow').style.display = 'none';
            document.getElementById('extrasSummaryRow').style.display = 'none';
            currentDays = 0;
            currentCarTotal = 0;
            calculateGrandTotal();
        }
        
        // Select a single car
        function selectCar(carId, carName, carPlate, carImage, carPrice) {
            // Remove selected class from all cars first
            removeSelectedFromAllCars();
            
            // Add selected class to the clicked car
            const selectedItem = document.querySelector(`.car-item[data-car-id="${carId}"]`);
            if(selectedItem) selectedItem.classList.add('selected');
            
            document.getElementById('selected_car_id').value = carId;
            currentCarId = carId;
            currentCarBasePrice = parseFloat(carPrice) || carData[carId]?.basePrice || 0;
            
            // Update preview
            const previewDiv = document.getElementById('selectedCarPreview');
            const imageUrl = carImage ? '../' + carImage : 'https://placehold.co/80x60?text=Car';
            previewDiv.innerHTML = `
                <div class="selected-car-preview">
                    <img src="${imageUrl}" class="selected-car-preview-img" onerror="this.src='https://placehold.co/80x60?text=Car'">
                    <div class="selected-car-preview-info">
                        <div class="selected-car-preview-name">${escapeHtml(carName)}</div>
                        <div class="selected-car-preview-plate">${escapeHtml(carPlate)}</div>
                        <div class="selected-car-preview-price">Base price: €${currentCarBasePrice.toFixed(2)}/day</div>
                    </div>
                </div>
            `;
            
            // Recalculate price and availability
            calculatePriceAndAvailability();
        }
        
        // Function to refresh available cars based on current dates (AJAX call to same file)
        async function refreshAvailableCars() {
            if(isRefreshingCars) return;
            isRefreshingCars = true;
            
            const pickup = pickupDate ? pickupDate.value : '';
            const dropoff = dropoffDate ? dropoffDate.value : '';
            const pTime = pickupTime ? (pickupTime.value || '10:00') : '10:00';
            const dTime = dropoffTime ? (dropoffTime.value || '10:00') : '10:00';
            
            if(pickup && dropoff && pickup <= dropoff) {
                // Show loading state
                const countDiv = document.getElementById('availableCarsCount');
                countDiv.innerHTML = '<span class="loading-spinner"></span> Checking available cars...';
                countDiv.style.background = '#fef3c7';
                countDiv.style.color = '#92400e';
                
                try {
                    const response = await fetch(`?ajax_available_cars=1&pickup_date=${pickup}&pickup_time=${pTime}&dropoff_date=${dropoff}&dropoff_time=${dTime}`);
                    const data = await response.json();
                    
                    const carList = document.getElementById('carList');
                    const currentSelectedId = currentCarId;
                    let selectedCarStillAvailable = false;
                    
                    if(data.cars && data.cars.length > 0) {
                        carList.innerHTML = '';
                        data.cars.forEach(car => {
                            const carDiv = document.createElement('div');
                            carDiv.className = 'car-item';
                            if(currentSelectedId == car.id) {
                                carDiv.classList.add('selected');
                                selectedCarStillAvailable = true;
                            }
                            carDiv.setAttribute('data-car-id', car.id);
                            carDiv.setAttribute('data-car-name', car.brand + ' ' + car.model);
                            carDiv.setAttribute('data-car-plate', car.license_plate);
                            carDiv.setAttribute('data-car-image', car.image_url);
                            carDiv.setAttribute('data-car-price', car.base_price);
                            carDiv.setAttribute('data-searchable', (car.brand + ' ' + car.model + ' ' + car.license_plate).toLowerCase());
                            carDiv.innerHTML = `
                                <span class="car-name">${escapeHtml(car.brand + ' ' + car.model)}</span>
                                <div style="display: flex; gap: 8px; align-items: center;">
                                    <span class="car-price">€${parseFloat(car.base_price).toFixed(2)}/day</span>
                                    <span class="car-plate">${escapeHtml(car.license_plate)}</span>
                                </div>
                            `;
                            carDiv.onclick = () => selectCar(car.id, car.brand + ' ' + car.model, car.license_plate, car.image_url, car.base_price);
                            carList.appendChild(carDiv);
                        });
                        
                        // If current selected car is no longer available, clear selection and price
                        if(currentSelectedId && !selectedCarStillAvailable) {
                            currentCarId = 0;
                            document.getElementById('selected_car_id').value = '';
                            document.getElementById('selectedCarPreview').innerHTML = `
                                <div class="no-car-selected">
                                    <i class="fas fa-info-circle"></i> Previously selected car is no longer available. Please select another.
                                </div>
                            `;
                            if(availabilityDiv) {
                                availabilityDiv.style.display = 'flex';
                                availabilityDiv.className = 'availability-status availability-unavailable';
                                availabilityDiv.innerHTML = '<i class="fas fa-times-circle"></i> The car is not available for the selected dates. Please choose different dates.';
                            }
                            submitBtn.disabled = true;
                            // Clear price summary
                            clearPriceSummary();
                        } else if(selectedCarStillAvailable) {
                            // Car still available, recalculate price
                            calculatePriceAndAvailability();
                        }
                        
                        countDiv.innerHTML = `<i class="fas fa-check-circle"></i> ${data.cars.length} cars available for selected dates`;
                        countDiv.style.background = '#d1fae5';
                        countDiv.style.color = '#065f46';
                    } else {
                        carList.innerHTML = '<div class="no-results"><i class="fas fa-info-circle"></i> No cars available for selected dates</div>';
                        countDiv.innerHTML = `<i class="fas fa-exclamation-triangle"></i> No cars available for selected dates`;
                        countDiv.style.background = '#fee2e2';
                        countDiv.style.color = '#991b1b';
                        
                        // Clear selected car if no cars available
                        if(currentCarId) {
                            currentCarId = 0;
                            document.getElementById('selected_car_id').value = '';
                            document.getElementById('selectedCarPreview').innerHTML = `
                                <div class="no-car-selected">
                                    <i class="fas fa-info-circle"></i> No cars available for selected dates.
                                </div>
                            `;
                            if(availabilityDiv) {
                                availabilityDiv.style.display = 'flex';
                                availabilityDiv.className = 'availability-status availability-unavailable';
                                availabilityDiv.innerHTML = '<i class="fas fa-times-circle"></i> No cars available for the selected dates. Please choose different dates.';
                            }
                            submitBtn.disabled = true;
                            // Clear price summary
                            clearPriceSummary();
                        }
                    }
                } catch(e) {
                    console.error('Error refreshing cars:', e);
                    countDiv.innerHTML = `<i class="fas fa-exclamation-triangle"></i> Error loading available cars`;
                    countDiv.style.background = '#fee2e2';
                    countDiv.style.color = '#991b1b';
                } finally {
                    isRefreshingCars = false;
                }
            } else {
                const countDiv = document.getElementById('availableCarsCount');
                countDiv.innerHTML = `<i class="fas fa-info-circle"></i> Select valid dates to see available cars`;
                countDiv.style.background = '#fef3c7';
                countDiv.style.color = '#92400e';
            }
        }
        
        // Date validation
        const today = new Date();
        const tomorrow = new Date(today);
        tomorrow.setDate(tomorrow.getDate() + 1);
        if(pickupDate) pickupDate.min = today.toISOString().split('T')[0];
        if(dropoffDate) dropoffDate.min = tomorrow.toISOString().split('T')[0];
        
        if(pickupDate) {
            pickupDate.addEventListener('change', function() {
                const pickup = new Date(this.value);
                const nextDay = new Date(pickup);
                nextDay.setDate(pickup.getDate() + 1);
                if(dropoffDate) {
                    dropoffDate.min = nextDay.toISOString().split('T')[0];
                    if(new Date(dropoffDate.value) <= pickup) {
                        dropoffDate.value = nextDay.toISOString().split('T')[0];
                    }
                }
                calculatePriceAndAvailability();
                refreshAvailableCars();
            });
        }
        
        async function calculatePriceAndAvailability() {
            const carId = currentCarId;
            const pickup = pickupDate ? pickupDate.value : '';
            const dropoff = dropoffDate ? dropoffDate.value : '';
            const pTime = pickupTime ? (pickupTime.value || '10:00') : '10:00';
            const dTime = dropoffTime ? (dropoffTime.value || '10:00') : '10:00';
            
            if(carId && pickup && dropoff && pickup <= dropoff) {
                try {
                    const priceRes = await fetch(`../ajax-price.php?car_id=${carId}&start=${pickup}&end=${dropoff}&pickup_time=${pTime}&dropoff_time=${dTime}`);
                    const priceData = await priceRes.json();
                    
                    currentDays = priceData.days;
                    currentCarTotal = priceData.total_price;
                    currentDiscountPercent = priceData.discount_percent;
                    currentDiscountAmount = priceData.discount_amount;
                    
                    document.getElementById('dailyRate').innerHTML = `€${priceData.base_price || '0'}`;
                    document.getElementById('daysCount').innerHTML = priceData.days;
                    document.getElementById('subtotal').innerHTML = `€${priceData.subtotal.toFixed(2)}`;
                    document.getElementById('totalCarPrice').innerHTML = `€${priceData.total_price.toFixed(2)}`;
                    
                    // Show discount if exists
                    if(priceData.discount_amount > 0) {
                        document.getElementById('discountPercent').innerHTML = priceData.discount_percent;
                        document.getElementById('discountAmount').innerHTML = `-€${priceData.discount_amount.toFixed(2)}`;
                        document.getElementById('discountRow').style.display = 'flex';
                    } else {
                        document.getElementById('discountRow').style.display = 'none';
                    }
                    
                    await checkAvailability();
                    calculateGrandTotal();
                } catch(e) {
                    console.error('Error:', e);
                }
            } else {
                clearPriceSummary();
                if(availabilityDiv) availabilityDiv.style.display = 'none';
                submitBtn.disabled = true;
            }
        }
        
        async function checkAvailability() {
            const carId = currentCarId;
            const pickup = pickupDate ? pickupDate.value : '';
            const dropoff = dropoffDate ? dropoffDate.value : '';
            const pTime = pickupTime ? (pickupTime.value || '10:00') : '10:00';
            const dTime = dropoffTime ? (dropoffTime.value || '10:00') : '10:00';
            
            if(!carId) {
                if(availabilityDiv) {
                    availabilityDiv.style.display = 'flex';
                    availabilityDiv.className = 'availability-status availability-unavailable';
                    availabilityDiv.innerHTML = '<i class="fas fa-exclamation-triangle"></i> Please select a car first';
                }
                submitBtn.disabled = true;
                return;
            }
            
            if(carId && pickup && dropoff && pickup <= dropoff) {
                try {
                    const response = await fetch(`../ajax-check-availability.php?car_id=${carId}&pickup_date=${pickup}&pickup_time=${pTime}&dropoff_date=${dropoff}&dropoff_time=${dTime}&prep_hours=2`);
                    const data = await response.json();
                    
                    if(availabilityDiv) {
                        if(data.available) {
                            availabilityDiv.style.display = 'none';
                            submitBtn.disabled = false;
                        } else {
                            availabilityDiv.style.display = 'flex';
                            availabilityDiv.className = 'availability-status availability-unavailable';
                            availabilityDiv.innerHTML = '<i class="fas fa-times-circle"></i> ' + (data.reason || 'Car is not available for these dates/times');
                            submitBtn.disabled = true;
                        }
                    }
                } catch(e) {
                    console.error('Availability check error:', e);
                }
            } else {
                if(availabilityDiv) availabilityDiv.style.display = 'none';
                submitBtn.disabled = (pickup && dropoff && pickup > dropoff);
            }
        }
        
        // Calculate grand total including extras
        function calculateGrandTotal() {
            const days = currentDays;
            let insurancePrice = 0;
            let selectedInsuranceId = null;
            
            // Get selected insurance
            const insuranceRadios = document.querySelectorAll('#reservationForm input[name="insurance_radio"]');
            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 = [];
            
            // Quantity dropdowns
            const quantitySelects = document.querySelectorAll('#reservationForm .option-quantity');
            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
                    });
                }
            }
            
            // Toggle switches
            const toggles = document.querySelectorAll('#reservationForm .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
                    });
                }
            }
            
            // Update hidden fields
            document.getElementById('selected_insurance_id').value = selectedInsuranceId || '';
            document.getElementById('selected_options').value = JSON.stringify(selectedOptions);
            
            // Update display
            const grandTotal = currentCarTotal + insurancePrice + extrasTotal;
            
            const insuranceRow = document.getElementById('insuranceSummaryRow');
            const insuranceDisplay = document.getElementById('insuranceSummaryDisplay');
            if(insurancePrice > 0) {
                insuranceRow.style.display = 'flex';
                insuranceDisplay.innerText = '€' + insurancePrice.toFixed(2);
            } else {
                insuranceRow.style.display = 'none';
            }
            
            const extrasRow = document.getElementById('extrasSummaryRow');
            const extrasDisplay = document.getElementById('extrasSummaryDisplay');
            if(extrasTotal > 0) {
                extrasRow.style.display = 'flex';
                extrasDisplay.innerText = '€' + extrasTotal.toFixed(2);
            } else {
                extrasRow.style.display = 'none';
            }
            
            const grandTotalDisplay = document.getElementById('grandTotalDisplay');
            if(grandTotalDisplay && currentCarTotal > 0) {
                grandTotalDisplay.innerText = '€' + grandTotal.toFixed(2);
            } else if(grandTotalDisplay) {
                grandTotalDisplay.innerText = '--';
            }
        }
        
        // Location same as pickup handler
        const pickupSelect = document.getElementById('pickup_location');
        const dropoffSelect = document.getElementById('dropoff_location');
        
        function updateDropoff() {
            if(dropoffSelect && dropoffSelect.value === 'same' && pickupSelect && pickupSelect.value) {
                dropoffSelect.value = pickupSelect.value;
            }
        }
        
        if(pickupSelect && dropoffSelect) {
            pickupSelect.addEventListener('change', updateDropoff);
            dropoffSelect.addEventListener('change', function() {
                if(this.value === 'same' && pickupSelect && pickupSelect.value) {
                    this.value = pickupSelect.value;
                }
            });
        }
        
        function escapeHtml(text) {
            if(!text) return '';
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        
        // Event listeners
        if(pickupTime) pickupTime.addEventListener('change', () => { checkAvailability(); refreshAvailableCars(); });
        if(dropoffTime) dropoffTime.addEventListener('change', () => { checkAvailability(); refreshAvailableCars(); });
        if(dropoffDate) dropoffDate.addEventListener('change', () => { calculatePriceAndAvailability(); refreshAvailableCars(); });
        
        // Attach event listeners for extras
        document.addEventListener('DOMContentLoaded', function() {
            const insuranceRadios = document.querySelectorAll('#reservationForm input[name="insurance_radio"]');
            const quantitySelects = document.querySelectorAll('#reservationForm .option-quantity');
            const toggles = document.querySelectorAll('#reservationForm .option-toggle');
            
            insuranceRadios.forEach(el => el.addEventListener('change', calculateGrandTotal));
            quantitySelects.forEach(el => el.addEventListener('change', calculateGrandTotal));
            toggles.forEach(el => el.addEventListener('change', calculateGrandTotal));
            
            if(currentCarId) calculatePriceAndAvailability();
        });
        
        // Initial refresh of available cars
        refreshAvailableCars();
    </script>
</body>
</html>