<?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
$sql = "SELECT r.id, r.name, r.image_url, GROUP_CONCAT(c.name SEPARATOR ', ') 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 LIKE :search";
    $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";
        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 mt-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; ?>

    <h1 class="text-center mb-5">Our Restaurants</h1>

    <!-- Filters and Sorting -->
    <form action="restaurants.php" method="get" class="row g-3 mb-5 align-items-center">
        <div class="col-md-5">
            <input type="text" name="search" class="form-control" placeholder="Search for a restaurant..." value="<?php echo htmlspecialchars($_GET['search'] ?? ''); ?>">
        </div>
        <div class="col-md-3">
            <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 class="col-md-2">
            <select name="sort" class="form-select">
                <option value="name_asc" <?php echo ($sort_order == 'name_asc') ? 'selected' : ''; ?>>Sort by Name (A-Z)</option>
                <option value="name_desc" <?php echo ($sort_order == 'name_desc') ? 'selected' : ''; ?>>Sort by Name (Z-A)</option>
                <option value="rating_desc" <?php echo ($sort_order == 'rating_desc') ? 'selected' : ''; ?>>Sort by Rating</option>
            </select>
        </div>
        <div class="col-md-2">
            <button type="submit" class="btn btn-primary w-100">Apply</button>
        </div>
    </form>

    <!-- Restaurant Grid -->
    <div class="row">
        <?php if ($restaurants): ?>
            <?php foreach ($restaurants as $restaurant): ?>
                <div class="col-md-4 mb-4">
                    <div class="card restaurant-card h-100">
                        <a href="menu.php?restaurant_id=<?php echo $restaurant['id']; ?>">
                            <img src="<?php echo htmlspecialchars($restaurant['image_url'] ?: 'assets/images/hero.jpg'); ?>" class="card-img-top" alt="<?php echo htmlspecialchars($restaurant['name']); ?>">
                        </a>
                        <div class="card-body">
                            <h5 class="card-title"><?php echo htmlspecialchars($restaurant['name']); ?></h5>
                            <p class="card-text text-muted"><?php echo htmlspecialchars($restaurant['cuisines']); ?></p>
                            <div class="d-flex justify-content-between align-items-center">
                                <span class="text-warning"><?php echo $restaurant['average_rating'] ? round($restaurant['average_rating'], 1) . ' ★' : 'No ratings'; ?></span>
                                <?php if ($shutdown_active): ?>
                                    <a href="#" class="btn btn-outline-danger disabled">Ordering Disabled</a>
                                <?php else: ?>
                                    <a href="menu.php?restaurant_id=<?php echo $restaurant['id']; ?>" class="btn btn-outline-primary">View Menu</a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <div class='col-12 text-center empty-state'>
                <i class='fas fa-store-slash fa-4x mb-3 text-muted'></i>
                <h3 class='mt-4'>No Restaurants Found</h3>
                <p>Try adjusting your search or filters to find what you're looking for.</p>
            </div>
        <?php endif; ?>
    </div>
</div>

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