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

// Debug mode - set to false in production
$debug_mode = true;

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

$admin = $_SESSION['user'];

// Get and sanitize filter values
$statusFilter = trim($_GET['status'] ?? '');
$categoryFilter = (int)($_GET['category'] ?? 0);

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

// Build query conditions
$whereConditions = [];
$params = [];

if (!empty($statusFilter)) {
    $whereConditions[] = 'r.status = ?';
    $params[] = $statusFilter;
}

if ($categoryFilter > 0) {
    $whereConditions[] = 'r.category_id = ?';
    $params[] = $categoryFilter;
}

$whereSQL = !empty($whereConditions) ? 'WHERE ' . implode(' AND ', $whereConditions) : '';

try {
    // Get all categories for filter dropdown first
    $categoryStmt = $pdo->query("SELECT id, name FROM room_categories ORDER BY name");
    $categories = $categoryStmt->fetchAll(PDO::FETCH_ASSOC);

    // Fetch rooms - build query without parameter binding for LIMIT/OFFSET to avoid issues
    $sql = "
        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 " . (int)$limit . " OFFSET " . (int)$offset;
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $rooms = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Count total rooms for pagination - simplified query
    $countSQL = "
        SELECT COUNT(*) 
        FROM rooms r 
        JOIN room_categories c ON r.category_id = c.id 
        $whereSQL";
    $countStmt = $pdo->prepare($countSQL);
    $countStmt->execute($params);
    $totalRooms = $countStmt->fetchColumn();
    $totalPages = ceil($totalRooms / $limit);

} catch (PDOException $e) {
    error_log("Database error in room_status.php: " . $e->getMessage());
    error_log("SQL Query: " . ($sql ?? 'N/A'));
    error_log("Parameters: " . print_r($params, true));
    
    $rooms = [];
    $categories = [];
    $totalRooms = 0;
    $totalPages = 0;
    $error_message = "Database error: " . $e->getMessage() . " (Check error logs for details)";
}

// Helper function to build filter-aware pagination URLs
function buildPaginationUrl($page, $statusFilter, $categoryFilter) {
    $params = ['page' => $page];
    if (!empty($statusFilter)) $params['status'] = $statusFilter;
    if ($categoryFilter > 0) $params['category'] = $categoryFilter;
    return '?' . http_build_query($params);
}

// Helper function to get status badge class
function getStatusBadgeClass($status) {
    return match($status) {
        'available' => 'bg-green-100 text-green-700 border-green-200',
        'booked' => 'bg-yellow-100 text-yellow-700 border-yellow-200',
        'occupied' => 'bg-red-100 text-red-700 border-red-200',
        'maintenance' => 'bg-gray-100 text-gray-700 border-gray-200',
        default => 'bg-blue-100 text-blue-700 border-blue-200'
    };
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Check Room Status - Sheridan Hotel</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 flex h-screen">
    <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-gray-600 mb-6">You are logged in as <strong><?= htmlspecialchars($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-blue-700 bg-blue-50 rounded font-medium">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="check_out.php" class="block px-4 py-2 text-gray-700 rounded hover:bg-gray-200">Customer Check-out</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 rights reserved &copy; Sheridan Hotels and Suites</p>
            <a href="../logout.php" class="mt-2 inline-block text-red-500 hover:underline text-sm">Logout</a>
        </div>
    </aside>

    <!-- 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">Room Status Management</h1>
            <div class="flex items-center gap-4">
                <span class="text-gray-600 text-sm">Welcome, <?= htmlspecialchars($admin['name']) ?></span>
                <span id="datetime" class="text-gray-500 text-sm"></span>
            </div>
        </nav>

        <main class="p-6 overflow-y-auto">
            <?php if (isset($error_message)): ?>
                <div class="mb-4 p-4 bg-red-100 border border-red-300 text-red-700 rounded">
                    <?= htmlspecialchars($error_message) ?>
                </div>
            <?php endif; ?>

            <?php if ($debug_mode && !empty($params)): ?>
                <div class="mb-4 p-4 bg-yellow-100 border border-yellow-300 text-yellow-700 rounded text-sm">
                    <strong>Debug Info:</strong><br>
                    Status Filter: <?= htmlspecialchars($statusFilter ?: 'None') ?><br>
                    Category Filter: <?= $categoryFilter > 0 ? $categoryFilter : 'None' ?><br>
                    Where Conditions: <?= htmlspecialchars(implode(' AND ', $whereConditions)) ?><br>
                    Parameters: <?= htmlspecialchars(print_r($params, true)) ?>
                </div>
            <?php endif; ?>

            <div class="max-w-7xl mx-auto bg-white p-6 rounded-lg shadow">
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-2xl font-bold">Room Status Overview</h2>
                    <?php if (!empty($statusFilter) || $categoryFilter > 0): ?>
                        <div class="flex items-center gap-2">
                            <span class="text-sm text-gray-600">Filters active:</span>
                            <?php if (!empty($statusFilter)): ?>
                                <span class="px-2 py-1 bg-blue-100 text-blue-700 rounded text-sm"><?= ucfirst($statusFilter) ?></span>
                            <?php endif; ?>
                            <?php if ($categoryFilter > 0): ?>
                                <?php 
                                $activeCat = array_filter($categories, fn($c) => $c['id'] == $categoryFilter);
                                $activeCatName = !empty($activeCat) ? reset($activeCat)['name'] : 'Category';
                                ?>
                                <span class="px-2 py-1 bg-green-100 text-green-700 rounded text-sm"><?= htmlspecialchars($activeCatName) ?></span>
                            <?php endif; ?>
                            <a href="room_status.php" class="text-sm text-red-600 hover:underline">Clear filters</a>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Filters Form -->
                <div class="bg-gray-50 p-4 rounded-lg mb-6">
                    <form method="GET" class="flex flex-wrap gap-4 items-end">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                            <select name="status" class="border border-gray-300 p-2 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                                <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>
                        </div>

                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Category</label>
                            <select name="category" class="border border-gray-300 p-2 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                                <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>
                        </div>

                        <div class="flex gap-2">
                            <button type="submit" class="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 transition-colors">
                                Apply Filters
                            </button>
                            <?php if (!empty($statusFilter) || $categoryFilter > 0): ?>
                                <a href="room_status.php" class="bg-gray-500 text-white px-4 py-2 rounded-md hover:bg-gray-600 transition-colors">
                                    Clear
                                </a>
                            <?php endif; ?>
                        </div>
                    </form>
                </div>

                <!-- Results Summary -->
                <div class="mb-4">
                    <p class="text-sm text-gray-600">
                        Showing <?= count($rooms) ?> of <?= $totalRooms ?> rooms
                        <?php if ($totalPages > 1): ?>
                            (Page <?= $page ?> of <?= $totalPages ?>)
                        <?php endif; ?>
                    </p>
                </div>

                <!-- Table -->
                <div class="overflow-x-auto">
                    <table class="min-w-full bg-white border border-gray-200 rounded-lg">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Room Number</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Category</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php if (count($rooms) > 0): ?>
                                <?php foreach ($rooms as $room): ?>
                                    <tr class="hover:bg-gray-50 transition-colors">
                                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                                            <?= htmlspecialchars($room['room_number']) ?>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                            <?= htmlspecialchars($room['category_name']) ?>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap">
                                            <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full border <?= getStatusBadgeClass($room['status']) ?>">
                                                <?= ucfirst($room['status']) ?>
                                            </span>
                                        </td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium space-x-2">
                                            <?php if ($room['status'] !== 'available'): ?>
                                                <button onclick="markCleaned(<?= $room['id'] ?>)" 
                                                        class="bg-green-500 text-white px-3 py-1 rounded text-sm hover:bg-green-600 transition-colors">
                                                    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-3 py-1 rounded text-sm hover:bg-blue-600 transition-colors inline-block">
                                                    Book Now
                                                </a>
                                            <?php endif; ?>
                                            
                                            <button onclick="viewRoomDetails(<?= htmlspecialchars(json_encode($room)) ?>)" 
                                                    class="bg-gray-500 text-white px-3 py-1 rounded text-sm hover:bg-gray-600 transition-colors">
                                                View Details
                                            </button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="4" class="px-6 py-12 text-center text-gray-500">
                                        <div class="text-lg mb-2">No rooms found</div>
                                        <div class="text-sm">Try adjusting your filters or check back later.</div>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <?php if ($totalPages > 1): ?>
                    <div class="mt-6 flex justify-center">
                        <nav class="flex items-center space-x-1">
                            <?php if ($page > 1): ?>
                                <a href="<?= buildPaginationUrl($page - 1, $statusFilter, $categoryFilter) ?>" 
                                   class="px-3 py-2 text-sm border border-gray-300 rounded-l-md bg-white text-gray-500 hover:bg-gray-50">
                                    Previous
                                </a>
                            <?php endif; ?>

                            <?php 
                            $start = max(1, $page - 2);
                            $end = min($totalPages, $page + 2);
                            
                            if ($start > 1): ?>
                                <a href="<?= buildPaginationUrl(1, $statusFilter, $categoryFilter) ?>" 
                                   class="px-3 py-2 text-sm border border-gray-300 bg-white text-gray-700 hover:bg-gray-50">1</a>
                                <?php if ($start > 2): ?>
                                    <span class="px-3 py-2 text-sm text-gray-500">...</span>
                                <?php endif; ?>
                            <?php endif; ?>

                            <?php for ($i = $start; $i <= $end; $i++): ?>
                                <a href="<?= buildPaginationUrl($i, $statusFilter, $categoryFilter) ?>" 
                                   class="px-3 py-2 text-sm border <?= $i == $page ? 'bg-blue-600 text-white border-blue-600' : 'border-gray-300 bg-white text-gray-700 hover:bg-gray-50' ?>">
                                    <?= $i ?>
                                </a>
                            <?php endfor; ?>

                            <?php if ($end < $totalPages): ?>
                                <?php if ($end < $totalPages - 1): ?>
                                    <span class="px-3 py-2 text-sm text-gray-500">...</span>
                                <?php endif; ?>
                                <a href="<?= buildPaginationUrl($totalPages, $statusFilter, $categoryFilter) ?>" 
                                   class="px-3 py-2 text-sm border border-gray-300 bg-white text-gray-700 hover:bg-gray-50"><?= $totalPages ?></a>
                            <?php endif; ?>

                            <?php if ($page < $totalPages): ?>
                                <a href="<?= buildPaginationUrl($page + 1, $statusFilter, $categoryFilter) ?>" 
                                   class="px-3 py-2 text-sm border border-gray-300 rounded-r-md bg-white text-gray-500 hover:bg-gray-50">
                                    Next
                                </a>
                            <?php endif; ?>
                        </nav>
                    </div>
                <?php endif; ?>
            </div>
        </main>
    </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-lg shadow-xl w-96 max-w-full mx-4 relative">
            <button onclick="closeModal()" class="absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-xl">
                &times;
            </button>
            <h3 class="text-xl font-bold mb-4 text-gray-800">Room Details</h3>
            <div id="roomDetails" class="space-y-3"></div>
            <div class="mt-6 flex justify-end">
                <button onclick="closeModal()" class="px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600">
                    Close
                </button>
            </div>
        </div>
    </div>

    <script>
        // Update datetime display
        function updateDateTime() {
            const now = new Date();
            document.getElementById('datetime').textContent = now.toLocaleString(undefined, { 
                hour12: false,
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        }
        setInterval(updateDateTime, 1000);
        updateDateTime();

        function markCleaned(roomId) {
            if (!confirm('Mark this room as cleaned and available?')) return;

            // Show loading state
            const button = event.target;
            const originalText = button.textContent;
            button.textContent = 'Processing...';
            button.disabled = true;

            fetch('mark_cleaned.php', {
                method: 'POST',
                headers: { 
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: 'room_id=' + encodeURIComponent(roomId)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    alert('Room marked as cleaned and available.');
                    location.reload();
                } else {
                    alert('Error: ' + (data.error || 'Could not mark room as cleaned.'));
                    button.textContent = originalText;
                    button.disabled = false;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred. Please try again.');
                button.textContent = originalText;
                button.disabled = false;
            });
        }

        function viewRoomDetails(room) {
            const modal = document.getElementById('roomModal');
            const detailBox = document.getElementById('roomDetails');
            
            detailBox.innerHTML = `
                <div class="grid grid-cols-1 gap-3">
                    <div class="flex justify-between">
                        <span class="font-medium text-gray-700">Room Number:</span>
                        <span class="text-gray-900">${escapeHtml(room.room_number)}</span>
                    </div>
                    <div class="flex justify-between">
                        <span class="font-medium text-gray-700">Category:</span>
                        <span class="text-gray-900">${escapeHtml(room.category_name)}</span>
                    </div>
                    <div class="flex justify-between">
                        <span class="font-medium text-gray-700">Status:</span>
                        <span class="px-2 py-1 text-xs rounded-full ${getStatusClass(room.status)}">${room.status.charAt(0).toUpperCase() + room.status.slice(1)}</span>
                    </div>
                    <div class="flex justify-between">
                        <span class="font-medium text-gray-700">Floor:</span>
                        <span class="text-gray-900">${escapeHtml(room.floor || 'N/A')}</span>
                    </div>
                    <div class="flex justify-between">
                        <span class="font-medium text-gray-700">Description:</span>
                        <span class="text-gray-900 text-right max-w-48">${escapeHtml(room.description || 'No description available')}</span>
                    </div>
                </div>
            `;
            
            modal.classList.remove('hidden');
        }

        function closeModal() {
            document.getElementById('roomModal').classList.add('hidden');
        }

        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        function getStatusClass(status) {
            const classes = {
                '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'
            };
            return classes[status] || 'bg-blue-100 text-blue-700';
        }

        // Close modal when clicking outside
        document.getElementById('roomModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeModal();
            }
        });

        // Close modal with Escape key
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                closeModal();
            }
        });
    </script>
</body>
</html>