<?php
session_start();
require_once __DIR__ . '/../includes/db.php';

if (!isset($_SESSION['user']) || $_SESSION['user']['role'] !== 'admin') {
    header("Location: ../index.php");
    exit;
}

// Get filter values
$statusFilter = $_GET['status'] ?? '';
$categoryFilter = $_GET['category'] ?? '';

// Pagination setup
$limit = 10;
$page = max((int)($_GET['page'] ?? 1), 1);
$offset = ($page - 1) * $limit;

// Base query
$where = [];
$params = [];

// Filter conditions
if ($statusFilter) {
    $where[] = 'r.status = ?';
    $params[] = $statusFilter;
}
if ($categoryFilter) {
    $where[] = 'r.category_id = ?';
    $params[] = $categoryFilter;
}

$whereSQL = $where ? 'WHERE ' . implode(' AND ', $where) : '';

// Fetch rooms
$stmt = $pdo->prepare("
    SELECT r.*, c.name AS category_name 
    FROM rooms r 
    JOIN room_categories c ON r.category_id = c.id 
    $whereSQL 
    ORDER BY r.id DESC 
    LIMIT $limit OFFSET $offset
");
$stmt->execute($params);
$rooms = $stmt->fetchAll();

// Count total rooms for pagination
$countStmt = $pdo->prepare("SELECT COUNT(*) FROM rooms r $whereSQL");
$countStmt->execute($params);
$totalRooms = $countStmt->fetchColumn();
$totalPages = ceil($totalRooms / $limit);

// Get all categories for filter dropdown
$categoryStmt = $pdo->query("SELECT id, name FROM room_categories ORDER BY name");
$categories = $categoryStmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Check Room Status</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 p-6">

    <div class="max-w-7xl mx-auto bg-white p-6 rounded shadow">
        <h2 class="text-2xl font-bold mb-4">Room Status Overview</h2>

        <!-- Filters -->
        <form method="GET" class="flex flex-wrap gap-4 mb-6">
            <select name="status" class="border p-2 rounded">
                <option value="">All Statuses</option>
                <option value="available" <?= $statusFilter === 'available' ? 'selected' : '' ?>>Available</option>
                <option value="booked" <?= $statusFilter === 'booked' ? 'selected' : '' ?>>Booked</option>
                <option value="occupied" <?= $statusFilter === 'occupied' ? 'selected' : '' ?>>Occupied</option>
                <option value="maintenance" <?= $statusFilter === 'maintenance' ? 'selected' : '' ?>>Under Maintenance</option>
            </select>

            <select name="category" class="border p-2 rounded">
                <option value="">All Categories</option>
                <?php foreach ($categories as $cat): ?>
                    <option value="<?= $cat['id'] ?>" <?= $categoryFilter == $cat['id'] ? 'selected' : '' ?>>
                        <?= htmlspecialchars($cat['name']) ?>
                    </option>
                <?php endforeach; ?>
            </select>

            <button type="submit" class="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700">Filter</button>
        </form>

        <!-- Table -->
        <div class="overflow-x-auto">
            <table class="min-w-full bg-white border rounded">
                <thead>
                    <tr class="bg-gray-200 text-left">
                        <th class="px-4 py-2">Room Number</th>
                        <th class="px-4 py-2">Category</th>
                        <th class="px-4 py-2">Status</th>
                        <th class="px-4 py-2">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($rooms) > 0): ?>
                        <?php foreach ($rooms as $room): ?>
                            <tr class="border-b hover:bg-gray-50">
                                <td class="px-4 py-2"><?= htmlspecialchars($room['room_number']) ?></td>
                                <td class="px-4 py-2"><?= htmlspecialchars($room['category_name']) ?></td>
                                <td class="px-4 py-2">
                                    <span class="px-2 py-1 text-sm rounded 
                                        <?= match($room['status']) {
                                            'available' => 'bg-green-100 text-green-700',
                                            'booked' => 'bg-yellow-100 text-yellow-700',
                                            'occupied' => 'bg-red-100 text-red-700',
                                            'maintenance' => 'bg-gray-100 text-gray-700',
                                            default => 'bg-blue-100 text-blue-700'
                                        } ?>">
                                        <?= ucfirst($room['status']) ?>
                                    </span>
                                </td>
                                <td class="px-4 py-2 flex gap-2">
                                    <?php if ($room['status'] === 'available'): ?>
                                        <a href="book_room.php?room_id=<?= $room['id'] ?>" class="text-white bg-blue-500 hover:bg-blue-600 px-3 py-1 text-sm rounded">Book Now</a>
                                    <?php endif; ?>

                                    <?php if (in_array($room['status'], ['booked', 'occupied', 'maintenance'])): ?>
                                        <form action="mark_cleaned.php" method="POST" onsubmit="return confirm('Mark as cleaned?')">
                                            <input type="hidden" name="room_id" value="<?= $room['id'] ?>">
                                            <button type="submit" class="bg-green-500 text-white px-3 py-1 text-sm rounded hover:bg-green-600">Mark Cleaned</button>
                                        </form>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="4" class="text-center py-4 text-gray-500">No rooms found for this filter.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <div class="mt-6 flex justify-center gap-2">
            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                <a href="?page=<?= $i ?>&status=<?= $statusFilter ?>&category=<?= $categoryFilter ?>"
                   class="px-3 py-1 border rounded <?= $i == $page ? 'bg-blue-600 text-white' : 'bg-white text-blue-600 hover:bg-blue-100' ?>">
                    <?= $i ?>
                </a>
            <?php endfor; ?>
        </div>
    </div>
</body>
</html>
