<?php include 'header.php'; ?>

<main>
    <section class="hero">
        <div class="hero-content">
            <h1>Order from Majuro's best</h1>
            <form action="index.php" method="get" class="search-form">
                <input type="text" name="search" class="search-bar" placeholder="Search for restaurants..." value="<?= isset($_GET['search']) ? htmlspecialchars($_GET['search']) : '' ?>">
                <button type="submit" class="search-button">Search</button>
            </form>
        </div>
    </section>

    <div class="container">
        <div class="row">
            <!-- Filter Sidebar -->
            <div class="col-md-3">
                <h4>Filter by Cuisine</h4>
                <form action="index.php" method="get" id="filter-form">
                    <!-- Hidden search field to persist search query -->
                    <?php if (isset($_GET['search'])): ?>
                        <input type="hidden" name="search" value="<?= htmlspecialchars($_GET['search']) ?>">
                    <?php endif; ?>

                    <?php
                    $cuisine_stmt = $pdo->query("SELECT * FROM cuisines ORDER BY name");
                    $all_cuisines = $cuisine_stmt->fetchAll(PDO::FETCH_ASSOC);
                    $selected_cuisines = isset($_GET['cuisines']) && is_array($_GET['cuisines']) ? $_GET['cuisines'] : [];

                    foreach ($all_cuisines as $cuisine): ?>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="cuisines[]" value="<?= $cuisine['id'] ?>" id="cuisine-<?= $cuisine['id'] ?>" <?= in_array($cuisine['id'], $selected_cuisines) ? 'checked' : '' ?>>
                            <label class="form-check-label" for="cuisine-<?= $cuisine['id'] ?>">
                                <?= htmlspecialchars($cuisine['name']) ?>
                            </label>
                        </div>
                    <?php endforeach; ?>
                    <button type="submit" class="btn btn-primary mt-3">Apply Filter</button>
                    <a href="index.php" class="btn btn-secondary mt-3">Clear Filter</a>
                </form>
            </div>

            <!-- Restaurant Listing -->
            <div class="col-md-9">
                <h2 class="page-title">All Restaurants</h2>
                <section class="restaurant-list">
                    <div class="restaurant-grid" id="restaurant-grid">
                        <?php
                        // Base query
                        $sql = "SELECT DISTINCT r.id, r.name, r.image_url, AVG(rt.rating) as average_rating, COUNT(rt.id) as rating_count 
                                FROM restaurants r
                                LEFT JOIN ratings rt ON r.id = rt.restaurant_id";
                        $params = [];

                        // Join with restaurant_cuisines if filtering by cuisine
                        if (!empty($selected_cuisines)) {
                            $sql .= " JOIN restaurant_cuisines rc ON r.id = rc.restaurant_id";
                        }

                        $where_clauses = [];

                        // Append search condition
                        if (!empty($_GET['search'])) {
                            $where_clauses[] = "r.name LIKE ?";
                            $params[] = '%' . $_GET['search'] . '%';
                        }

                        // Append cuisine filter
                        if (!empty($selected_cuisines)) {
                            $placeholders = implode(',', array_fill(0, count($selected_cuisines), '?'));
                            $where_clauses[] = "rc.cuisine_id IN ($placeholders)";
                            $params = array_merge($params, $selected_cuisines);
                        }

                        if (!empty($where_clauses)) {
                            $sql .= " WHERE " . implode(' AND ', $where_clauses);
                        }

                        $sql .= " GROUP BY r.id, r.name, r.image_url ORDER BY r.name";

                        $stmt = $pdo->prepare($sql);
                        $stmt->execute($params);
                        $restaurants = $stmt->fetchAll();

                        if (empty($restaurants)) {
                            echo '<p>No restaurants found matching your criteria.</p>';
                        } else {
                            foreach ($restaurants as $restaurant) {
                                // Get cuisines for this restaurant
                                $cuisine_sql = "SELECT c.name FROM cuisines c JOIN restaurant_cuisines rc ON c.id = rc.cuisine_id WHERE rc.restaurant_id = ?";
                                $cuisine_stmt = $pdo->prepare($cuisine_sql);
                                $cuisine_stmt->execute([$restaurant['id']]);
                                $restaurant_cuisines_list = $cuisine_stmt->fetchAll(PDO::FETCH_COLUMN);

                                echo '<a href="menu.php?id=' . htmlspecialchars($restaurant['id']) . '" class="restaurant-card">';
                                echo '<img src="' . htmlspecialchars($restaurant['image_url'] ? $restaurant['image_url'] : 'assets/images/hero.jpg') . '" alt="' . htmlspecialchars($restaurant['name']) . '">';
                                echo '<div class="restaurant-card-content">';
                                echo '<h3>' . htmlspecialchars($restaurant['name']) . '</h3>';
                                echo '<p>' . htmlspecialchars(implode(', ', $restaurant_cuisines_list)) . '</p>';
                                if ($restaurant['rating_count'] > 0) {
                                    echo '<div class="rating-display">';
                                    echo '<span class="star">★</span>';
                                    echo '<span>' . htmlspecialchars(number_format($restaurant['average_rating'], 1)) . '</span>';
                                    echo '<span class="rating-count">(' . htmlspecialchars($restaurant['rating_count']) . ' ratings)</span>';
                                    echo '</div>';
                                } else {
                                    echo '<div class="rating-display"><span class="rating-count">No ratings yet</span></div>';
                                }
                                echo '</div>';
                                echo '</a>';
                            }
                        }
                        ?>
                    </div>
                </section>
            </div>
        </div>
    </div>
</main>

<style>
    .container {
        max-width: 1200px;
        margin: 0 auto;
        padding: 20px;
    }
    .row {
        display: flex;
        flex-wrap: wrap;
        margin: 0 -15px;
    }
    .col-md-3 {
        width: 25%;
        padding: 0 15px;
    }
    .col-md-9 {
        width: 75%;
        padding: 0 15px;
    }
    .form-check {
        margin-bottom: 10px;
    }
    .btn {
        padding: 8px 15px;
        border-radius: 5px;
        text-decoration: none;
        cursor: pointer;
        display: inline-block;
        text-align: center;
    }
    .btn-primary {
        background-color: #007bff;
        color: white;
        border: 1px solid #007bff;
    }
    .btn-secondary {
        background-color: #6c757d;
        color: white;
        border: 1px solid #6c757d;
    }
    .mt-3 {
        margin-top: 1rem;
    }
    .search-form {
        display: flex;
    }
    .search-bar {
        flex-grow: 1;
    }
</style>

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