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

function roomTypeKey(string $type): string
{
    $normalized = strtolower(trim($type));
    $normalized = str_replace([' suite', ' room'], '', $normalized);
    $normalized = preg_replace('/[^a-z0-9]+/', '-', $normalized);
    return trim((string)$normalized, '-');
}
?>
<!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" >

</head>

<body>
    <?php
    $checkIn = isset($_GET['checkIn']) ? trim((string)$_GET['checkIn']) : '';
    $checkOut = isset($_GET['checkOut']) ? trim((string)$_GET['checkOut']) : '';
    $adults = isset($_GET['adults']) ? (int)$_GET['adults'] : 0;
    $roomType = isset($_GET['roomType']) ? strtolower(trim((string)$_GET['roomType'])) : 'all';

    if ($adults < 0) {
        $adults = 0;
    }

    $rooms = [];
    $roomTypeOptions = ['all' => 'All Rooms'];

    $roomSql = "SELECT id, room_type, description, max_guests, price_per_night, size_sqft, 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 = roomTypeKey($typeLabel);
            if ($typeKey === '') {
                $typeKey = 'room';
            }

            $image = trim((string)($row['image_url'] ?? ''));
            if ($image === '') {
                $image = 'images/room/1.webp';
            }

            $roomTypeOptions[$typeKey] = $typeLabel;
            $rooms[] = [
                'id' => (int)($row['id'] ?? 0),
                'name' => $typeLabel,
                'type' => $typeKey,
                'image' => str_replace('\\', '/', $image),
                'price' => (float)($row['price_per_night'] ?? 0),
                'description' => trim((string)($row['description'] ?? 'Comfortable stay with premium amenities.')),
                'capacity' => (int)($row['max_guests'] ?? 1),
                'size' => (int)($row['size_sqft'] ?? 0),
            ];
        }
        $roomResult->free();
    }

    if (empty($rooms)) {
        $rooms = [
            ['id' => 1, 'name' => 'Standard Room', 'type' => 'standard', 'image' => 'images/room/1.webp', 'price' => 129, 'description' => 'Comfortable essentials with modern styling for business and leisure guests.', 'capacity' => 2, 'size' => 30],
            ['id' => 2, 'name' => 'Deluxe Room', 'type' => 'deluxe', 'image' => 'images/room/2.webp', 'price' => 149, 'description' => 'Extra space, premium bedding, and refined details for a restful stay.', 'capacity' => 2, 'size' => 35],
            ['id' => 3, 'name' => 'Premier Room', 'type' => 'premier', 'image' => 'images/room/3.webp', 'price' => 159, 'description' => 'Stylish interiors with upgraded amenities and an elevated stay experience.', 'capacity' => 2, 'size' => 35],
            ['id' => 4, 'name' => 'Family Suite', 'type' => 'family', 'image' => 'images/room/4.webp', 'price' => 179, 'description' => 'Perfect for group stays with generous room layout and flexible comfort.', 'capacity' => 4, 'size' => 60],
            ['id' => 5, 'name' => 'Luxury Suite', 'type' => 'luxury', 'image' => 'images/room/5.webp', 'price' => 199, 'description' => 'Premium comfort and curated design for guests seeking extra indulgence.', 'capacity' => 4, 'size' => 70],
            ['id' => 6, 'name' => 'Presidential Suite', 'type' => 'presidential', 'image' => 'images/room/6.webp', 'price' => 249, 'description' => 'Top-tier luxury with spacious living, privacy, and signature service.', 'capacity' => 2, 'size' => 90],
        ];
        $roomTypeOptions = [
            'all' => 'All Rooms',
            'standard' => 'Standard Room',
            'deluxe' => 'Deluxe Room',
            'premier' => 'Premier Room',
            'family' => 'Family Suite',
            'luxury' => 'Luxury Suite',
            'presidential' => 'Presidential Suite',
        ];
    }

    if (!array_key_exists($roomType, $roomTypeOptions)) {
        $roomType = 'all';
    }

    // Render all rooms and let JS handle live filtering without page reload.
    $filteredRooms = $rooms;
    ?>
    <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/1.webp');">
                <div class="container">
                    <div class="page-breadcrumb-content text-center">
                        <span class="page-breadcrumb-kicker">Room Collection</span>
                        <h1>Our Rooms</h1>
                        <p>Browse room types crafted for comfort, style, and easy online booking across all guest needs.</p>
                        <ul class="page-breadcrumb-list">
                            <li><a href="index.php">Home</a></li>
                            <li class="active">Our Rooms</li>
                        </ul>
                    </div>
                </div>
            </section>

            <!-- rooms section -->
            <section id="section-rooms" class="rooms-modern-section">
                <div class="container">
                    <div class="rooms-modern-head text-center wow fadeInUp">
                        <span class="rooms-kicker">Stay Your Way</span>
                        <h2 class="rooms-title">Choose the perfect room for your next trip.</h2>
                        <p class="rooms-subtitle">From cozy stays to premium suites, each room is crafted for comfort and easy online booking.</p>
                    </div>

                    <div class="room-filter-wrap wow fadeInUp" data-wow-delay="0s">
                        <style>
                            .room-filter-wrap {
                                margin: 20px 0 30px;
                                padding: 18px;
                                border-radius: 14px;
                                background: #ffffff;
                                border: 1px solid #e7edf3;
                                box-shadow: 0 12px 30px rgba(15, 33, 53, 0.08);
                            }

                            .room-filter-form .filter-grid {
                                display: grid;
                                gap: 12px;
                                grid-template-columns: repeat(5, minmax(0, 1fr));
                                align-items: end;
                            }

                            .room-filter-form label {
                                display: block;
                                font-size: 12px;
                                font-weight: 700;
                                color: #42556f;
                                text-transform: uppercase;
                                margin-bottom: 6px;
                            }

                            .room-filter-form input,
                            .room-filter-form select {
                                width: 100%;
                                height: 46px;
                                padding: 0 12px;
                                border: 1px solid #d9e2ed;
                                border-radius: 10px;
                                background: #fff;
                            }

                            .room-filter-form .filter-stepper {
                                height: 46px;
                                display: grid;
                                grid-template-columns: 40px 1fr 40px;
                                border: 1px solid #d9e2ed;
                                border-radius: 10px;
                                overflow: hidden;
                                background: #fff;
                            }

                            .room-filter-form .filter-stepper-btn {
                                border: 0;
                                background: #f3f7fb;
                                font-size: 18px;
                                font-weight: 700;
                                color: #1f3148;
                            }

                            .room-filter-form .filter-stepper input {
                                border: 0;
                                text-align: center;
                                font-weight: 700;
                                padding: 0;
                            }

                            .room-filter-form .btn-main {
                                width: 100%;
                                height: 46px;
                                border-radius: 10px;
                            }

                            .room-filter-form .filter-grid > div:last-child {
                                min-width: 150px;
                            }

                            .room-filter-summary {
                                margin-top: 12px;
                                font-size: 14px;
                                color: #4e6176;
                            }

                            .room-filter-empty {
                                margin-top: 16px;
                                padding: 16px;
                                border-radius: 12px;
                                background: #f8fbff;
                                border: 1px solid #dce8f5;
                                color: #2f465f;
                                text-align: center;
                            }

                            @media (max-width: 1199px) {
                                .room-filter-form .filter-grid {
                                    grid-template-columns: repeat(3, minmax(0, 1fr));
                                }
                            }

                            @media (max-width: 991px) {
                                .room-filter-form .filter-grid {
                                    grid-template-columns: repeat(2, minmax(0, 1fr));
                                }
                            }

                            @media (max-width: 575px) {
                                .room-filter-form .filter-grid {
                                    grid-template-columns: 1fr;
                                }

                                .room-filter-wrap {
                                    padding: 14px;
                                }
                            }
                        </style>

                        <form class="room-filter-form" method="get" action="rooms.php" id="room-filter-form">
                            <div class="filter-grid">
                                <div>
                                    <label for="room-check-in">Check in</label>
                                    <input type="date" id="room-check-in" name="checkIn" value="<?php echo htmlspecialchars($checkIn, ENT_QUOTES, 'UTF-8'); ?>">
                                </div>
                                <div>
                                    <label for="room-check-out">Check out</label>
                                    <input type="date" id="room-check-out" name="checkOut" value="<?php echo htmlspecialchars($checkOut, ENT_QUOTES, 'UTF-8'); ?>">
                                </div>
                                <div>
                                    <label for="room-adults">Adults</label>
                                    <div class="filter-stepper">
                                        <button type="button" class="filter-stepper-btn" data-step="down">-</button>
                                        <input type="number" id="room-adults" name="adults" value="<?php echo (int)$adults; ?>" min="0" readonly>
                                        <button type="button" class="filter-stepper-btn" data-step="up">+</button>
                                    </div>
                                </div>
                                <div>
                                    <label for="room-type">Room type</label>
                                    <select id="room-type" name="roomType">
                                        <?php foreach ($roomTypeOptions as $typeKey => $typeLabel): ?>
                                            <option value="<?php echo htmlspecialchars($typeKey, ENT_QUOTES, 'UTF-8'); ?>" <?php echo $roomType === $typeKey ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($typeLabel, ENT_QUOTES, 'UTF-8'); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div>
                                    <label>&nbsp;</label>
                                    <button type="submit" class="btn-main">Search Rooms</button>
                                </div>
                            </div>
                        </form>

                        <div class="room-filter-summary" id="room-filter-summary">
                            Showing <?php echo count($rooms); ?> room(s)
                            <?php if ($adults > 0): ?>
                                for <?php echo (int)$adults; ?> guest(s)
                            <?php endif; ?>
                            <?php if ($roomType !== 'all'): ?>
                                | Type: <?php echo htmlspecialchars(ucfirst($roomType), ENT_QUOTES, 'UTF-8'); ?>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="row g-3 g-md-4" id="rooms-grid">
                        <?php foreach ($filteredRooms as $index => $room): ?>
                            <?php $delay = number_format(($index % 10) * 0.15, 2); ?>
                            <div class="col-lg-4 col-md-6 wow fadeInUp room-filter-item"
                                 data-wow-delay="<?php echo htmlspecialchars($delay . 's', ENT_QUOTES, 'UTF-8'); ?>"
                                 data-capacity="<?php echo (int)$room['capacity']; ?>"
                                 data-type="<?php echo htmlspecialchars($room['type'], ENT_QUOTES, 'UTF-8'); ?>">
                                <article class="room-modern-card h-100">
                                    <a href="room-details.php" class="room-modern-image-wrap">
                                        <img src="<?php echo htmlspecialchars($room['image'], ENT_QUOTES, 'UTF-8'); ?>" class="room-modern-image" alt="<?php echo htmlspecialchars($room['name'], ENT_QUOTES, 'UTF-8'); ?>">
                                        <span class="room-modern-price">From $<?php echo (int)round((float)$room['price']); ?></span>
                                    </a>
                                    <div class="room-modern-body">
                                        <h3><?php echo htmlspecialchars($room['name'], ENT_QUOTES, 'UTF-8'); ?></h3>
                                        <p><?php echo htmlspecialchars($room['description'], ENT_QUOTES, 'UTF-8'); ?></p>
                                        <div class="room-modern-meta">
                                            <span><?php echo (int)$room['capacity']; ?> Guests</span>
                                            <span><?php echo (int)$room['size']; ?> ft</span>
                                        </div>
                                        <div class="room-modern-actions">
                                            <a href="room-details.php" class="btn-line room-modern-btn">View Details</a>
                                            <a href="reservation.php?checkIn=<?php echo urlencode($checkIn); ?>&checkOut=<?php echo urlencode($checkOut); ?>&adults=<?php echo (int)$adults; ?>&roomType=<?php echo urlencode($room['type']); ?>" class="btn-main room-modern-btn">Book Now</a>
                                        </div>
                                    </div>
                                </article>
                            </div>
                        <?php endforeach; ?>
                    </div>

                    <div class="room-filter-empty wow fadeInUp" id="room-filter-empty" data-wow-delay="0.1s" style="display:none;">
                        No rooms match your filters. Try reducing guests or choosing "All Rooms".
                    </div>

                    <div class="rooms-modern-cta wow fadeInUp" data-wow-delay="0.9s">
                        <div class="rooms-cta-copy">
                            <h3>Need help choosing a room?</h3>
                            <p>Compare room options and reserve in just a few clicks with instant confirmation.</p>
                        </div>
                        <div class="rooms-cta-actions">
                            <a href="room-details.php" class="btn-main">View Room Details</a>
                            <a href="reservation.php" class="btn-main btn-line">Book Direct</a>
                        </div>
                    </div>
                </div>
            </section>
        </div>
        <!-- content close -->
        
        <!-- footer begin -->
        <?php include 'footer.php'; ?>
         <!-- footer close -->
        <!-- footer close -->
    </div>

    <!-- Javascript Files
    ================================================== -->
    <script src="js/plugins.js"></script>
    <script src="js/designesia.js"></script>
    <script src="js/swiper.js"></script>
    <script src="js/custom-marquee.js"></script>
    <script src="js/custom-swiper-1.js"></script>
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            const adultsInput = document.getElementById("room-adults");
            const roomTypeSelect = document.getElementById("room-type");
            const roomItems = document.querySelectorAll(".room-filter-item");
            const filterSummary = document.getElementById("room-filter-summary");
            const emptyState = document.getElementById("room-filter-empty");
            const filterForm = document.getElementById("room-filter-form");
            const stepperBtns = document.querySelectorAll(".filter-stepper-btn");
            const checkInInput = document.getElementById("room-check-in");
            const checkOutInput = document.getElementById("room-check-out");

            const applyLiveFilter = () => {
                if (!roomItems.length || !adultsInput || !roomTypeSelect) return;

                const adults = parseInt(adultsInput.value, 10) || 0;
                const roomType = roomTypeSelect.value || "all";
                let visibleCount = 0;

                roomItems.forEach((item) => {
                    const capacity = parseInt(item.dataset.capacity || "0", 10);
                    const type = item.dataset.type || "";
                    const adultsMatch = adults === 0 || capacity === adults;
                    const typeMatch = roomType === "all" || type === roomType;
                    const show = adultsMatch && typeMatch;

                    item.style.display = show ? "" : "none";
                    if (show) visibleCount++;
                });

                if (filterSummary) {
                    let text = `Showing ${visibleCount} room(s)`;
                    if (adults > 0) {
                        text += ` for ${adults} guest(s)`;
                    }
                    if (roomType !== "all") {
                        const selected = roomTypeSelect.options[roomTypeSelect.selectedIndex]?.text || roomType;
                        text += ` | Type: ${selected}`;
                    }
                    filterSummary.textContent = text;
                }

                if (emptyState) {
                    emptyState.style.display = visibleCount === 0 ? "" : "none";
                }
            };

            if (filterForm) {
                filterForm.addEventListener("submit", function (e) {
                    e.preventDefault();
                    applyLiveFilter();
                });
            }

            stepperBtns.forEach((btn) => {
                btn.addEventListener("click", function () {
                    if (!adultsInput) return;
                    const currentValue = parseInt(adultsInput.value, 10) || 1;
                    const step = this.dataset.step;

                    if (step === "up") {
                        adultsInput.value = currentValue + 1;
                    } else if (step === "down" && currentValue > 0) {
                        adultsInput.value = currentValue - 1;
                    }
                    applyLiveFilter();
                });
            });

            if (roomTypeSelect) {
                roomTypeSelect.addEventListener("change", applyLiveFilter);
            }

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

            if (checkOutInput) {
                checkOutInput.setAttribute("min", today);
            }

            applyLiveFilter();
        });
    </script>

</body>

</html>
