<?php
require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/config/session.php';

if (!function_exists('isLoggedIn') || !isLoggedIn()) {
    $redirectTarget = 'reservation.php';
    if (!empty($_SERVER['QUERY_STRING'])) {
        $redirectTarget .= '?' . $_SERVER['QUERY_STRING'];
    }
    header('Location: login.php?redirect=' . urlencode($redirectTarget));
    exit();
}

$loggedInUserId = function_exists('getCurrentUserId') ? (int)(getCurrentUserId() ?? 0) : 0;
$loggedInName = '';
$loggedInEmail = '';
$loggedInPhone = '';

if ($loggedInUserId > 0) {
    $userStmt = $conn->prepare("SELECT first_name, last_name, email, phone FROM users WHERE id = ? LIMIT 1");
    if ($userStmt) {
        $userStmt->bind_param('i', $loggedInUserId);
        $userStmt->execute();
        $userResult = $userStmt->get_result();
        $userRow = $userResult ? $userResult->fetch_assoc() : null;
        $userStmt->close();

        if ($userRow) {
            $loggedInName = trim((string)($userRow['first_name'] ?? '') . ' ' . (string)($userRow['last_name'] ?? ''));
            $loggedInEmail = trim((string)($userRow['email'] ?? ''));
            $loggedInPhone = trim((string)($userRow['phone'] ?? ''));
        }
    }
}

function reservationRoomTypeKey(string $type): string
{
    $normalized = strtolower(trim($type));
    $normalized = str_replace([' suite', ' room'], '', $normalized);
    $normalized = preg_replace('/[^a-z0-9]+/', '-', $normalized);
    return trim((string)$normalized, '-');
}

$selectedCheckIn = trim((string)($_GET['checkIn'] ?? ''));
$selectedCheckOut = trim((string)($_GET['checkOut'] ?? ''));
$selectedAdults = (int)($_GET['adults'] ?? 2);
$selectedTypeKey = strtolower(trim((string)($_GET['roomType'] ?? '')));
$selectedReservationType = strtolower(trim((string)($_GET['reservation_type'] ?? 'room')));
if ($selectedReservationType !== 'service') {
    $selectedReservationType = 'room';
}
if ($selectedAdults < 1) {
    $selectedAdults = 1;
}

$reservationRooms = [];
$roomSql = "SELECT id, room_type, max_guests, price_per_night, image_url, is_available
            FROM rooms
            WHERE is_available = 1
            ORDER BY price_per_night ASC, id ASC";
$roomResult = $conn->query($roomSql);
if ($roomResult instanceof mysqli_result) {
    while ($row = $roomResult->fetch_assoc()) {
        $typeLabel = trim((string)($row['room_type'] ?? 'Room'));
        $typeKey = reservationRoomTypeKey($typeLabel);
        if ($typeKey === '') {
            $typeKey = 'room';
        }
        $reservationRooms[] = [
            'id' => (int)($row['id'] ?? 0),
            'type' => $typeLabel,
            'type_key' => $typeKey,
            'guests' => (int)($row['max_guests'] ?? 1),
            'price' => (float)($row['price_per_night'] ?? 0),
            'image' => str_replace('\\', '/', trim((string)($row['image_url'] ?? 'images/room/1.webp'))),
        ];
    }
    $roomResult->free();
}

if (empty($reservationRooms)) {
    $reservationRooms = [
        ['id' => 1, 'type' => 'Standard Room', 'type_key' => 'standard', 'guests' => 2, 'price' => 129, 'image' => 'images/room/1.webp'],
        ['id' => 2, 'type' => 'Deluxe Room', 'type_key' => 'deluxe', 'guests' => 2, 'price' => 149, 'image' => 'images/room/2.webp'],
        ['id' => 3, 'type' => 'Premier Room', 'type_key' => 'premier', 'guests' => 2, 'price' => 159, 'image' => 'images/room/3.webp'],
        ['id' => 4, 'type' => 'Family Suite', 'type_key' => 'family', 'guests' => 4, 'price' => 179, 'image' => 'images/room/4.webp'],
        ['id' => 5, 'type' => 'Luxury Suite', 'type_key' => 'luxury', 'guests' => 4, 'price' => 199, 'image' => 'images/room/5.webp'],
        ['id' => 6, 'type' => 'Presidential Suite', 'type_key' => 'presidential', 'guests' => 4, 'price' => 249, 'image' => 'images/room/6.webp'],
    ];
}

$selectedRoomId = $reservationRooms[0]['id'] ?? 0;
if ($selectedTypeKey !== '') {
    foreach ($reservationRooms as $room) {
        if ($room['type_key'] === $selectedTypeKey) {
            $selectedRoomId = $room['id'];
            break;
        }
    }
}

$reservationServices = [];
$fallbackServiceImages = [
    'images/facilities/1.webp',
    'images/facilities/2.webp',
    'images/facilities/3.webp',
    'images/facilities/4.webp',
    'images/facilities/5.webp',
    'images/facilities/6.webp',
];
$serviceSql = "SELECT id, name, description, image_url, is_active
               FROM facilities
               ORDER BY is_active DESC, id ASC";
$serviceResult = $conn->query($serviceSql);
if ($serviceResult instanceof mysqli_result) {
    $idx = 0;
    while ($row = $serviceResult->fetch_assoc()) {
        $image = str_replace('\\', '/', trim((string)($row['image_url'] ?? '')));
        if ($image === '' || preg_match('/\.svg$/i', $image)) {
            $image = $fallbackServiceImages[$idx % count($fallbackServiceImages)];
        }

        $name = trim((string)($row['name'] ?? 'Hotel Service'));
        $nameKey = strtolower($name);
        $servicePrice = 39.00;
        if (strpos($nameKey, 'restaurant') !== false || strpos($nameKey, 'dining') !== false) {
            $servicePrice = 49.00;
        } elseif (strpos($nameKey, 'pool') !== false) {
            $servicePrice = 29.00;
        } elseif (strpos($nameKey, 'spa') !== false || strpos($nameKey, 'massage') !== false) {
            $servicePrice = 79.00;
        } elseif (strpos($nameKey, 'fitness') !== false || strpos($nameKey, 'gym') !== false) {
            $servicePrice = 19.00;
        } elseif (strpos($nameKey, 'meeting') !== false) {
            $servicePrice = 99.00;
        } elseif (strpos($nameKey, 'laundry') !== false) {
            $servicePrice = 15.00;
        }

        $isActive = (int)($row['is_active'] ?? 0) === 1;
        $reservationServices[] = [
            'id' => (int)($row['id'] ?? 0),
            'name' => $name,
            'description' => trim((string)($row['description'] ?? 'Premium guest service')),
            'image' => $image,
            'price' => $servicePrice,
            'is_active' => $isActive,
            'status_label' => $isActive ? 'Available' : 'Unavailable',
        ];
        $idx++;
    }
    $serviceResult->free();
}

if (empty($reservationServices)) {
    $reservationServices = [
        ['id' => 1, 'name' => 'Restaurant', 'description' => 'Reserve dining with curated menus and premium service.', 'image' => 'images/facilities/1.webp', 'price' => 49.00, 'is_active' => true, 'status_label' => 'Available'],
        ['id' => 2, 'name' => 'Swimming Pool', 'description' => 'Book pool access and lounge support for your stay.', 'image' => 'images/facilities/2.webp', 'price' => 29.00, 'is_active' => true, 'status_label' => 'Available'],
        ['id' => 3, 'name' => 'Spa & Massage', 'description' => 'Relax with wellness treatments and massage sessions.', 'image' => 'images/facilities/5.webp', 'price' => 79.00, 'is_active' => true, 'status_label' => 'Available'],
    ];
}

$firstActiveServiceId = 0;
foreach ($reservationServices as $serviceItem) {
    if (!empty($serviceItem['is_active'])) {
        $firstActiveServiceId = (int)$serviceItem['id'];
        break;
    }
}
if ($firstActiveServiceId <= 0) {
    $firstActiveServiceId = (int)($reservationServices[0]['id'] ?? 0);
}

$selectedFacilityId = (int)($_GET['facility_id'] ?? $firstActiveServiceId);
$selectedService = null;
foreach ($reservationServices as $serviceItem) {
    if ((int)$serviceItem['id'] === $selectedFacilityId) {
        $selectedService = $serviceItem;
        break;
    }
}
if (!$selectedService && !empty($reservationServices)) {
    $selectedService = $reservationServices[0];
    $selectedFacilityId = (int)$selectedService['id'];
}
?>
<!DOCTYPE html>
<html lang="zxx">

<head>
    <title>zemaraim — Hotel Website Template</title>
    <link rel="icon" href="images/icon.webp" type="image/gif" sizes="16x16">
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
    <meta content="width=device-width, initial-scale=1.0" name="viewport" >
    <meta content="zemaraim — Hotel Website Template" name="description" >
    <meta content="" name="keywords" >
    <meta content="" name="author" >
    <!-- CSS Files
    ================================================== -->
    <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" id="bootstrap">
    <link href="css/plugins.css" rel="stylesheet" type="text/css" >
    <link href="css/swiper.css" rel="stylesheet" type="text/css" >
    <link href="css/style.css" rel="stylesheet" type="text/css" >
    <link href="css/coloring.css" rel="stylesheet" type="text/css" >
    <!-- color scheme -->
    <link id="colors" href="css/colors/scheme-01.css" rel="stylesheet" type="text/css" >
    <style>
        .reservation-booking-row {
            display: grid;
            grid-template-columns: repeat(4, minmax(0, 1fr));
            gap: 14px;
        }

        .reservation-booking-card .booking-form-group {
            margin: 0;
        }

        .reservation-booking-card .booking-form-group.room-select-group {
            grid-column: span 4;
        }

        .reservation-room-select-single {
            height: 48px;
            border: 1px solid #d9e2ed;
            border-radius: 10px;
            padding: 0 12px;
            width: 100%;
            background: #fff;
        }

        .reservation-room-preview {
            margin-top: 10px;
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 8px;
            border: 1px solid #e5ecf3;
            border-radius: 10px;
            background: #f9fbfd;
        }

        .reservation-room-preview img {
            width: 62px;
            height: 46px;
            object-fit: cover;
            border-radius: 8px;
            border: 1px solid #d9e2ed;
            flex: 0 0 auto;
        }

        .reservation-room-preview span {
            font-size: 13px;
            color: #22384f;
            line-height: 1.3;
        }

        .reservation-type-group {
            grid-column: span 4;
        }

        .reservation-type-switch {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .reservation-type-option {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            border: 1px solid #d8e2ee;
            border-radius: 10px;
            padding: 10px 14px;
            font-size: 14px;
            color: #20374f;
            background: #fff;
            cursor: pointer;
        }

        .reservation-selection-panel.is-hidden {
            display: none;
        }

        .reservation-confirmation-box {
            margin-top: 14px;
            border: 1px solid #dbe5ef;
            border-radius: 12px;
            background: #ffffff;
            padding: 16px;
            text-align: left;
        }

        .reservation-confirmation-grid {
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr));
            gap: 10px 14px;
        }

        .reservation-confirmation-item {
            border: 1px solid #e6edf5;
            border-radius: 10px;
            background: #f9fbfd;
            padding: 10px 12px;
        }

        .reservation-confirmation-item span {
            display: block;
            font-size: 12px;
            color: #607286;
            margin-bottom: 2px;
        }

        .reservation-confirmation-item strong {
            display: block;
            color: #152f4b;
            font-size: 14px;
            line-height: 1.4;
            word-break: break-word;
        }

        @media (max-width: 1199px) {
            .reservation-booking-row {
                grid-template-columns: repeat(2, minmax(0, 1fr));
            }

            .reservation-booking-card .booking-form-group.room-select-group {
                grid-column: span 2;
            }

            .reservation-type-group {
                grid-column: span 2;
            }
        }

        @media (max-width: 575px) {
            .reservation-booking-row {
                grid-template-columns: 1fr;
            }

            .reservation-booking-card .booking-form-group.room-select-group {
                grid-column: span 1;
            }

            .reservation-type-group {
                grid-column: span 1;
            }

            .reservation-confirmation-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>

</head>

<body>
    <div id="wrapper">
        <a href="#" id="back-to-top"></a>
        
        <!-- page preloader begin -->
        <div id="de-loader"></div>
        <!-- page preloader close -->

        <!-- header begin -->
        <?php include 'header.php'; ?>
        <!-- header close -->
        <!-- content begin -->
        <div class="no-bottom no-top" id="content">

            <div id="top"></div>

            <section class="page-breadcrumb-hero" style="--page-hero-bg: url('images/background/3.webp');">
                <div class="container">
                    <div class="page-breadcrumb-content text-center">
                        <span class="page-breadcrumb-kicker">Secure Booking</span>
                        <h1>Reservation</h1>
                        <p>Book your room or service in minutes with instant confirmation and trusted hotel support.</p>
                        <ul class="page-breadcrumb-list">
                            <li><a href="index.php">Home</a></li>
                            <li class="active">Reservation</li>
                        </ul>
                    </div>
                </div>
            </section>

            <!-- reservation section -->
            <section id="section_form" class="reservation-modern-section">
                <div class="container">
                    <div class="reservation-modern-wrap">
                        <div class="row g-4 g-lg-5">
                            <div class="col-lg-7">
                                <div id="booking_form_wrap" class="reservation-form-panel">
                                        <div class="reservation-head">
                                            <span class="reservation-kicker">Secure Booking</span>
                                            <h2>Reserve your stay in minutes.</h2>
                                            <p>Fill in your dates and details below to get instant reservation confirmation.</p>
                                        </div>

                                    <form name="contactForm" id="booking_form" class="form-border reservation-modern-form" method="post" action="booking.php">
                                        <div class="reservation-block reservation-booking-card">
                                            <h4>Choose Date and Room</h4>
                                            <div class="booking-form-row booking-form-row-compact reservation-booking-row">
                                                <div class="booking-form-group reservation-type-group">
                                                    <label>Reservation For</label>
                                                    <div class="reservation-type-switch">
                                                        <label class="reservation-type-option">
                                                            <input type="radio" name="reservation_type" value="room" <?php echo $selectedReservationType === 'room' ? 'checked' : ''; ?>>
                                                            <span>Room Stay</span>
                                                        </label>
                                                        <label class="reservation-type-option">
                                                            <input type="radio" name="reservation_type" value="service" <?php echo $selectedReservationType === 'service' ? 'checked' : ''; ?>>
                                                            <span>Hotel Service</span>
                                                        </label>
                                                    </div>
                                                </div>
                                                <div class="booking-form-group">
                                                    <label>Check in</label>
                                                    <input type="date" id="check-in" name="check_in" class="booking-input" value="<?php echo htmlspecialchars($selectedCheckIn, ENT_QUOTES, 'UTF-8'); ?>" required>
                                                </div>
                                                <div class="booking-form-group">
                                                    <label>Check out</label>
                                                    <input type="date" id="check-out" name="check_out" class="booking-input" value="<?php echo htmlspecialchars($selectedCheckOut, ENT_QUOTES, 'UTF-8'); ?>" required>
                                                </div>
                                                <div class="booking-form-group">
                                                    <label>Person</label>
                                                    <div class="booking-stepper">
                                                        <button type="button" class="stepper-btn" data-step="down">-</button>
                                                        <input type="number" id="adults" name="adult" value="<?php echo (int)$selectedAdults; ?>" min="1" readonly>
                                                        <button type="button" class="stepper-btn" data-step="up">+</button>
                                                    </div>
                                                </div>
                                                <div class="booking-form-group room-select-group reservation-selection-panel <?php echo $selectedReservationType === 'service' ? 'is-hidden' : ''; ?>" id="room-selection-group">
                                                    <label>Room select</label>
                                                    <select id="room-type" class="reservation-room-select-single" name="room_type">
                                                        <?php foreach ($reservationRooms as $room): ?>
                                                            <option
                                                                value="<?php echo htmlspecialchars($room['type'], ENT_QUOTES, 'UTF-8'); ?>"
                                                                data-room-id="<?php echo (int)$room['id']; ?>"
                                                                data-src="<?php echo htmlspecialchars($room['image'], ENT_QUOTES, 'UTF-8'); ?>"
                                                                data-capacity="<?php echo (int)$room['guests']; ?>"
                                                                <?php echo ((int)$room['id'] === (int)$selectedRoomId) ? 'selected' : ''; ?>>
                                                                <?php echo htmlspecialchars($room['type'], ENT_QUOTES, 'UTF-8'); ?> | $<?php echo (int)round((float)$room['price']); ?>/night | <?php echo (int)$room['guests']; ?> Guests
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                    <div class="reservation-room-preview" id="reservation-room-preview">
                                                        <img id="reservation-room-preview-image" src="<?php echo htmlspecialchars($reservationRooms[0]['image'] ?? 'images/room/1.webp', ENT_QUOTES, 'UTF-8'); ?>" alt="Selected room">
                                                        <span id="reservation-room-preview-text">Selected room preview</span>
                                                    </div>
                                                    <input type="hidden" id="room-id" name="room_id" value="<?php echo (int)$selectedRoomId; ?>">
                                                </div>

                                                <div class="booking-form-group room-select-group reservation-selection-panel <?php echo $selectedReservationType === 'room' ? 'is-hidden' : ''; ?>" id="service-selection-group">
                                                    <label>Service select</label>
                                                    <select id="service-id" class="reservation-room-select-single" name="facility_id">
                                                        <?php $hasActiveService = false; ?>
                                                        <?php foreach ($reservationServices as $service): ?>
                                                            <?php if (!empty($service['is_active'])) { $hasActiveService = true; } ?>
                                                            <option
                                                                value="<?php echo (int)$service['id']; ?>"
                                                                data-src="<?php echo htmlspecialchars($service['image'], ENT_QUOTES, 'UTF-8'); ?>"
                                                                data-price="<?php echo htmlspecialchars(number_format((float)$service['price'], 2, '.', ''), ENT_QUOTES, 'UTF-8'); ?>"
                                                                data-status="<?php echo htmlspecialchars((string)$service['status_label'], ENT_QUOTES, 'UTF-8'); ?>"
                                                                <?php echo empty($service['is_active']) ? 'disabled' : ''; ?>
                                                                <?php echo ((int)$service['id'] === (int)$selectedFacilityId) ? 'selected' : ''; ?>>
                                                                <?php echo htmlspecialchars($service['name'], ENT_QUOTES, 'UTF-8'); ?> | $<?php echo htmlspecialchars(number_format((float)$service['price'], 2), ENT_QUOTES, 'UTF-8'); ?> | <?php echo htmlspecialchars((string)$service['status_label'], ENT_QUOTES, 'UTF-8'); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                        <?php if (!$hasActiveService): ?>
                                                            <option value="" selected disabled>No available services right now</option>
                                                        <?php endif; ?>
                                                    </select>
                                                    <div class="reservation-room-preview" id="reservation-service-preview">
                                                        <img id="reservation-service-preview-image" src="<?php echo htmlspecialchars((string)($selectedService['image'] ?? 'images/facilities/1.webp'), ENT_QUOTES, 'UTF-8'); ?>" alt="Selected service">
                                                        <span id="reservation-service-preview-text"><?php echo htmlspecialchars((string)($selectedService['name'] ?? 'Selected service') . ' | $' . number_format((float)($selectedService['price'] ?? 0), 2) . ' | ' . (string)($selectedService['status_label'] ?? 'Unavailable'), ENT_QUOTES, 'UTF-8'); ?></span>
                                                    </div>
                                                </div>
                                            </div>
                                            <input type="hidden" name="children" value="0">
                                            <input type="hidden" id="room-count" name="room_count" value="1">
                                        </div>

                                        <div class="reservation-block">
                                            <h4>Your Details</h4>
                                            <div id="step-2" class="row g-3">
                                                <div class="col-md-6">
                                                    <div id="name_error" class="error">Please enter your name.</div>
                                                    <input type="text" name="name" id="name" class="form-control" placeholder="Your Name" value="<?php echo htmlspecialchars($loggedInName, ENT_QUOTES, 'UTF-8'); ?>" required>
                                                </div>
                                                <div class="col-md-6">
                                                    <div id="email_error" class="error">Please enter your valid E-mail ID.</div>
                                                    <input type="email" name="email" id="email" class="form-control" placeholder="Your Email" value="<?php echo htmlspecialchars($loggedInEmail, ENT_QUOTES, 'UTF-8'); ?>" required>
                                                </div>
                                                <div class="col-md-6">
                                                    <div id="phone_error" class="error">Please enter your phone number.</div>
                                                    <input type="text" name="phone" id="phone" class="form-control" placeholder="Your Phone" value="<?php echo htmlspecialchars($loggedInPhone, ENT_QUOTES, 'UTF-8'); ?>" required>
                                                </div>
                                                <div class="col-md-6">
                                                    <textarea name="message" id="message" class="form-control" placeholder="Special requests (optional)"></textarea>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="reservation-submit-wrap">
                                            <p id="submit">
                                                <input type="submit" id="send_message" value="Confirm Reservation" class="btn-main">
                                            </p>
                                        </div>
                                    </form>

                                    <div id="error_message" class="error">Sorry, error occured this time sending your message.</div>
                                </div>

                                <div id="success_message" class="reservation-success-panel text-center">
                                    <h2 id="reservation-success-title">Your reservation has been confirmed.</h2>
                                    <p id="reservation-success-text">We will contact you shortly. Refresh this page if you want to make another reservation.</p>
                                    <div class="reservation-confirmation-box">
                                        <div class="reservation-confirmation-grid">
                                            <div class="reservation-confirmation-item">
                                                <span>Booking ID</span>
                                                <strong id="confirm-booking-id">-</strong>
                                            </div>
                                            <div class="reservation-confirmation-item">
                                                <span>Reservation Type</span>
                                                <strong id="confirm-type">-</strong>
                                            </div>
                                            <div class="reservation-confirmation-item">
                                                <span>Check In</span>
                                                <strong id="confirm-checkin">-</strong>
                                            </div>
                                            <div class="reservation-confirmation-item">
                                                <span>Check Out</span>
                                                <strong id="confirm-checkout">-</strong>
                                            </div>
                                            <div class="reservation-confirmation-item">
                                                <span>Guests</span>
                                                <strong id="confirm-guests">-</strong>
                                            </div>
                                            <div class="reservation-confirmation-item">
                                                <span>Selected Option</span>
                                                <strong id="confirm-selected">-</strong>
                                            </div>
                                            <div class="reservation-confirmation-item">
                                                <span>Total Price</span>
                                                <strong id="confirm-total">-</strong>
                                            </div>
                                            <div class="reservation-confirmation-item">
                                                <span>Booking Status</span>
                                                <strong id="confirm-status">Pending Confirmation</strong>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-lg-5">
                                <aside class="reservation-side-card">
                                    <h3>Why Book Direct?</h3>
                                    <ul class="reservation-benefits">
                                        <li><i class="icofont-check-circled"></i> Instant booking confirmation</li>
                                        <li><i class="icofont-check-circled"></i> Best available direct rate</li>
                                        <li><i class="icofont-check-circled"></i> Flexible check-in and cancellation support</li>
                                        <li><i class="icofont-check-circled"></i> Priority room preference</li>
                                    </ul>

                                    <div class="reservation-side-meta">
                                        <div>
                                            <span>Support</span>
                                            <strong>24/7 Guest Assistance</strong>
                                        </div>
                                        <div>
                                            <span>Contact</span>
                                            <strong>+929 333 9296</strong>
                                        </div>
                                        <div>
                                            <span>Email</span>
                                            <strong>contact@zemaraim.com</strong>
                                        </div>
                                    </div>

                                    <a href="rooms.php" class="btn-main btn-line reservation-side-btn">Browse Rooms</a>
                                </aside>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </div>
        <!-- content close -->
        
        <!-- footer begin -->
        <?php include 'footer.php'; ?>
        <!-- footer close -->
    </div>

    <!-- Javascript Files
    ================================================== -->
    <script src="js/plugins.js"></script>
    <script src="js/designesia.js"></script>
    <script src="js/validation-booking.js"></script>
    <script>
    document.addEventListener("DOMContentLoaded", function () {
      const stepperBtns = document.querySelectorAll(".stepper-btn");
      const adultsInput = document.getElementById("adults");
      const roomTypeSelect = document.getElementById("room-type");
      const serviceSelect = document.getElementById("service-id");
      const roomIdInput = document.getElementById("room-id");
      const roomSelectionGroup = document.getElementById("room-selection-group");
      const serviceSelectionGroup = document.getElementById("service-selection-group");
      const reservationTypeInputs = document.querySelectorAll('input[name="reservation_type"]');
      const roomPreviewImage = document.getElementById("reservation-room-preview-image");
      const roomPreviewText = document.getElementById("reservation-room-preview-text");
      const servicePreviewImage = document.getElementById("reservation-service-preview-image");
      const servicePreviewText = document.getElementById("reservation-service-preview-text");
      const roomOptionsCache = roomTypeSelect ? Array.from(roomTypeSelect.options).map((opt) => ({
        value: opt.value,
        text: opt.text,
        roomId: opt.dataset.roomId || "",
        src: opt.dataset.src || "",
        capacity: parseInt(opt.dataset.capacity || "0", 10)
      })) : [];

      const getReservationType = () => {
        const selected = Array.from(reservationTypeInputs).find((input) => input.checked);
        return selected ? selected.value : "room";
      };

      const updateTypePanels = () => {
        const type = getReservationType();
        const isRoom = type === "room";
        if (roomSelectionGroup) {
          roomSelectionGroup.classList.toggle("is-hidden", !isRoom);
        }
        if (serviceSelectionGroup) {
          serviceSelectionGroup.classList.toggle("is-hidden", isRoom);
        }
      };

      const updateRoomPreview = (selectedOption) => {
        if (!roomPreviewImage || !roomPreviewText) return;
        if (!selectedOption) {
          roomPreviewText.textContent = "No room selected";
          roomPreviewImage.src = "images/room/1.webp";
          return;
        }
        const src = selectedOption.dataset.src || "images/room/1.webp";
        roomPreviewImage.src = src;
        roomPreviewText.textContent = selectedOption.text || "Selected room";
      };

      const updateServicePreview = (selectedOption) => {
        if (!servicePreviewImage || !servicePreviewText) return;
        if (!selectedOption) {
          servicePreviewText.textContent = "No service selected";
          servicePreviewImage.src = "images/facilities/1.webp";
          return;
        }
        const src = selectedOption.dataset.src || "images/facilities/1.webp";
        const price = selectedOption.dataset.price ? `$${selectedOption.dataset.price}` : "$0.00";
        const status = selectedOption.dataset.status || "Unavailable";
        servicePreviewImage.src = src;
        servicePreviewText.textContent = `${selectedOption.text.split('|')[0].trim()} | ${price} | ${status}`;
      };

      const syncRoomSelection = () => {
        if (!roomTypeSelect || !adultsInput) return;
        const adults = parseInt(adultsInput.value || "1", 10);
        const previousRoomId = roomIdInput ? roomIdInput.value : "";

        // Rebuild options so only exact guest-match rooms are shown in real time.
        roomTypeSelect.innerHTML = "";
        const matching = roomOptionsCache.filter((opt) => opt.capacity === adults);

        if (!matching.length) {
          const noOption = document.createElement("option");
          noOption.value = "";
          noOption.text = `No rooms available for ${adults} guest(s)`;
          noOption.disabled = true;
          noOption.selected = true;
          roomTypeSelect.appendChild(noOption);
          if (roomIdInput) {
            roomIdInput.value = "";
          }
          updateRoomPreview(null);
          return;
        }

        matching.forEach((opt) => {
          const optionEl = document.createElement("option");
          optionEl.value = opt.value;
          optionEl.text = opt.text;
          optionEl.dataset.roomId = opt.roomId;
          optionEl.dataset.src = opt.src;
          optionEl.dataset.capacity = String(opt.capacity);
          roomTypeSelect.appendChild(optionEl);
        });

        let selected = Array.from(roomTypeSelect.options).find((opt) => (opt.dataset.roomId || "") === previousRoomId);
        if (!selected) {
          selected = roomTypeSelect.options[0] || null;
          if (selected) {
            roomTypeSelect.value = selected.value;
          }
        }

        if (roomIdInput && selected) {
          roomIdInput.value = selected.dataset.roomId || "";
        }
        updateRoomPreview(selected);
      };

      stepperBtns.forEach(function (btn) {
        btn.addEventListener("click", function () {
          const input = this.parentElement.querySelector("input");
          if (!input) return;
          const min = parseInt(input.getAttribute("min") || "1", 10);
          const currentValue = parseInt(input.value || min, 10);
          if (this.dataset.step === "up") {
            input.value = currentValue + 1;
          } else if (this.dataset.step === "down" && currentValue > min) {
            input.value = currentValue - 1;
          }
          syncRoomSelection();
        });
      });

      if (roomTypeSelect) {
        roomTypeSelect.addEventListener("change", function () {
          const selected = this.selectedOptions[0];
          if (roomIdInput && selected) {
            roomIdInput.value = selected.dataset.roomId || "";
          }
          updateRoomPreview(selected);
        });
      }

      if (serviceSelect) {
        serviceSelect.addEventListener("change", function () {
          const selected = this.selectedOptions[0] || null;
          updateServicePreview(selected);
        });
      }

      reservationTypeInputs.forEach((input) => {
        input.addEventListener("change", updateTypePanels);
      });

      window.getReservationConfirmationData = function () {
        const selectedType = getReservationType();
        const selectedOption = selectedType === "room"
          ? (roomTypeSelect ? roomTypeSelect.selectedOptions[0] : null)
          : (serviceSelect ? serviceSelect.selectedOptions[0] : null);
        return {
          reservationType: selectedType,
          selectedLabel: selectedOption ? selectedOption.text.split("|")[0].trim() : "-",
          checkIn: checkInInput ? checkInInput.value : "-",
          checkOut: checkOutInput ? checkOutInput.value : "-",
          guests: adultsInput ? adultsInput.value : "-",
        };
      };

      const checkInInput = document.getElementById("check-in");
      const checkOutInput = document.getElementById("check-out");
      if (checkInInput && checkOutInput) {
        const today = new Date().toISOString().split("T")[0];
        checkInInput.setAttribute("min", today);
        checkOutInput.setAttribute("min", today);

        checkInInput.addEventListener("change", function () {
          if (!this.value) return;
          const checkInDate = new Date(this.value);
          checkInDate.setDate(checkInDate.getDate() + 1);
          const minDate = checkInDate.toISOString().split("T")[0];
          checkOutInput.setAttribute("min", minDate);
          if (checkOutInput.value && checkOutInput.value <= this.value) {
            checkOutInput.value = minDate;
          }
        });
      }

      syncRoomSelection();
      if (serviceSelect) {
        updateServicePreview(serviceSelect.selectedOptions[0] || null);
      }
      updateTypePanels();
    });
    </script>

</body>

</html>
