<?php
// 1. INCLUDE HEADER & HELPERS
include 'includes/header.php'; 
require_once 'includes/helpers.php'; 

// 2. INITIALIZE FILTERS & PAGINATION
$records_per_page = 9;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $records_per_page;

// Get filter values from URL
$location_search = trim($_GET['location'] ?? '');
$rating_filter = isset($_GET['rating']) && is_array($_GET['rating']) ? $_GET['rating'] : [];
$amenities_filter = isset($_GET['amenities']) && is_array($_GET['amenities']) ? $_GET['amenities'] : [];
$sort_by = $_GET['sort'] ?? 'rating_desc';

// 3. BUILD DYNAMIC SQL QUERY
$where_clauses = ["h.is_published = 1"];
$params = [];
$types = '';

if (!empty($location_search)) {
    $where_clauses[] = "h.location LIKE ?";
    $params[] = "%{$location_search}%";
    $types .= 's';
}

if (!empty($rating_filter)) {
    $placeholders = implode(',', array_fill(0, count($rating_filter), '?'));
    $where_clauses[] = "h.star_rating IN ($placeholders)";
    foreach ($rating_filter as $rating) {
        $params[] = $rating;
        $types .= 'i';
    }
}

if (!empty($amenities_filter)) {
    foreach ($amenities_filter as $amenity) {
        $where_clauses[] = "FIND_IN_SET(?, h.amenities)";
        $params[] = $amenity;
        $types .= 's';
    }
}

$where_sql = "WHERE " . implode(' AND ', $where_clauses);

// Determine sorting order
$order_by_sql = "ORDER BY ";
switch ($sort_by) {
    case 'price_asc':
        $order_by_sql .= "min_price ASC";
        break;
    case 'price_desc':
        $order_by_sql .= "min_price DESC";
        break;
    default:
        $order_by_sql .= "h.star_rating DESC, h.name ASC";
}

// Subquery to get the minimum price for each hotel
$price_subquery = "(SELECT MIN(price_per_night) FROM hotel_room_rates r JOIN hotel_rooms hr ON r.room_id = hr.id WHERE hr.hotel_id = h.id AND r.is_active = 1)";

// 4. EXECUTE QUERIES
$base_query = "FROM hotels h $where_sql";

$count_sql = "SELECT COUNT(h.id) as total $base_query";
$stmt_count = $conn->prepare($count_sql);
if (count($params) > 0) { $stmt_count->bind_param($types, ...$params); }
$stmt_count->execute();
$total_records = $stmt_count->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_records / $records_per_page);
$stmt_count->close();

$fetch_sql = "SELECT h.*, $price_subquery as min_price $base_query $order_by_sql LIMIT ? OFFSET ?";
$params[] = $records_per_page; $params[] = $offset; $types .= 'ii';
$stmt_fetch = $conn->prepare($fetch_sql);
if (count($params) > 0) { $stmt_fetch->bind_param($types, ...$params); }
$stmt_fetch->execute();
$hotels_result = $stmt_fetch->get_result();

$common_amenities = ['Wifi', 'Pool', 'Parking', 'Restaurant', 'Pet Friendly', 'Fitness Center', 'Spa'];
?>

<div class="container my-4">
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="index.php">Home</a></li>
            <li class="breadcrumb-item active" aria-current="page">Hotels</li>
        </ol>
    </nav>
    <h1 class="display-5">Find Your Perfect Stay</h1>
</div>

<div class="container mb-5">
    <div class="row">
        <aside class="col-lg-3">
            <div class="card shadow-sm sticky-top" style="top: 20px;">
                <div class="card-header bg-light">
                    <h5 class="mb-0"><i class="bi bi-funnel-fill me-2"></i>Filter Results</h5>
                </div>
                <div class="card-body">
                    <form id="filter-form" method="GET">
                        <div class="mb-4">
                            <label for="location" class="form-label fw-bold">Destination</label>
                            <input type="text" id="location" name="location" class="form-control" placeholder="e.g., Cebu" value="<?php echo htmlspecialchars($location_search); ?>">
                        </div>
                        <div class="mb-4">
                            <h6 class="fw-bold">Star Rating</h6>
                            <?php for($i=5; $i>=2; $i--): ?>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="rating[]" value="<?php echo $i; ?>" id="rating<?php echo $i; ?>" <?php if (in_array($i, $rating_filter)) echo 'checked'; ?>>
                                <label class="form-check-label text-warning" for="rating<?php echo $i; ?>">
                                    <?php for($s=0; $s<$i; $s++) echo '<i class="bi bi-star-fill"></i>'; ?>
                                </label>
                            </div>
                            <?php endfor; ?>
                        </div>
                        <div class="mb-3">
                             <h6 class="fw-bold">Amenities</h6>
                             <?php foreach($common_amenities as $amenity): ?>
                             <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="amenities[]" value="<?php echo $amenity; ?>" id="amenity-<?php echo str_replace(' ','',$amenity); ?>" <?php if (in_array($amenity, $amenities_filter)) echo 'checked'; ?>>
                                <label class="form-check-label" for="amenity-<?php echo str_replace(' ','',$amenity); ?>"><?php echo $amenity; ?></label>
                            </div>
                             <?php endforeach; ?>
                        </div>
                        <div class="d-grid">
                            <button type="submit" class="btn btn-primary">Apply Filters</button>
                        </div>
                    </form>
                </div>
            </div>
        </aside>

        <main class="col-lg-9">
            <div class="d-flex justify-content-between align-items-center mb-3 p-3 bg-light rounded">
                <span class="fw-bold">Showing <?php echo $hotels_result->num_rows; ?> of <?php echo $total_records; ?> hotels</span>
                <form id="sort-form" method="GET" class="d-flex align-items-center">
                    <input type="hidden" name="location" value="<?php echo htmlspecialchars($location_search); ?>">
                    <?php foreach ($rating_filter as $r) echo '<input type="hidden" name="rating[]" value="'.$r.'">'; ?>
                    <?php foreach ($amenities_filter as $a) echo '<input type="hidden" name="amenities[]" value="'.$a.'">'; ?>
                    <label for="sort" class="form-label me-2 mb-0">Sort by:</label>
                    <select name="sort" id="sort" class="form-select form-select-sm" onchange="this.form.submit()">
                        <option value="rating_desc" <?php if ($sort_by == 'rating_desc') echo 'selected'; ?>>Rating (High to Low)</option>
                        <option value="price_asc" <?php if ($sort_by == 'price_asc') echo 'selected'; ?>>Price (Low to High)</option>
                        <option value="price_desc" <?php if ($sort_by == 'price_desc') echo 'selected'; ?>>Price (High to Low)</option>
                    </select>
                </form>
            </div>
            
            <div class="row row-cols-1 row-cols-md-2 row-cols-xl-3 g-4">
                <?php if ($hotels_result->num_rows > 0): while($hotel = $hotels_result->fetch_assoc()): ?>
                <div class="col">
                    <div class="card h-100 tour-card">
                        <a href="hotel-details.php?id=<?php echo $hotel['id']; ?>">
                            <img src="<?php echo htmlspecialchars($hotel['main_image_url'] ?? 'https://via.placeholder.com/300x200.png?text=No+Image'); ?>" class="card-img-top" alt="<?php echo htmlspecialchars($hotel['name']); ?>">
                        </a>
                        <div class="card-body d-flex flex-column">
                            <h5 class="card-title"><?php echo htmlspecialchars($hotel['name']); ?></h5>
                            <p class="card-text text-muted small"><i class="bi bi-geo-alt-fill"></i> <?php echo htmlspecialchars($hotel['location']); ?></p>
                            <div class="text-warning mb-2">
                                <?php for($i=0; $i<$hotel['star_rating']; $i++) echo '<i class="bi bi-star-fill"></i>'; ?>
                            </div>
                            <div class="mt-auto">
                                <?php if (isset($hotel['min_price'])): ?>
                                <p class="mb-2">From <span class="fw-bold h5">₱<?php echo number_format($hotel['min_price'], 2); ?></span>/night</p>
                                <?php endif; ?>
                                <a href="hotel-details.php?id=<?php echo $hotel['id']; ?>" class="btn btn-primary w-100">See Rooms & Rates</a>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endwhile; else: ?>
                <div class="col-12">
                    <div class="alert alert-warning text-center">No hotels found matching your criteria. Please try broadening your search.</div>
                </div>
                <?php endif; ?>
            </div>
            
            <?php if($total_pages > 1): ?>
            <nav class="mt-5"><ul class="pagination justify-content-center">
                <?php
                    $query_params = $_GET; unset($query_params['page']);
                    for ($i = 1; $i <= $total_pages; $i++): 
                    $query_params['page'] = $i;
                ?>
                <li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query($query_params); ?>"><?php echo $i; ?></a>
                </li>
                <?php endfor; ?>
            </ul></nav>
            <?php endif; ?>
        </main>
    </div>
</div>

<?php include 'includes/footer.php'; ?>
