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

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

$admin = $_SESSION['user'];

// 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">
<aside class="w-64 bg-white shadow-md h-full flex flex-col">
    <div class="p-6">
        <h1 class="text-xl font-bold text-blue-700">Sheridan Hotel</h1>
        <!--<p class="text-sm text-gray-500 mt-1">Admin Dashboard</p>-->
        <p class="text-gray-600 mb-6">You are logged in as <strong><?= $admin['role'] ?></strong>.</p>
    </div>
    <nav class="flex-1 px-4 space-y-2">
        <a href="dashboard.php" class="block px-4 py-2 text-gray-700 rounded hover:bg-gray-200">Dashboard Home</a>
        <a href="book_room.php" class="block px-4 py-2 text-gray-700 rounded hover:bg-gray-200">Book a Room</a>
        <a href="room_status.php" class="block px-4 py-2 text-gray-700 rounded hover:bg-gray-200">Check Room Status</a>
        <a href="available_rooms.php" class="block px-4 py-2 text-gray-700 rounded hover:bg-gray-200">Available Rooms</a>
        <a href="list_available.php" class="block px-4 py-2 text-gray-700 rounded hover:bg-gray-200">List of Available Rooms</a>
        <a href="list_booked.php" class="block px-4 py-2 text-gray-700 rounded hover:bg-gray-200">List of Booked Rooms</a>
    </nav>
    <div class="p-4 border-t">
        <p class="text-sm text-gray-500">All right reserved &copy;Sheridan Hotels and suits
 </p>
        <a href="../logout.php" class="mt-2 inline-block text-red-500 hover:underline text-sm">Logout</a>
    </div>
</aside>

<!-- Dashboard Body -->
 <!-- Content Area -->
<!-- Main content area -->
<div class="flex-1 flex flex-col overflow-hidden">

    <!-- Top Navbar -->
    <nav class="bg-white shadow px-6 py-4 flex justify-between items-center">
        <h1 class="text-xl font-bold text-gray-800">Dashboard Overview</h1>
        <div class="flex items-center gap-4">
            <span class="text-gray-600 text-sm">Welcome, <?= htmlspecialchars($admin['name']) ?>  <span id="datetime"></span>
<script>setInterval(() => document.getElementById('datetime').textContent = new Date().toLocaleString(undefined, { hour12: false }), 1000);</script></span>
             
            
        </div>
    </nav>

    <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>
