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

require_once 'includes/config.php';

$PREPARATION_HOURS = PREPARATION_HOURS;

$car_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if($car_id == 0) {
    header('Location: index.php');
    exit();
}

$stmt = $pdo->prepare("SELECT * FROM cars WHERE id = ?");
$stmt->execute([$car_id]);
$car = $stmt->fetch(PDO::FETCH_ASSOC);

if(!$car) {
    die("Car not found!");
}

// Get URL parameters
$url_pickup_location = isset($_GET['pickup_location']) ? urldecode($_GET['pickup_location']) : '';
$url_dropoff_location = isset($_GET['dropoff_location']) ? urldecode($_GET['dropoff_location']) : '';
$url_pickup_date = isset($_GET['pickup_date']) ? $_GET['pickup_date'] : '';
$url_pickup_time = isset($_GET['pickup_time']) ? $_GET['pickup_time'] : '10:00';
$url_dropoff_date = isset($_GET['dropoff_date']) ? $_GET['dropoff_date'] : '';
$url_dropoff_time = isset($_GET['dropoff_time']) ? $_GET['dropoff_time'] : '10:00';

if($url_dropoff_location == 'same') {
    $url_dropoff_location = $url_pickup_location;
}

$success = false;
$error = '';
$last_reservation_code = '';
$last_customer_phone = '';

$csrf_token = generateCSRFToken();

if (!isset($_SESSION['step1_data'])) {
    $_SESSION['step1_data'] = [];
}

$time_options = [];
for($hour = 0; $hour <= 23; $hour++) {
    $hour_str = str_pad($hour, 2, '0', STR_PAD_LEFT);
    $time_options[] = $hour_str . ':00';
}

if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['step1'])) {
    if(!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $error = "Security validation failed. Please try again.";
    } else {
        $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'];
        $name = trim($_POST['name']);
        $email = trim($_POST['email']);
        $phone = trim($_POST['phone']);
        $notes = trim($_POST['notes'] ?? '');
        
        $errors = [];
        if(empty($name)) $errors[] = t('car_details_name_required');
        if(empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = t('car_details_email_required');
        if(empty($phone)) $errors[] = t('car_details_phone_required');
        if(empty($pickup_location)) $errors[] = t('car_details_location_required');
        if(empty($dropoff_location)) $errors[] = t('car_details_location_required');
        
        if($pickup_date > $dropoff_date) {
            $errors[] = t('car_details_date_invalid');
        }
        
        if($pickup_date == $dropoff_date && $pickup_time >= $dropoff_time) {
            $errors[] = t('car_details_time_invalid');
        }
        
        if(empty($errors)) {
            $availability = isGroupAvailable($car_id, $pickup_date, $pickup_time, $dropoff_date, $dropoff_time, $pdo, null, $PREPARATION_HOURS);
            
            if(!$availability['available']) {
                $error = $availability['reason'] ?: t('car_details_not_available');
            } else {
                $_SESSION['step1_data'] = [
                    'pickup_location' => $pickup_location,
                    'dropoff_location' => $dropoff_location,
                    'pickup_date' => $pickup_date,
                    'pickup_time' => $pickup_time,
                    'dropoff_date' => $dropoff_date,
                    'dropoff_time' => $dropoff_time,
                    'name' => $name,
                    'email' => $email,
                    'phone' => $phone,
                    'notes' => $notes
                ];
                $_SESSION['step'] = 2;
                header("Location: car-details.php?id=$car_id");
                exit();
            }
        } else {
            $error = implode("<br>", $errors);
        }
    }
}

if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['step2'])) {
    if(!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $error = "Security validation failed. Please try again.";
    } else {
        $step1 = $_SESSION['step1_data'];
        if(empty($step1)) {
            $_SESSION['step'] = 1;
            header("Location: car-details.php?id=$car_id");
            exit();
        }
        
        $pickup_location = $step1['pickup_location'];
        $dropoff_location = $step1['dropoff_location'];
        $pickup_date = $step1['pickup_date'];
        $pickup_time = $step1['pickup_time'];
        $dropoff_date = $step1['dropoff_date'];
        $dropoff_time = $step1['dropoff_time'];
        $name = $step1['name'];
        $email = $step1['email'];
        $phone = $step1['phone'];
        $notes = $step1['notes'];
        
        $selected_insurance_id = !empty($_POST['selected_insurance_id']) ? (int)$_POST['selected_insurance_id'] : null;
        $selected_options = !empty($_POST['selected_options']) ? $_POST['selected_options'] : null;
        
$price_data = calculateDynamicPrice($car_id, $pickup_date, $pickup_time, $dropoff_date, $dropoff_time, $pdo);
$days = $price_data['days'];
        $total_price = $price_data['total_price'];
        
        $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 = isGroupAvailable($car_id, $pickup_date, $pickup_time, $dropoff_date, $dropoff_time, $pdo, null, $PREPARATION_HOURS);
        
        if(!$availability['available']) {
            $error = $availability['reason'] ?: t('car_details_not_available');
            $_SESSION['step'] = 1;
        } else {
            // car_id i caktuar realisht per rezervimin (mund te jete nje nga makinat identike te grupit)
            $assigned_car_id = $availability['assigned_car_id'] ?: $car_id;
            
            $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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 'unpaid', ?, ?, ?, ?, ?, ?)";
            $stmt = $pdo->prepare($sql);
            
            try {
                if($stmt->execute([$reservation_code, $assigned_car_id, $pickup_location, $dropoff_location, $pickup_date, $pickup_time, $dropoff_date, $dropoff_time, $days, $total_price, $balance, $name, $email, $phone, $notes, $selected_insurance_id, $selected_insurance_price, $selected_options, $extras_total, $grand_total, $total_price])) {
                    $success = true;
                    $last_reservation_code = $reservation_code;
                    $last_customer_phone = $phone;
                    
                    $car_stmt = $pdo->prepare("SELECT * FROM cars WHERE id = ?");
                    $car_stmt->execute([$assigned_car_id]);
                    $car_data_email = $car_stmt->fetch(PDO::FETCH_ASSOC);
                    
                    $booking_data_email = [
                        'reservation_code' => $reservation_code,
                        'customer_name' => $name,
                        'customer_email' => $email,
                        'customer_phone' => $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
                    ];
                    
                    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");
                    }
                    
                    unset($_SESSION['step1_data']);
                    unset($_SESSION['step']);
                } else {
                    $error = "Error creating reservation. Please try again.";
                }
            } catch (PDOException $e) {
                $error = "Database error: " . $e->getMessage();
            }
        }
    }
}

if(isset($_GET['reset'])) {
    unset($_SESSION['step1_data']);
    unset($_SESSION['step']);
    header("Location: car-details.php?id=$car_id");
    exit();
}

$current_step = isset($_SESSION['step']) ? $_SESSION['step'] : 1;
$step1_data = $_SESSION['step1_data'] ?? [];

$default_pickup_date = $step1_data['pickup_date'] ?? ($url_pickup_date ?: date('Y-m-d'));
$default_dropoff_date = $step1_data['dropoff_date'] ?? ($url_dropoff_date ?: date('Y-m-d', strtotime('+3 days')));
$default_pickup_time = $step1_data['pickup_time'] ?? ($url_pickup_time ?: '10:00');
$default_dropoff_time = $step1_data['dropoff_time'] ?? ($url_dropoff_time ?: '10:00');
$default_pickup_location = $step1_data['pickup_location'] ?? $url_pickup_location;
$default_dropoff_location = $step1_data['dropoff_location'] ?? $url_dropoff_location;
$default_name = $step1_data['name'] ?? '';
$default_email = $step1_data['email'] ?? '';
$default_phone = $step1_data['phone'] ?? '';
$default_notes = $step1_data['notes'] ?? '';

$price_data = calculateDynamicPrice($car_id, $default_pickup_date, $default_pickup_time, $default_dropoff_date, $default_dropoff_time, $pdo);

$availability_result = isCarAvailable(
    $car_id, 
    $default_pickup_date, 
    $default_pickup_time, 
    $default_dropoff_date, 
    $default_dropoff_time, 
    $pdo, 
    null, 
    $PREPARATION_HOURS
);
$is_available = $availability_result['available'];
$availability_reason = $availability_result['reason'];

$key_features = [];
if(!empty($car['key_features'])) {
    $key_features = explode("\n", trim($car['key_features']));
    $key_features = array_map('trim', $key_features);
    $key_features = array_filter($key_features);
}

$cancellation_policy = getSetting('cancellation_policy', $pdo, 'Free cancellation up to 24 hours before pickup.');

$insurance_types = getInsuranceTypes($pdo);
$additional_options = getAdditionalOptions($pdo);

$type_labels = [
    'economy' => t('car_type_economy'),
    'sedan' => t('car_type_sedan'),
    'suv' => t('car_type_suv'),
    '7-seats' => t('car_type_7seats'),
    'cabrio' => t('car_type_cabrio'),
    'luxury' => t('car_type_luxury')
];

$page_title = $car['brand'] . ' ' . $car['model'] . ' - ' . t('car_details_title');

require_once 'header.php';
?>

<!DOCTYPE html>
<html lang="<?php echo getCurrentLanguage(); ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover, user-scalable=yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="format-detection" content="telephone=yes">
    <title><?php echo sanitize($page_title); ?></title>
    <style>
        :root {
            --primary: #0066ff;
            --primary-dark: #0052cc;
            --secondary: #1a1f36;
            --text-light: #5a6e8a;
            --bg-light: #f8fafc;
            --white: #ffffff;
            --border: #eef2f6;
            --success: #10b981;
            --danger: #ef4444;
            --warning: #f59e0b;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            -webkit-tap-highlight-color: transparent;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
            background: var(--bg-light);
            color: var(--secondary);
            line-height: 1.5;
            overflow-x: hidden;
            -webkit-font-smoothing: antialiased;
        }

        .container { 
            max-width: 1300px; 
            margin: 0 auto; 
            padding: 20px 5%;
        }
        
        .car-detail-grid { 
            display: grid; 
            grid-template-columns: 1fr 450px; 
            gap: 32px; 
        }
        
        .car-gallery { 
            background: white; 
            border-radius: 24px; 
            border: 1px solid var(--border); 
            overflow: hidden; 
            margin-bottom: 24px; 
        }
        .main-image { 
            width: 100%; 
            height: auto;
            min-height: 300px;
            max-height: 400px;
            object-fit: cover; 
        }
        .car-info { padding: 24px; }
        
        .car-brand-model { 
            margin-bottom: 12px;
        }
        .car-brand {
            font-size: 28px;
            font-weight: 800;
            color: #000000;
            letter-spacing: -0.5px;
            line-height: 1.2;
        }
        .car-model {
            font-size: 20px;
            font-weight: 500;
            color: #555555;
            line-height: 1.3;
        }
        
        .car-meta { 
            display: flex; 
            flex-wrap: wrap; 
            gap: 24px; 
            margin-bottom: 24px; 
            padding-bottom: 20px; 
            border-bottom: 1px solid var(--border); 
        }
        .meta-item { 
            display: flex; 
            align-items: center; 
            gap: 8px; 
            font-size: 14px; 
            color: var(--text-light); 
        }
        .meta-item i { color: var(--primary); width: 16px; }
        
        .specs-grid { 
            display: grid; 
            grid-template-columns: repeat(4, 1fr); 
            gap: 16px; 
            margin-bottom: 24px; 
            padding: 20px; 
            background: var(--bg-light); 
            border-radius: 20px; 
        }
        .spec-item { text-align: center; }
        .spec-item i { 
            font-size: 24px; 
            color: var(--primary); 
            margin-bottom: 8px; 
            display: block; 
        }
        .spec-label { 
            font-size: 11px; 
            color: var(--text-light); 
            text-transform: uppercase; 
        }
        .spec-value { 
            font-weight: 600; 
            font-size: 14px; 
            margin-top: 4px; 
        }
        
        .description-section { margin-bottom: 24px; }
        .description-section h3 { 
            font-size: 18px; 
            font-weight: 600; 
            margin-bottom: 12px; 
        }
        .description-section p { 
            color: var(--text-light); 
            line-height: 1.6; 
            font-size: 15px; 
        }
        
        .features-section { margin-bottom: 24px; }
        .features-section h3 { 
            font-size: 18px; 
            font-weight: 600; 
            margin-bottom: 12px; 
        }
        .features-list { 
            display: grid; 
            grid-template-columns: repeat(2, 1fr); 
            gap: 10px; 
        }
        .feature-item { 
            display: flex; 
            align-items: center; 
            gap: 8px; 
            font-size: 14px; 
            color: var(--text-light); 
        }
        .feature-item i { color: var(--success); font-size: 14px; }
        
        .policy-box { 
            background: var(--bg-light); 
            padding: 16px 20px; 
            border-radius: 16px; 
            margin-top: 24px; 
        }
        .policy-box h4 { 
            font-size: 14px; 
            font-weight: 600; 
            margin-bottom: 8px; 
        }
        .policy-box p { 
            font-size: 13px; 
            color: var(--text-light); 
        }
        
        .booking-card {
            background: white;
            border-radius: 24px;
            border: 1px solid var(--border);
            overflow: hidden;
            position: sticky;
            top: 20px;
        }
        
        .step-indicator {
            display: flex;
            background: var(--bg-light);
            border-bottom: 1px solid var(--border);
            padding: 16px 20px;
        }
        .step {
            flex: 1;
            text-align: center;
            position: relative;
        }
        .step-number {
            width: 32px;
            height: 32px;
            background: #e5e7eb;
            color: #6b7280;
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 14px;
            margin-bottom: 6px;
        }
        .step.active .step-number {
            background: var(--primary);
            color: white;
        }
        .step.completed .step-number {
            background: var(--success);
            color: white;
        }
        .step-label {
            font-size: 11px;
            font-weight: 500;
            color: #6b7280;
        }
        .step.active .step-label {
            color: var(--primary);
            font-weight: 600;
        }
        .step.completed .step-label {
            color: var(--success);
        }
        .step-line {
            position: absolute;
            top: 16px;
            left: 50%;
            width: 100%;
            height: 2px;
            background: #e5e7eb;
            z-index: 0;
        }
        .step:first-child .step-line { display: none; }
        
        .form-container {
            padding: 20px;
        }
        
        .price-header {
            text-align: center;
            padding-bottom: 16px;
            margin-bottom: 16px;
            border-bottom: 1px solid var(--border);
        }
        .daily-price { 
            font-size: clamp(28px, 6vw, 32px); 
            font-weight: 700; 
            color: var(--primary); 
        }
        .daily-price small { 
            font-size: 13px; 
            font-weight: normal; 
            color: var(--text-light); 
        }
        .price-note { 
            font-size: 11px; 
            color: var(--text-light); 
            margin-top: 4px; 
        }
        
        .availability-status {
            text-align: center;
            margin-bottom: 16px;
            padding: 12px;
            border-radius: 14px;
            font-size: 14px;
            font-weight: 500;
        }
        .availability-available { background: #d1fae5; color: #065f46; }
        .availability-unavailable { background: #fee2e2; color: #991b1b; }
        
        .alert-error { 
            background: #fee2e2; 
            color: #991b1b; 
            padding: 12px; 
            border-radius: 14px; 
            margin-bottom: 16px; 
            font-size: 13px; 
        }
        .alert-success { 
            background: #d1fae5; 
            color: #065f46; 
            padding: 12px; 
            border-radius: 14px; 
            margin-bottom: 16px; 
            font-size: 13px; 
        }
        
        .form-group { margin-bottom: 16px; }
        .form-group label { 
            display: block; 
            margin-bottom: 6px; 
            font-weight: 600; 
            font-size: 13px; 
            color: var(--secondary); 
        }
        .form-group label .required { color: var(--danger); }
        .form-group input, 
        .form-group select, 
        .form-group textarea { 
            width: 100%; 
            padding: 12px 14px; 
            border: 2px solid var(--border); 
            border-radius: 14px; 
            font-size: 16px;
            transition: all 0.3s; 
            font-family: inherit;
            -webkit-appearance: none;
            appearance: none;
        }
        .form-group select {
            background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="%236b7280" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9"></polyline></svg>');
            background-repeat: no-repeat;
            background-position: right 14px center;
            padding-right: 40px;
        }
        .form-group input:focus, 
        .form-group select:focus, 
        .form-group textarea:focus { 
            outline: none; 
            border-color: var(--primary); 
            box-shadow: 0 0 0 4px rgba(0,102,255,0.1); 
        }
        .form-row { 
            display: grid; 
            grid-template-columns: 1fr 1fr; 
            gap: 12px; 
        }
        
        .time-select {
            font-family: monospace;
            font-size: 16px;
            background: white;
            cursor: pointer;
        }
        
        .extras-section {
            margin: 20px 0;
            padding: 16px;
            background: var(--bg-light);
            border-radius: 20px;
        }
        .extras-section h4 {
            margin-bottom: 16px;
            font-size: 16px;
            font-weight: 600;
        }
        .insurance-option, .option-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 12px;
            margin-bottom: 8px;
            background: white;
            border-radius: 14px;
            border: 1px solid var(--border);
            transition: all 0.2s;
        }
        .insurance-option {
            cursor: pointer;
        }
        .insurance-option:hover, .option-item:hover {
            border-color: var(--primary);
        }
        .option-item {
            cursor: default;
        }
        .insurance-option input {
            margin-right: 12px;
            width: 18px;
            height: 18px;
        }
        .option-desc {
            font-size: 11px;
            color: var(--text-light);
            margin-top: 3px;
        }
        .option-icon {
            width: 28px;
            font-size: 16px;
            color: var(--primary);
            text-align: center;
        }
        .option-price-badge {
            font-weight: 600;
            color: var(--primary);
            font-size: 13px;
            min-width: 70px;
            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: 70px;
            padding: 8px;
            border-radius: 10px;
            border: 1px solid var(--border);
            font-size: 14px;
            text-align: center;
        }
        
        .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: var(--primary);
        }
        .toggle-switch input:checked + .toggle-slider:before {
            transform: translateX(22px);
        }
        
        .price-summary {
            background: var(--bg-light);
            border-radius: 16px;
            padding: 16px;
            margin: 20px 0;
        }
        .summary-row {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            font-size: 14px;
        }
        .summary-row:not(:last-child) {
            border-bottom: 1px solid var(--border);
        }
        .summary-row.total {
            font-weight: 700;
            color: var(--primary);
            font-size: 17px;
            border-bottom: none;
            padding-top: 10px;
        }
        .discount-row {
            color: var(--success);
        }
        
        .btn-next, .btn-back, .btn-book {
            width: 100%;
            padding: 16px;
            border: none;
            border-radius: 16px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            margin-top: 8px;
            -webkit-tap-highlight-color: transparent;
        }
        .btn-next, .btn-book {
            background: var(--primary);
            color: white;
        }
        .btn-next:active, .btn-book:active {
            transform: scale(0.98);
            background: var(--primary-dark);
        }
        .btn-back {
            background: #e5e7eb;
            color: #374151;
            margin-bottom: 8px;
        }
        .btn-back:active {
            transform: scale(0.98);
            background: #d1d5db;
        }
        .btn-next:disabled, .btn-book:disabled {
            background: #9ca3af;
            cursor: not-allowed;
            transform: none;
        }
        
        .button-group {
            display: flex;
            gap: 12px;
            margin-top: 8px;
        }
        .button-group .btn-back {
            flex: 1;
            margin-bottom: 0;
        }
        .button-group .btn-next, .button-group .btn-book {
            flex: 2;
        }
        
        .reset-link {
            text-align: center;
            margin-top: 16px;
        }
        .reset-link a {
            font-size: 13px;
            color: var(--text-light);
            text-decoration: none;
            padding: 8px 16px;
            display: inline-block;
        }
        
        .modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
            -webkit-backdrop-filter: blur(4px);
            backdrop-filter: blur(4px);
        }
        .modal-container {
            background: white;
            border-radius: 28px;
            width: 450px;
            max-width: 90%;
            text-align: center;
            padding: 32px 24px;
            animation: modalSlideIn 0.3s ease;
        }
        @keyframes modalSlideIn {
            from { opacity: 0; transform: translateY(-30px) scale(0.95); }
            to { opacity: 1; transform: translateY(0) scale(1); }
        }
        .modal-icon { font-size: 64px; color: var(--success); margin-bottom: 16px; }
        .modal-container h2 { 
            font-size: clamp(22px, 5vw, 24px); 
            font-weight: 700; 
            margin-bottom: 16px; 
        }
        .modal-reference {
            background: var(--bg-light);
            padding: 12px;
            border-radius: 14px;
            font-family: monospace;
            font-size: 18px;
            font-weight: bold;
            color: var(--primary);
            margin: 16px 0;
        }
        .modal-btn {
            background: var(--primary);
            color: white;
            border: none;
            padding: 14px 28px;
            border-radius: 14px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            margin-top: 20px;
            -webkit-tap-highlight-color: transparent;
        }
        .modal-btn:active {
            transform: scale(0.98);
        }
        
        @media (max-width: 968px) {
            .car-detail-grid { 
                grid-template-columns: 1fr; 
                gap: 24px; 
            }
            .booking-card { 
                position: static; 
            }
            .specs-grid {
                grid-template-columns: repeat(2, 1fr);
                gap: 12px;
            }
            .car-brand {
                font-size: 24px;
            }
            .car-model {
                font-size: 18px;
            }
        }
        @media (max-width: 576px) {
            .container { padding: 16px 4%; }
            .form-row { 
                grid-template-columns: 1fr; 
                gap: 0;
            }
            .insurance-option, .option-item { 
                flex-wrap: wrap; 
            }
            .option-control { 
                width: 100%; 
                justify-content: flex-end; 
                margin-top: 8px; 
            }
            .car-info { padding: 16px; }
            .specs-grid { grid-template-columns: repeat(2, 1fr); }
            .features-list { grid-template-columns: 1fr; }
            .car-brand {
                font-size: 22px;
            }
            .car-model {
                font-size: 16px;
            }
        }
        
        input, select, textarea {
            font-size: 16px !important;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="car-detail-grid">
            <div>
                <div class="car-gallery">
                    <img src="<?php echo !empty($car['image_url']) ? $car['image_url'] : 'https://placehold.co/800x400?text=' . urlencode($car['brand'] . ' ' . $car['model']); ?>" 
                         alt="<?php echo sanitize($car['brand'] . ' ' . $car['model']); ?>" 
                         class="main-image"
                         loading="lazy"
                         onerror="this.src='https://placehold.co/800x400?text=Car+Image'">
                    
                    <div class="car-info">
                        <div class="car-brand-model">
                            <div class="car-brand"><?php echo sanitize($car['brand']); ?></div>
                            <div class="car-model"><?php echo sanitize($car['model']); ?></div>
                        </div>
                        
                        <div class="car-meta">
                            <div class="meta-item"><i class="fas fa-calendar-alt"></i> Year: <?php echo $car['year']; ?></div>
                            <div class="meta-item"><i class="fas fa-gas-pump"></i> <?php echo sanitize($car['fuel_type']); ?></div>
                            <div class="meta-item"><i class="fas fa-cog"></i> <?php echo sanitize($car['transmission']); ?></div>
                        </div>
                        
                        <div class="specs-grid">
                            <div class="spec-item"><i class="fas fa-gas-pump"></i><div class="spec-label">Fuel</div><div class="spec-value"><?php echo sanitize($car['fuel_type']); ?></div></div>
                            <div class="spec-item"><i class="fas fa-cog"></i><div class="spec-label">Transmission</div><div class="spec-value"><?php echo sanitize($car['transmission']); ?></div></div>
                            <div class="spec-item"><i class="fas fa-users"></i><div class="spec-label">Seats</div><div class="spec-value"><?php echo $car['seats']; ?> persons</div></div>
                            <div class="spec-item"><i class="fas fa-suitcase"></i><div class="spec-label">Luggage</div><div class="spec-value"><?php echo $car['luggage']; ?> bags</div></div>
                        </div>
                        
                        <div class="description-section">
                            <h3><?php echo t('car_details_about'); ?></h3>
                            <p><?php echo nl2br(sanitize($car['description'] ?: 'Experience the perfect blend of comfort and performance with this exceptional vehicle.')); ?></p>
                        </div>
                        
                        <?php if(count($key_features) > 0): ?>
                        <div class="features-section">
                            <h3><?php echo t('car_details_features'); ?></h3>
                            <div class="features-list">
                                <?php foreach($key_features as $feature): ?>
                                <div class="feature-item"><i class="fas fa-check-circle"></i> <?php echo sanitize($feature); ?></div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <div class="policy-box">
                            <h4><i class="fas fa-shield-alt"></i> <?php echo t('car_details_cancellation'); ?></h4>
                            <p><?php echo sanitize($cancellation_policy); ?></p>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="booking-card">
                <div class="step-indicator">
                    <div class="step <?php echo $current_step >= 1 ? 'active' : ''; ?> <?php echo $current_step > 1 ? 'completed' : ''; ?>">
                        <div class="step-number">1</div>
                        <div class="step-label"><?php echo t('car_details_step1'); ?></div>
                        <div class="step-line"></div>
                    </div>
                    <div class="step <?php echo $current_step >= 2 ? 'active' : ''; ?> <?php echo $current_step > 2 ? 'completed' : ''; ?>">
                        <div class="step-number">2</div>
                        <div class="step-label"><?php echo t('car_details_step2'); ?></div>
                    </div>
                </div>
                
                <div class="form-container">
                    <div class="price-header">
                        <div class="daily-price">€<?php echo number_format($price_data['base_price'], 2); ?> <small><?php echo t('car_details_daily_price'); ?></small></div>
                        <div class="price-note"><?php echo t('car_details_includes'); ?></div>
                    </div>
                    
                    <div id="step1" style="display: <?php echo $current_step == 1 ? 'block' : 'none'; ?>">
                        <div class="availability-status <?php echo $is_available ? 'availability-available' : 'availability-unavailable'; ?>" id="step1_availability_status">
                            <i class="fas <?php echo $is_available ? 'fa-check-circle' : 'fa-times-circle'; ?>"></i>
                            <?php if($is_available): ?>
                                <?php echo t('car_details_available'); ?>
                            <?php else: ?>
                                <?php echo $availability_reason ?: t('car_details_not_available'); ?>
                            <?php endif; ?>
                        </div>
                        
                        <?php if($error && $current_step == 1): ?>
                            <div class="alert-error"><i class="fas fa-exclamation-circle"></i> <?php echo $error; ?></div>
                        <?php endif; ?>
                        
                        <form method="POST" id="step1Form">
                            <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
                            <input type="hidden" name="step1" value="1">
                            
                            <div class="form-group">
                                <label><?php echo t('car_details_pickup_location'); ?> <span class="required">*</span></label>
                                <select name="pickup_location" id="step1_pickup_location" required>
                                    <option value=""><?php echo t('car_details_select_location'); ?></option>
                                    <option value="Tirana Airport" <?php echo $default_pickup_location == 'Tirana Airport' ? 'selected' : ''; ?>><?php echo t('location_tirana_airport'); ?></option>
                                    <option value="Tirana Center" <?php echo $default_pickup_location == 'Tirana Center' ? 'selected' : ''; ?>><?php echo t('location_tirana_center'); ?></option>
                                    <option value="Durres" <?php echo $default_pickup_location == 'Durres' ? 'selected' : ''; ?>><?php echo t('location_durres'); ?></option>
                                    <option value="Vlore" <?php echo $default_pickup_location == 'Vlore' ? 'selected' : ''; ?>><?php echo t('location_vlore'); ?></option>
                                    <option value="Sarande" <?php echo $default_pickup_location == 'Sarande' ? 'selected' : ''; ?>><?php echo t('location_sarande'); ?></option>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label><?php echo t('car_details_return_location'); ?> <span class="required">*</span></label>
                                <select name="dropoff_location" id="step1_dropoff_location" required>
                                    <option value=""><?php echo t('car_details_select_location'); ?></option>
                                    <option value="same" <?php echo $default_dropoff_location == 'same' ? 'selected' : ''; ?>><?php echo t('car_details_same_as_pickup'); ?></option>
                                    <option value="Tirana Airport" <?php echo $default_dropoff_location == 'Tirana Airport' ? 'selected' : ''; ?>><?php echo t('location_tirana_airport'); ?></option>
                                    <option value="Tirana Center" <?php echo $default_dropoff_location == 'Tirana Center' ? 'selected' : ''; ?>><?php echo t('location_tirana_center'); ?></option>
                                    <option value="Durres" <?php echo $default_dropoff_location == 'Durres' ? 'selected' : ''; ?>><?php echo t('location_durres'); ?></option>
                                    <option value="Vlore" <?php echo $default_dropoff_location == 'Vlore' ? 'selected' : ''; ?>><?php echo t('location_vlore'); ?></option>
                                    <option value="Sarande" <?php echo $default_dropoff_location == 'Sarande' ? 'selected' : ''; ?>><?php echo t('location_sarande'); ?></option>
                                </select>
                            </div>
                            
                            <div class="form-row">
                                <div class="form-group">
                                    <label><?php echo t('car_details_pickup_date'); ?> <span class="required">*</span></label>
                                    <input type="date" name="pickup_date" id="step1_pickup_date" required value="<?php echo $default_pickup_date; ?>">
                                </div>
                                <div class="form-group">
                                    <label><?php echo t('car_details_pickup_time'); ?></label>
                                    <select name="pickup_time" id="step1_pickup_time" class="time-select" required>
                                        <?php foreach($time_options as $time): ?>
                                            <option value="<?php echo $time; ?>" <?php echo $default_pickup_time == $time ? 'selected' : ''; ?>><?php echo $time; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="form-row">
                                <div class="form-group">
                                    <label><?php echo t('car_details_return_date'); ?> <span class="required">*</span></label>
                                    <input type="date" name="dropoff_date" id="step1_dropoff_date" required value="<?php echo $default_dropoff_date; ?>">
                                </div>
                                <div class="form-group">
                                    <label><?php echo t('car_details_return_time'); ?></label>
                                    <select name="dropoff_time" id="step1_dropoff_time" class="time-select" required>
                                        <?php foreach($time_options as $time): ?>
                                            <option value="<?php echo $time; ?>" <?php echo $default_dropoff_time == $time ? 'selected' : ''; ?>><?php echo $time; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label><?php echo t('car_details_full_name'); ?> <span class="required">*</span></label>
                                <input type="text" name="name" placeholder="<?php echo t('car_details_full_name'); ?>" required value="<?php echo htmlspecialchars($default_name); ?>">
                            </div>
                            
                            <div class="form-group">
                                <label><?php echo t('car_details_email'); ?> <span class="required">*</span></label>
                                <input type="email" name="email" placeholder="your@email.com" required value="<?php echo htmlspecialchars($default_email); ?>">
                            </div>
                            
                            <div class="form-group">
                                <label><?php echo t('car_details_phone'); ?> <span class="required">*</span></label>
                                <input type="tel" name="phone" placeholder="+355 XX XXX XXX" required value="<?php echo htmlspecialchars($default_phone); ?>">
                            </div>
                            
                            <div class="form-group">
                                <label><?php echo t('car_details_notes'); ?></label>
                                <textarea name="notes" rows="2" placeholder="<?php echo t('car_details_notes'); ?>"><?php echo htmlspecialchars($default_notes); ?></textarea>
                            </div>
                            
                            <button type="submit" class="btn-next" id="step1_continue_btn"><?php echo t('car_details_continue'); ?></button>
                            
                            <div class="reset-link">
                                <a href="?id=<?php echo $car_id; ?>&reset=1"><?php echo t('car_details_start_over'); ?></a>
                            </div>
                        </form>
                    </div>
                    
                    <div id="step2" style="display: <?php echo $current_step == 2 ? 'block' : 'none'; ?>">
                        <div class="availability-status availability-available" id="step2_availability_status">
                            <i class="fas fa-check-circle"></i> <?php echo t('car_details_available'); ?>
                        </div>
                        
                        <?php if($error && $current_step == 2): ?>
                            <div class="alert-error"><i class="fas fa-exclamation-circle"></i> <?php echo $error; ?></div>
                        <?php endif; ?>
                        
                        <form method="POST" id="step2Form">
                            <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
                            <input type="hidden" name="step2" value="1">
                            <input type="hidden" name="selected_insurance_id" id="selected_insurance_id" value="">
                            <input type="hidden" name="selected_options" id="selected_options" value="">
                            
                            <?php if(count($insurance_types) > 0): ?>
                            <div class="extras-section">
                                <h4><i class="fas fa-shield-alt"></i> <?php echo t('car_details_insurance'); ?></h4>
                                <?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="calculateExtrasTotal()">
                                        <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; ?>
                            </div>
                            <?php endif; ?>
                            
                            <?php if(count($additional_options) > 0): ?>
                            <div class="extras-section">
                                <h4><i class="fas fa-plus-circle"></i> <?php echo t('car_details_extra_options'); ?></h4>
                                <?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="calculateExtrasTotal()">
                                                <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="calculateExtrasTotal()">
                                                <?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; ?>
                            </div>
                            <?php endif; ?>
                            
                            <div class="price-summary" id="priceSummary">
                                <div class="summary-row"><span><?php echo t('car_details_car_rental'); ?> (<?php echo $price_data['days']; ?> <?php echo t('car_details_days'); ?>):</span><span id="carTotalDisplay">€<?php echo number_format($price_data['total_price'], 2); ?></span></div>
                                <?php if($price_data['discount_amount'] > 0): ?>
                                <div class="summary-row discount-row"><span><?php echo t('car_details_discount'); ?> (<?php echo $price_data['discount_percent']; ?>%):</span><span>-€<?php echo number_format($price_data['discount_amount'], 2); ?></span></div>
                                <?php endif; ?>
                                <div class="summary-row" id="insuranceSummaryRow" style="display: none;"><span><?php echo t('car_details_insurance_label'); ?>:</span><span id="insuranceSummaryDisplay">€0.00</span></div>
                                <div class="summary-row" id="extrasSummaryRow" style="display: none;"><span><?php echo t('car_details_extras_label'); ?>:</span><span id="extrasSummaryDisplay">€0.00</span></div>
                                <div class="summary-row total"><span><?php echo t('car_details_total_to_pay'); ?>:</span><span id="totalSummaryDisplay">€<?php echo number_format($price_data['total_price'], 2); ?></span></div>
                            </div>
                            
                            <div class="button-group">
                                <button type="button" class="btn-back" onclick="goToStep1()"><?php echo t('car_details_back'); ?></button>
                                <button type="submit" class="btn-book"><?php echo t('car_details_confirm'); ?></button>
                            </div>
                            
                            <div class="reset-link">
                                <a href="?id=<?php echo $car_id; ?>&reset=1"><?php echo t('car_details_start_over'); ?></a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div id="successModal" class="modal-overlay">
        <div class="modal-container">
            <div class="modal-icon"><i class="fas fa-check-circle"></i></div>
            <h2><?php echo t('car_details_confirmed'); ?></h2>
            <p><?php echo t('car_details_confirmed_text'); ?></p>
            <p><?php echo t('car_details_confirmed_email'); ?></p>
            <div class="modal-reference" id="modalReference">#<?php echo $last_reservation_code ?: 'XXXXXXXX'; ?></div>
            <p><?php echo t('car_details_confirmed_contact'); ?> <strong id="modalPhone"><?php echo $last_customer_phone ?: 'your phone number'; ?></strong> <?php echo t('car_details_confirmed_contact_suffix', 'to confirm.'); ?></p>
            <button class="modal-btn" onclick="goToHome()"><?php echo t('car_details_confirmed_ok'); ?></button>
        </div>
    </div>
    
    <script>
        const carId = <?php echo $car_id; ?>;
        const preparationHours = <?php echo $PREPARATION_HOURS; ?>;
        let currentCarTotal = <?php echo $price_data['total_price']; ?>;
        let currentDiscount = <?php echo $price_data['discount_amount']; ?>;
        let currentDays = <?php echo $price_data['days']; ?>;
        
        <?php if($success === true && !empty($last_reservation_code)): ?>
        document.addEventListener('DOMContentLoaded', function() {
            const modal = document.getElementById('successModal');
            const referenceSpan = document.getElementById('modalReference');
            const phoneSpan = document.getElementById('modalPhone');
            if(referenceSpan) referenceSpan.innerHTML = '#<?php echo $last_reservation_code; ?>';
            if(phoneSpan) phoneSpan.innerHTML = '<?php echo $last_customer_phone; ?>';
            if(modal) modal.style.display = 'flex';
        });
        <?php endif; ?>
        
        function goToHome() { 
            window.location.href = 'index.php'; 
        }
        
        function goToStep1() {
            window.location.href = '?id=<?php echo $car_id; ?>&reset=1';
        }
        
        const step1PickupDate = document.getElementById('step1_pickup_date');
        const step1PickupTime = document.getElementById('step1_pickup_time');
        const step1DropoffDate = document.getElementById('step1_dropoff_date');
        const step1DropoffTime = document.getElementById('step1_dropoff_time');
        const step1PickupLocation = document.getElementById('step1_pickup_location');
        const step1DropoffLocation = document.getElementById('step1_dropoff_location');
        const step1AvailabilityDiv = document.getElementById('step1_availability_status');
        const step1ContinueBtn = document.getElementById('step1_continue_btn');
        
        async function checkStep1Availability() {
            if(!step1PickupDate || !step1DropoffDate) return;
            
            const pickupDate = step1PickupDate.value;
            const pickupTime = step1PickupTime ? step1PickupTime.value : '10:00';
            const dropoffDate = step1DropoffDate.value;
            const dropoffTime = step1DropoffTime ? step1DropoffTime.value : '10:00';
            
            if(pickupDate && dropoffDate && pickupDate <= dropoffDate) {
                try {
                    const response = await fetch(`ajax-check-availability.php?car_id=${carId}&pickup_date=${pickupDate}&pickup_time=${pickupTime}&dropoff_date=${dropoffDate}&dropoff_time=${dropoffTime}&prep_hours=${preparationHours}`);
                    const data = await response.json();
                    
                    if(step1AvailabilityDiv) {
                        if(data.available) {
                            step1AvailabilityDiv.className = 'availability-status availability-available';
                            step1AvailabilityDiv.innerHTML = '<i class="fas fa-check-circle"></i> <?php echo t('car_details_available'); ?>';
                            if(step1ContinueBtn) step1ContinueBtn.disabled = false;
                        } else {
                            step1AvailabilityDiv.className = 'availability-status availability-unavailable';
                            step1AvailabilityDiv.innerHTML = '<i class="fas fa-times-circle"></i> ' + (data.reason || '<?php echo t('car_details_not_available'); ?>');
                            if(step1ContinueBtn) step1ContinueBtn.disabled = true;
                        }
                    }
                } catch(e) { 
                    console.error('Availability check error:', e);
                    if(step1AvailabilityDiv) {
                        step1AvailabilityDiv.className = 'availability-status availability-unavailable';
                        step1AvailabilityDiv.innerHTML = '<i class="fas fa-exclamation-triangle"></i> <?php echo t('car_details_error_checking'); ?>';
                    }
                }
            } else {
                if(step1AvailabilityDiv) {
                    step1AvailabilityDiv.className = 'availability-status availability-unavailable';
                    step1AvailabilityDiv.innerHTML = '<i class="fas fa-info-circle"></i> <?php echo t('car_details_select_valid_dates'); ?>';
                }
                if(step1ContinueBtn) step1ContinueBtn.disabled = true;
            }
        }
        
        if(step1PickupDate && step1DropoffDate) {
            const today = new Date();
            const tomorrow = new Date(today);
            tomorrow.setDate(today.getDate() + 1);
            
            step1PickupDate.min = today.toISOString().split('T')[0];
            step1DropoffDate.min = tomorrow.toISOString().split('T')[0];
            
            step1PickupDate.addEventListener('change', function() {
                checkStep1Availability();
                const pickupDate = new Date(this.value);
                const nextDay = new Date(pickupDate);
                nextDay.setDate(pickupDate.getDate() + 1);
                step1DropoffDate.min = nextDay.toISOString().split('T')[0];
                if(new Date(step1DropoffDate.value) <= pickupDate) {
                    step1DropoffDate.value = nextDay.toISOString().split('T')[0];
                    checkStep1Availability();
                }
            });
        }
        
        if(step1PickupTime) step1PickupTime.addEventListener('change', checkStep1Availability);
        if(step1DropoffDate) step1DropoffDate.addEventListener('change', checkStep1Availability);
        if(step1DropoffTime) step1DropoffTime.addEventListener('change', checkStep1Availability);
        
        function updateDropoffLocation() {
            if(step1DropoffLocation && step1DropoffLocation.value === 'same' && step1PickupLocation && step1PickupLocation.value) {
                step1DropoffLocation.value = step1PickupLocation.value;
            }
        }
        
        if(step1PickupLocation && step1DropoffLocation) {
            step1PickupLocation.addEventListener('change', updateDropoffLocation);
            step1DropoffLocation.addEventListener('change', function() {
                if(this.value === 'same' && step1PickupLocation && step1PickupLocation.value) {
                    this.value = step1PickupLocation.value;
                }
            });
        }
        
        checkStep1Availability();
        
        function calculateExtrasTotal() {
            const days = currentDays;
            let insurancePrice = 0;
            let selectedInsuranceId = null;
            
            const insuranceRadios = document.querySelectorAll('#step2Form 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 = [];
            
            const quantitySelects = document.querySelectorAll('#step2Form .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
                    });
                }
            }
            
            const toggles = document.querySelectorAll('#step2Form .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
                    });
                }
            }
            
            document.getElementById('selected_insurance_id').value = selectedInsuranceId || '';
            document.getElementById('selected_options').value = JSON.stringify(selectedOptions);
            
            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 totalDisplay = document.getElementById('totalSummaryDisplay');
            if(totalDisplay) totalDisplay.innerText = '€' + grandTotal.toFixed(2);
        }
        
        document.addEventListener('DOMContentLoaded', function() {
            const insuranceRadios = document.querySelectorAll('#step2Form input[name="insurance_radio"]');
            const quantitySelects = document.querySelectorAll('#step2Form .option-quantity');
            const toggles = document.querySelectorAll('#step2Form .option-toggle');
            
            insuranceRadios.forEach(el => el.addEventListener('change', calculateExtrasTotal));
            quantitySelects.forEach(el => el.addEventListener('change', calculateExtrasTotal));
            toggles.forEach(el => el.addEventListener('change', calculateExtrasTotal));
            
            calculateExtrasTotal();
        });
    </script>
</body>
</html>

<?php 
if(file_exists('footer.php')) {
    include 'footer.php';
}
?>