<?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'): ?>
        <button onclick="markCleaned(<?= $room['id'] ?>)" class="bg-green-500 text-white px-2 py-1 rounded text-sm hover:bg-green-600">Mark Cleaned</button>
    <?php endif; ?>
    <?php if ($room['status'] === 'available'): ?>
        <a href="book_room.php?room_id=<?= $room['id'] ?>" class="bg-blue-500 text-white px-2 py-1 rounded text-sm hover:bg-blue-600">Book Now</a>
    <?php endif; ?>
    <button onclick="viewRoomDetails(<?= htmlspecialchars(json_encode($room)) ?>)" class="bg-gray-500 text-white px-2 py-1 rounded text-sm hover:bg-gray-600">View</button>
</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>



    <!-- Room Details Modal -->
<div id="roomModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">
    <div class="bg-white p-6 rounded shadow w-96 relative">
        <button onclick="closeModal()" class="absolute top-2 right-2 text-gray-500 hover:text-black">&times;</button>
        <h3 class="text-xl font-bold mb-4">Room Details</h3>
        <div id="roomDetails"></div>
    </div>
</div>
<script>
function markCleaned(roomId) {
    if (!confirm('Mark this room as cleaned and available?')) return;

    fetch('mark_cleaned.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'room_id=' + roomId
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            alert('Room marked as cleaned.');
            location.reload();
        } else {
            alert('Error: ' + (data.error || 'Could not mark room as cleaned.'));
        }
    });
}

function viewRoomDetails(room) {
    const modal = document.getElementById('roomModal');
    const detailBox = document.getElementById('roomDetails');
    detailBox.innerHTML = `
        <p><strong>Room Number:</strong> ${room.room_number}</p>
        <p><strong>Category:</strong> ${room.category_name}</p>
        <p><strong>Status:</strong> ${room.status}</p>
        <p><strong>Floor:</strong> ${room.floor || 'N/A'}</p>
        <p><strong>Description:</strong> ${room.description || 'No description'}</p>
    `;
    modal.classList.remove('hidden');
}

function closeModal() {
    document.getElementById('roomModal').classList.add('hidden');
}
</script>

</body>
</html>
