<?php
session_start();
require_once 'db/config.php';
require_once 'header.php';

// Fetch emergency shutdown status
$stmt_shutdown = db()->prepare("SELECT value FROM settings WHERE name = ?");
$stmt_shutdown->execute(['emergency_shutdown']);
$shutdown_active = ($stmt_shutdown->fetchColumn() === 'true');

// Fetch all cuisines for the filter dropdown
$cuisines_stmt = db()->query("SELECT * FROM cuisines ORDER BY name");
$cuisines = $cuisines_stmt->fetchAll(PDO::FETCH_ASSOC);

// Base query
// Corrected GROUP_CONCAT for PostgreSQL
$sql = "SELECT r.id, r.name, r.image_url, STRING_AGG(c.name, ', ') as cuisines, AVG(ra.rating) as average_rating
        FROM restaurants r
        LEFT JOIN restaurant_cuisines rc ON r.id = rc.restaurant_id
        LEFT JOIN cuisines c ON rc.cuisine_id = c.id
        LEFT JOIN ratings ra ON r.id = ra.restaurant_id";

$where_clauses = [];
$params = [];

// Search functionality
if (!empty($_GET['search'])) {
    $where_clauses[] = "r.name ILIKE :search"; // ILIKE for case-insensitive search in PostgreSQL
    $params[':search'] = '%' . $_GET['search'] . '%';
}

// Cuisine filter
if (!empty($_GET['cuisine'])) {
    $where_clauses[] = "r.id IN (SELECT restaurant_id FROM restaurant_cuisines WHERE cuisine_id = :cuisine_id)";
    $params[':cuisine_id'] = $_GET['cuisine'];
}

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

$sql .= " GROUP BY r.id";

// Sorting functionality
$sort_order = $_GET['sort'] ?? 'name_asc';
switch ($sort_order) {
    case 'rating_desc':
        $sql .= " ORDER BY average_rating DESC NULLS LAST";
        break;
    case 'name_desc':
        $sql .= " ORDER BY r.name DESC";
        break;
    default:
        $sql .= " ORDER BY r.name ASC";
        break;
}

$stmt = db()->prepare($sql);
$stmt->execute($params);
$restaurants = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="container my-5">
    <?php if ($shutdown_active): ?>
        <div class="alert alert-danger text-center" role="alert">
            <h4 class="alert-heading">Ordering Temporarily Disabled</h4>
            <p>Due to severe weather conditions, we have temporarily suspended all delivery services. The safety of our drivers and customers is our top priority.</p>
            <hr>
            <p class="mb-0">We apologize for any inconvenience and will resume operations as soon as it is safe to do so.</p>
        </div>
    <?php endif; ?>

    <div class="row mb-4 align-items-center">
        <div class="col-lg-6">
            <h1 class="display-5 fw-bold">Our Restaurants</h1>
            <p class="text-muted">Explore a variety of cuisines from the best local restaurants.</p>
        </div>
    </div>

    <!-- Filters and Sorting -->
    <form action="restaurants.php" method="get" class="row g-3 mb-5 align-items-center bg-light p-3 rounded-3">
        <div class="col-lg-5 col-md-12">
            <div class="input-group">
                <span class="input-group-text"><i class="fas fa-search"></i></span>
                <input type="text" name="search" class="form-control" placeholder="Search for a restaurant..." value="<?php echo htmlspecialchars($_GET['search'] ?? ''); ?>">
            </div>
        </div>
        <div class="col-lg-3 col-md-6">
            <div class="input-group">
                <span class="input-group-text"><i class="fas fa-utensils"></i></span>
                <select name="cuisine" class="form-select">
                    <option value="">All Cuisines</option>
                    <?php foreach ($cuisines as $cuisine): ?>
                        <option value="<?php echo $cuisine['id']; ?>" <?php echo (($_GET['cuisine'] ?? '') == $cuisine['id']) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($cuisine['name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
        <div class="col-lg-2 col-md-6">
            <div class="input-group">
                 <span class="input-group-text"><i class="fas fa-sort-alpha-down"></i></span>
                <select name="sort" class="form-select">
                    <option value="name_asc" <?php echo ($sort_order == 'name_asc') ? 'selected' : ''; ?>>Name (A-Z)</option>
                    <option value="name_desc" <?php echo ($sort_order == 'name_desc') ? 'selected' : ''; ?>>Name (Z-A)</option>
                    <option value="rating_desc" <?php echo ($sort_order == 'rating_desc') ? 'selected' : ''; ?>>Rating</option>
                </select>
            </div>
        </div>
        <div class="col-lg-2 col-md-12">
            <button type="submit" class="btn btn-primary w-100">Apply Filters</button>
        </div>
    </form>

    <!-- Restaurant Grid -->
    <div class="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-4">
        <?php if ($restaurants): ?>
            <?php foreach ($restaurants as $restaurant): ?>
                <div class="col">
                    <div class="card h-100 restaurant-card-new shadow-sm">
                        <a href="menu.php?restaurant_id=<?php echo $restaurant['id']; ?>" class="card-link">
                            <div class="img-container">
                                <img src="<?php echo htmlspecialchars($restaurant['image_url'] ?: 'https://via.placeholder.com/400x250/dee2e6/6c757d.text=No+Image'); ?>" class="card-img-top" alt="<?php echo htmlspecialchars($restaurant['name']); ?>">
                            </div>
                            <div class="card-body">
                                <h5 class="card-title fw-bold"><?php echo htmlspecialchars($restaurant['name']); ?></h5>
                                <p class="card-text text-muted small"><?php echo htmlspecialchars($restaurant['cuisines']); ?></p>
                            </div>
                            <div class="card-footer bg-white border-0 pb-3">
                                <div class="d-flex justify-content-between align-items-center">
                                    <span class="text-warning fw-bold">
                                        <?php echo $restaurant['average_rating'] ? number_format($restaurant['average_rating'], 1) . ' <i class="fas fa-star"></i>' : 'No ratings'; ?>
                                    </span>
                                    <span class="btn btn-sm btn-primary">View Menu <i class="fas fa-arrow-right"></i></span>
                                </div>
                            </div>
                        </a>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="col-12">
                <div class="text-center py-5">
                    <i class="fas fa-store-slash fa-4x mb-3 text-muted"></i>
                    <h3 class="mt-4">No Restaurants Found</h3>
                    <p class="text-muted">Try adjusting your search or filters to find what you're looking for.</p>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

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