<?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'];

$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>
<head>
    <title>Room Status - Sheridan Hotel</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
        
        body {
            font-family: 'Inter', sans-serif;
        }
        
        .gradient-bg {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        .card-hover {
            transition: all 0.3s ease;
        }
        
        .card-hover:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }
        
        .nav-item {
            transition: all 0.2s ease;
            position: relative;
            overflow: hidden;
        }
        
        .nav-item:hover {
            background: linear-gradient(135deg, #f3f4f6, #e5e7eb);
            transform: translateX(5px);
        }
        
        .nav-item.active {
            background: linear-gradient(135deg, #3b82f6, #1d4ed8);
            color: white;
        }
        
        .metric-card {
            background: linear-gradient(135deg, #ffffff, #f8fafc);
            border: 1px solid rgba(255, 255, 255, 0.2);
            backdrop-filter: blur(10px);
        }
        
        .sidebar-gradient {
            background: linear-gradient(180deg, #1e293b 0%, #334155 100%);
        }
        
        .animate-fade-in {
            animation: fadeIn 0.8s ease-in-out;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .pulse-dot {
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0%, 100% { transform: scale(1); opacity: 1; }
            50% { transform: scale(1.1); opacity: 0.8; }
        }
        
        .table-row-hover:hover {
            background-color: #f8fafc;
        }
    </style>
</head>
<body class="bg-gradient-to-br from-gray-50 to-gray-100 min-h-screen">
    <!-- Sidebar -->
    <aside class="fixed left-0 top-0 w-72 h-full sidebar-gradient shadow-2xl z-50">
        <div class="p-8">
            <div class="flex items-center gap-3 mb-2">
                <div class="w-10 h-10 bg-gradient-to-r from-blue-400 to-purple-500 rounded-xl flex items-center justify-center">
                    <i class="fas fa-hotel text-white text-lg"></i>
                </div>
                <h1 class="text-2xl font-bold text-white">Sheridan Hotel</h1>
            </div>
            <div class="flex items-center gap-2 mt-4 p-3 bg-white/10 rounded-lg backdrop-blur-sm">
                <div class="w-2 h-2 bg-green-400 rounded-full pulse-dot"></div>
                <p class="text-white/90 text-sm">Logged in as <span class="font-semibold text-blue-300"><?= htmlspecialchars($admin['role']) ?></span></p>
            </div>
        </div>
        
        <nav class="px-6 space-y-2">
            <a href="dashboard.php" class="nav-item flex items-center gap-3 px-4 py-3 text-white/80 hover:text-white rounded-xl">
                <i class="fas fa-tachometer-alt w-5"></i>
                <span class="font-medium">Dashboard Home</span>
            </a>
            <a href="book_room.php" class="nav-item flex items-center gap-3 px-4 py-3 text-white/80 hover:text-white rounded-xl">
                <i class="fas fa-calendar-plus w-5"></i>
                <span class="font-medium">Book a Room</span>
            </a>
            <a href="room_status.php" class="nav-item active flex items-center gap-3 px-4 py-3 text-white rounded-xl">
                <i class="fas fa-bed w-5"></i>
                <span class="font-medium">Room Status</span>
            </a>
           
            <a href="check_out.php" class="nav-item flex items-center gap-3 px-4 py-3 text-white/80 hover:text-white rounded-xl">
                <i class="fas fa-sign-out-alt w-5"></i>
                <span class="font-medium">Customer Check-out</span>
            </a>
            <!--<a href="list_booked.php" class="nav-item flex items-center gap-3 px-4 py-3 text-white/80 hover:text-white rounded-xl">
                <i class="fas fa-list-alt w-5"></i>
                <span class="font-medium">Booked Rooms</span>
            </a>-->
            
        </nav>
        
        <div class="absolute bottom-0 left-0 right-0 p-6 border-t border-white/10">
            <p class="text-white/60 text-xs mb-3">© Sheridan Hotels and Suites</p>
            <a href="../logout.php" class="flex items-center gap-2 text-red-400 hover:text-red-300 text-sm font-medium transition-colors">
                <i class="fas fa-power-off"></i>
                <span>Logout</span>
            </a>
        </div>
    </aside>

    <!-- Main Content Area -->
    <div class="ml-72 min-h-screen">
        <!-- Top Header -->
        <header class="bg-white/80 backdrop-blur-sm border-b border-gray-200/50 px-8 py-6 sticky top-0 z-40">
            <div class="flex justify-between items-center">
                <div>
                    <h1 class="text-3xl font-bold text-gray-800">Room Status Management</h1>
                    <p class="text-gray-600 mt-1">Monitor and manage room availability</p>
                </div>
                <div class="flex items-center gap-6">
                    <div class="text-right">
                        <p class="text-sm text-gray-500">Welcome back,</p>
                        <p class="font-semibold text-gray-800"><a href="My_profile.php"><?= htmlspecialchars($admin['name']) ?></a></p>
                    </div>
                    <div class="w-12 h-12 bg-gradient-to-r from-blue-500 to-purple-600 rounded-full flex items-center justify-center text-white font-bold text-lg">
                        <?= strtoupper(substr($admin['name'], 0, 1)) ?>
                    </div>
                    <div class="text-sm text-gray-600 font-mono bg-gray-100 px-3 py-2 rounded-lg">
                        <span id="datetime"></span>
                    </div>
                </div>
            </div>
        </header>

        <!-- Dashboard Content -->
        <main class="p-8">
            <?php if (isset($error_message)): ?>
                <div class="mb-6 p-4 bg-red-100 border-l-4 border-red-500 text-red-700 rounded-lg shadow">
                    <?= htmlspecialchars($error_message) ?>
                </div>
            <?php endif; ?>

            <?php if ($debug_mode && !empty($params)): ?>
                <div class="mb-6 p-4 bg-yellow-100 border-l-4 border-yellow-500 text-yellow-700 rounded-lg shadow 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="bg-white rounded-2xl shadow-lg overflow-hidden">
                <div class="gradient-bg p-6 text-white">
                    <h2 class="text-xl font-bold">Room Status Overview</h2>
                    <p class="text-blue-100">Filter and manage room statuses</p>
                </div>
                
                <div class="p-6">
                    <div class="flex justify-between items-center mb-6">
                        <?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-6 rounded-xl mb-6">
                        <form method="GET" class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                                <select name="status" class="w-full 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="w-full 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 items-end gap-2">
                                <button type="submit" class="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 transition-colors h-[42px]">
                                    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 h-[42px]">
                                        Clear
                                    </a>
                                <?php endif; ?>
                            </div>
                        </form>
                    </div>

                    <!-- Results Summary -->
                    <div class="mb-6">
                        <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="w-full bg-white rounded-xl overflow-hidden">
                            <thead class="bg-gray-100">
                                <tr>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider">Room Number</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider">Category</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider">Status</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-700 uppercase tracking-wider">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-200">
                                <?php if (count($rooms) > 0): ?>
                                    <?php foreach ($rooms as $room): ?>
                                        <tr class="table-row-hover">
                                            <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-600">
                                                <?= htmlspecialchars($room['category_name']) ?>
                                            </td>
                                            <td class="px-6 py-4 whitespace-nowrap">
                                                <span class="inline-flex px-3 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 hover:bg-green-600 text-white px-3 py-1 rounded-lg text-sm transition-colors">
                                                        <i class="fas fa-broom mr-1"></i> Cleaned
                                                    </button>
                                                <?php endif; ?>
                                                
                                                <?php if ($room['status'] === 'available'): ?>
                                                    <a href="book_room.php?room_id=<?= $room['id'] ?>" 
                                                       class="bg-blue-500 hover:bg-blue-600 text-white px-3 py-1 rounded-lg text-sm transition-colors inline-block">
                                                        <i class="fas fa-calendar-plus mr-1"></i> Book
                                                    </a>
                                                <?php endif; ?>
                                                
                                                <button onclick="viewRoomDetails(<?= htmlspecialchars(json_encode($room)) ?>)" 
                                                        class="bg-gray-500 hover:bg-gray-600 text-white px-3 py-1 rounded-lg text-sm transition-colors">
                                                    <i class="fas fa-eye mr-1"></i> View
                                                </button>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="4" class="px-6 py-12 text-center text-gray-500">
                                            <i class="fas fa-door-closed text-3xl mb-3 opacity-30"></i>
                                            <div class="text-lg mb-1">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-8 flex justify-center">
                            <nav class="flex items-center space-x-1">
                                <?php if ($page > 1): ?>
                                    <a href="<?= buildPaginationUrl($page - 1, $statusFilter, $categoryFilter) ?>" 
                                       class="px-4 py-2 text-sm border border-gray-300 rounded-l-md bg-white text-gray-500 hover:bg-gray-50">
                                        <i class="fas fa-chevron-left mr-1"></i> 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-4 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-4 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-4 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-4 py-2 text-sm text-gray-500">...</span>
                                    <?php endif; ?>
                                    <a href="<?= buildPaginationUrl($totalPages, $statusFilter, $categoryFilter) ?>" 
                                       class="px-4 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-4 py-2 text-sm border border-gray-300 rounded-r-md bg-white text-gray-500 hover:bg-gray-50">
                                        Next <i class="fas fa-chevron-right ml-1"></i>
                                    </a>
                                <?php endif; ?>
                            </nav>
                        </div>
                    <?php endif; ?>
                </div>
            </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-xl shadow-xl w-96 max-w-full mx-4 relative animate-fade-in">
            <button onclick="closeModal()" class="absolute top-4 right-4 text-gray-400 hover:text-gray-600 text-xl">
                <i class="fas fa-times"></i>
            </button>
            <div class="gradient-bg p-4 rounded-t-xl -m-6 mb-4">
                <h3 class="text-xl font-bold text-white">Room Details</h3>
            </div>
            <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-lg hover:bg-gray-600 transition-colors">
                    Close
                </button>
            </div>
        </div>
    </div>

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

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

            // Show loading state
            const button = event.target;
            const originalText = button.innerHTML;
            button.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i> 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.innerHTML = originalText;
                    button.disabled = false;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred. Please try again.');
                button.innerHTML = 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>