<!DOCTYPE html>
<html dir="ltr" lang="en-US">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="author" content="zytheme">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="description" content="Online Reservation Tables - Granny Restaurant">
    <link href="../assets/images/favicon/favicon.png" rel="icon">

    <!-- Fonts -->
    <link href="https://fonts.googleapis.com/css?family=Raleway:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet" type="text/css">

    <!-- Font Awesome Icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <!-- Bootstrap CSS -->
    <link href="../assets/css/bootstrap.min.css" rel="stylesheet">

    <!-- SweetAlert2 CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">

    <title>Online Reservation Tables - Granny Restaurant</title>

    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Raleway', sans-serif;
            background: #f5f5f5;
            color: #333;
        }

        /* Sidebar */
        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            width: 280px;
            height: 100vh;
            background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            color: white;
            padding: 0;
            z-index: 1000;
            overflow-y: auto;
            box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
        }

        .sidebar-header {
            padding: 30px 20px;
            background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
            text-align: center;
            border-bottom: 3px solid #d4a574;
        }

        .sidebar-logo {
            font-size: 40px;
            margin-bottom: 10px;
            display: block;
        }

        .sidebar-header h2 {
            font-size: 20px;
            margin: 10px 0 5px 0;
            font-weight: 700;
        }

        .sidebar-header p {
            font-size: 12px;
            opacity: 0.9;
            margin: 0;
        }

        .sidebar-menu {
            list-style: none;
            padding: 20px 0;
        }

        .sidebar-menu li {
            margin: 0;
        }

        .sidebar-menu a {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 15px 25px;
            color: white;
            text-decoration: none;
            transition: all 0.3s ease;
            border-left: 4px solid transparent;
        }

        .sidebar-menu a:hover {
            background: rgba(255, 255, 255, 0.1);
            border-left-color: #d4a574;
        }

        .sidebar-menu a.active {
            background: rgba(212, 165, 116, 0.2);
            border-left-color: #d4a574;
            color: #d4a574;
        }

        /* Topbar */
        .topbar {
            position: fixed;
            top: 0;
            left: 280px;
            right: 0;
            height: 70px;
            background: white;
            border-bottom: 1px solid #e8e8e8;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 30px;
            z-index: 999;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        }

        .topbar-title {
            font-size: 24px;
            font-weight: 700;
            color: #2c3e50;
        }

        .topbar-right {
            display: flex;
            align-items: center;
            gap: 30px;
        }

        .topbar-user {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .user-avatar {
            width: 50px;
            height: 50px;
            background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            font-weight: 700;
            font-size: 18px;
        }

        .user-info p {
            font-size: 12px;
            color: #999;
            margin: 0;
        }

        .user-info strong {
            display: block;
            font-size: 14px;
            color: #2c3e50;
        }

        .menu-toggle {
            display: none;
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #2c3e50;
        }

        /* Main Content */
        .main-content {
            margin-left: 280px;
            padding: 30px;
            padding-top: 100px;
            min-height: 100vh;
        }

        .header h1 {
            font-size: 28px;
            font-weight: 600;
            margin: 0;
            color: #2c3e50;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .header-actions {
            display: flex;
            gap: 10px;
        }

        .btn {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            font-size: 13px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
        }

        .btn-primary {
            background: #d4a574;
            color: white;
        }

        .btn-primary:hover {
            background: #c1944a;
            color: white;
        }

        .btn-secondary {
            background: #eceff1;
            color: #2c3e50;
        }

        .btn-secondary:hover {
            background: #cfd8dc;
        }

        .btn-danger {
            background: #e74c3c;
            color: white;
        }

        .btn-danger:hover {
            background: #c0392b;
        }

        .btn-sm {
            padding: 6px 12px;
            font-size: 12px;
        }

        /* Filters */
        .filters {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            flex-wrap: wrap;
        }

        .filter-group {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .filter-group label {
            font-size: 12px;
            font-weight: 600;
            color: #555;
        }

        .filter-group input,
        .filter-group select {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            font-family: 'Raleway', sans-serif;
            min-width: 150px;
        }

        /* Table Grid */
        .table-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .table-card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            transition: all 0.3s ease;
            border-top: 4px solid #d4a574;
        }

        .table-card:hover {
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
            transform: translateY(-4px);
        }

        .table-card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }

        .table-number {
            font-size: 24px;
            font-weight: 700;
            color: #2c3e50;
        }

        .status-badge {
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
        }

        .status-available {
            background: #d4edda;
            color: #155724;
        }

        .status-booked {
            background: #fff3cd;
            color: #856404;
        }

        .status-maintenance {
            background: #f8d7da;
            color: #721c24;
        }

        .status-reserved {
            background: #d1ecf1;
            color: #0c5460;
        }

        .table-info {
            display: flex;
            flex-direction: column;
            gap: 10px;
            margin-bottom: 15px;
        }

        .info-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 13px;
        }

        .info-label {
            color: #666;
            font-weight: 500;
        }

        .info-value {
            color: #2c3e50;
            font-weight: 600;
        }

        .capacity-indicator {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .chair-icon {
            width: 30px;
            height: 30px;
            background: #d4a574;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 600;
            font-size: 14px;
        }

        .table-card-actions {
            display: flex;
            gap: 8px;
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px solid #eee;
        }

        .table-card-actions .btn {
            flex: 1;
            justify-content: center;
            font-size: 12px;
            padding: 8px 10px;
        }

        /* Modal */
        .modal {
            display: none;
            position: fixed;
            z-index: 2000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            animation: fadeIn 0.3s ease;
        }

        .modal.show {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        .modal-content {
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
            max-width: 500px;
            width: 90%;
            max-height: 90vh;
            overflow-y: auto;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }

        .modal-header h2 {
            font-size: 20px;
            margin: 0;
            color: #2c3e50;
        }

        .modal-close {
            background: none;
            border: none;
            font-size: 28px;
            cursor: pointer;
            color: #999;
            padding: 0;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .modal-close:hover {
            color: #2c3e50;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            font-size: 13px;
            font-weight: 600;
            margin-bottom: 5px;
            color: #2c3e50;
        }

        .form-group input,
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            font-family: 'Raleway', sans-serif;
        }

        .form-group textarea {
            resize: vertical;
            min-height: 80px;
        }

        .modal-actions {
            display: flex;
            gap: 10px;
            margin-top: 25px;
            padding-top: 15px;
            border-top: 1px solid #eee;
        }

        .modal-actions .btn {
            flex: 1;
            justify-content: center;
        }

        /* Statistics */
        .stats-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            border-left: 4px solid #d4a574;
        }

        .stat-value {
            font-size: 32px;
            font-weight: 700;
            color: #d4a574;
            margin-bottom: 5px;
        }

        .stat-label {
            font-size: 13px;
            color: #666;
            text-transform: uppercase;
            font-weight: 600;
        }

        .loading {
            display: none;
            text-align: center;
            padding: 40px;
            color: #999;
        }

        .loading.show {
            display: block;
        }

        .spinner {
            display: inline-block;
            width: 30px;
            height: 30px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #d4a574;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .sidebar-footer {
            padding: 20px;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
        }

        .logout-btn {
            width: 100%;
            padding: 10px;
            background: #e74c3c;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 13px;
            font-weight: 600;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            transition: all 0.3s ease;
        }

        .logout-btn:hover {
            background: #c0392b;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .sidebar {
                position: fixed;
                left: 0;
                top: 0;
                width: 280px;
                height: 100vh;
                transform: translateX(-100%);
                transition: transform 0.3s ease;
                z-index: 1000;
            }

            .sidebar.mobile-open {
                transform: translateX(0);
            }

            .topbar {
                left: 0;
            }

            .main-content {
                margin-left: 0;
                padding: 15px;
                padding-top: 100px;
            }

            .menu-toggle {
                display: block;
            }

            .table-grid {
                grid-template-columns: 1fr;
            }

            .header {
                flex-direction: column;
                gap: 15px;
            }

            .header-actions {
                width: 100%;
            }

            .header-actions .btn {
                flex: 1;
            }

            .filters {
                flex-direction: column;
            }

            .filter-group input,
            .filter-group select {
                min-width: 100%;
            }
        }

        @media (max-width: 1024px) {
            .sidebar {
                width: 250px;
            }

            .topbar {
                left: 250px;
            }

            .main-content {
                margin-left: 250px;
            }
        }
    </style>
</head>

<body>
    <!-- Sidebar -->
    <div class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <span class="sidebar-logo"><i class="fas fa-chair"></i></span>
            <h2>Restaurant</h2>
            <p>Admin Panel</p>
        </div>

        <ul class="sidebar-menu" id="sidebarMenu">
            <li><a href="dashboard.php"><i class="fas fa-chart-line"></i> Dashboard</a></li>
            <li><a href="tables.php"><i class="fas fa-chair"></i> Dine-in Tables</a></li>
            <li><a href="online_tables.php" class="active"><i class="fas fa-laptop"></i> Online Tables</a></li>
            <li><a href="bookings.php"><i class="fas fa-calendar-alt"></i> Bookings</a></li>
            <li><a href="orders.php"><i class="fas fa-shopping-cart"></i> Orders</a></li>
            <li><a href="menu.php"><i class="fas fa-utensils"></i> Menu</a></li>
            <li><a href="users.php"><i class="fas fa-users"></i> Users</a></li>
            <li><a href="feedback.php"><i class="fas fa-comments"></i> Feedback</a></li>
            <li><a href="contacts.php"><i class="fas fa-envelope"></i> Contacts</a></li>
            <li><a href="settings.php"><i class="fas fa-cog"></i> Settings</a></li>
        </ul>

        <div class="sidebar-footer">
            <button class="logout-btn" id="logoutBtn">
                <i class="fas fa-sign-out-alt"></i> Logout
            </button>
        </div>
    </div>

    <!-- Hamburger Menu Button -->
    <button class="menu-toggle" id="menuToggle">
        <i class="fas fa-bars"></i>
    </button>

    <!-- Topbar -->
    <div class="topbar">
        <div style="display: flex; align-items: center; gap: 20px;">
            <button class="menu-toggle" id="menuToggleTop">
                <i class="fas fa-bars"></i>
            </button>
            <div class="topbar-title">Online Reservation Tables</div>
        </div>

        <div class="topbar-right">
            <div class="topbar-user">
                <div class="user-avatar" id="userInitial">A</div>
                <div class="user-info">
                    <p>Welcome back</p>
                    <strong id="topbarUserName">Admin</strong>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
        <!-- Header -->
        <div class="header">
            <div>
                <h1><i class="fas fa-laptop"></i> Online Reservation Tables</h1>
                <p style="margin: 5px 0 0 0; color: #999; font-size: 13px;">Manage tables available for online reservations and customer allocations</p>
            </div>
            <div class="header-actions">
                <button class="btn btn-primary" onclick="openCreateModal()">
                    <i class="fas fa-plus"></i> Create Table
                </button>
            </div>
        </div>

        <!-- Statistics -->
        <div class="stats-container">
            <div class="stat-card">
                <div class="stat-value" id="totalTables">0</div>
                <div class="stat-label">Total Tables</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="availableTables">0</div>
                <div class="stat-label">Available Tables</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="bookedTables">0</div>
                <div class="stat-label">Booked Tables</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="totalCapacity">0</div>
                <div class="stat-label">Total Capacity</div>
            </div>
        </div>

        <!-- Filters -->
        <div class="filters">
            <div class="filter-group">
                <label for="filterDate"><i class="fas fa-calendar-alt"></i> Select Date</label>
                <input type="date" id="filterDate" onchange="loadTables()">
            </div>
            <div class="filter-group">
                <label for="filterFloor">Floor Level</label>
                <select id="filterFloor" onchange="loadTables()">
                    <option value="">All Floors</option>
                    <option value="1">Floor 1</option>
                    <option value="2">Floor 2</option>
                    <option value="3">Floor 3</option>
                </select>
            </div>
            <div class="filter-group">
                <label for="filterSection">Section</label>
                <select id="filterSection" onchange="loadTables()">
                    <option value="">All Sections</option>
                </select>
            </div>
            <div class="filter-group">
                <label for="filterStatus">Status</label>
                <select id="filterStatus" onchange="loadTables()">
                    <option value="">All Status</option>
                    <option value="available">Available</option>
                    <option value="booked">Booked</option>
                    <option value="maintenance">Maintenance</option>
                    <option value="reserved">Reserved</option>
                </select>
            </div>
            <div class="filter-group">
                <label for="filterMealType">Meal Type</label>
                <select id="filterMealType" onchange="onMealTypeFilterChange()">
                    <option value="">All Meal Types</option>
                </select>
            </div>
            <div class="filter-group">
                <label for="filterSlotTime">Slot Timing</label>
                <select id="filterSlotTime" onchange="onSlotFilterChange()" disabled>
                    <option value="">All Slots</option>
                </select>
            </div>
            <div class="filter-group" style="margin-top: auto;">
                <button class="btn btn-secondary" onclick="resetFilters()">
                    <i class="fas fa-redo"></i> Reset Filters
                </button>
            </div>
        </div>

        <!-- Loading -->
        <div class="loading" id="loading">
            <div class="spinner"></div>
            <p>Loading tables...</p>
        </div>

        <!-- Table Grid -->
        <div id="tableGrid" class="table-grid"></div>
    </div>

    <!-- Create/Edit Table Modal -->
    <div id="tableModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modalTitle">Create New Online Table</h2>
                <button class="modal-close" onclick="closeModal()">&times;</button>
            </div>
            <form id="tableForm">
                <div class="form-group">
                    <label for="tableNumber">Table Number <span style="color: #d4a574;">*</span></label>
                    <input type="text" id="tableNumber" placeholder="e.g., OT-01, ON-A01" required>
                </div>
                <div class="form-group">
                    <label for="tableCapacity">Capacity (Guests) <span style="color: #d4a574;">*</span></label>
                    <input type="number" id="tableCapacity" value="4" min="1" max="20" required>
                </div>
                <div class="form-group">
                    <label for="tableFloor">Floor Level <span style="color: #d4a574;">*</span></label>
                    <select id="tableFloor" required>
                        <option value="1">Floor 1</option>
                        <option value="2">Floor 2</option>
                        <option value="3">Floor 3</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="tableSection">Section</label>
                    <input type="text" id="tableSection" placeholder="e.g., Online Reservation Zone, VIP">
                </div>
                <div class="form-group">
                    <label for="tableType">Table Type <span style="color: #d4a574;">*</span></label>
                    <select id="tableType" required>
                        <option value="online">Exclusive Online</option>
                        <option value="shared">Shared with Walk-ins</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="availabilityFrom">Available From <span style="color: #d4a574;">*</span></label>
                    <input type="time" id="availabilityFrom" value="10:00" required>
                </div>
                <div class="form-group">
                    <label for="availabilityTo">Available To <span style="color: #d4a574;">*</span></label>
                    <input type="time" id="availabilityTo" value="22:00" required>
                </div>
                <div class="form-group">
                    <label for="tableNotes">Notes</label>
                    <textarea id="tableNotes" placeholder="Any special notes about this table..."></textarea>
                </div>
                <div class="modal-actions">
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save Table</button>
                </div>
            </form>
        </div>
    </div>

    <!-- View/Edit Table Modal -->
    <div id="viewTableModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="viewModalTitle">Table Details</h2>
                <button class="modal-close" onclick="closeViewModal()">&times;</button>
            </div>
            <div id="viewTableContent"></div>
            <div class="modal-actions">
                <button type="button" class="btn btn-secondary" onclick="closeViewModal()">Close</button>
                <button type="button" class="btn btn-primary" onclick="editCurrentTable()">Edit Table</button>
                <button type="button" class="btn btn-danger" onclick="deleteCurrentTable()">Delete Table</button>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
    <script src="../assets/js/bootstrap.min.js"></script>

    <script>
        let tables = [];
        let currentTableId = null;

        // Initialize
        document.addEventListener('DOMContentLoaded', function() {
            const today = new Date().toISOString().split('T')[0];
            document.getElementById('filterDate').value = today;
            
            loadTables();
            loadSections();
            loadMealTypes();
            document.getElementById('tableForm').addEventListener('submit', saveTable);
            
            initMobileMenu();

            document.querySelectorAll('.sidebar-menu a').forEach(link => {
                link.addEventListener('click', function() {
                    if (window.innerWidth <= 768) {
                        const sidebar = document.querySelector('.sidebar');
                        if (sidebar) {
                            sidebar.classList.remove('mobile-open');
                        }
                    }
                });
            });

            document.addEventListener('click', function(event) {
                const sidebar = document.querySelector('.sidebar');
                const menuToggle = document.getElementById('menuToggle');
                const menuToggleTop = document.getElementById('menuToggleTop');
                if (window.innerWidth <= 768 && sidebar && menuToggle && menuToggleTop && 
                    !sidebar.contains(event.target) && !menuToggle.contains(event.target) && !menuToggleTop.contains(event.target)) {
                    sidebar.classList.remove('mobile-open');
                }
            });
        });

        function toggleMobileSidebar() {
            const sidebar = document.querySelector('.sidebar');
            if (sidebar) {
                sidebar.classList.toggle('mobile-open');
            }
        }

        function initMobileMenu() {
            const menuToggle = document.getElementById('menuToggle');
            const menuToggleTop = document.getElementById('menuToggleTop');

            if (menuToggle) {
                menuToggle.addEventListener('click', toggleMobileSidebar);
            }

            if (menuToggleTop) {
                menuToggleTop.addEventListener('click', toggleMobileSidebar);
            }

            document.getElementById('logoutBtn').addEventListener('click', function() {
                Swal.fire({
                    icon: 'warning',
                    title: 'Confirm Logout',
                    text: 'Are you sure you want to logout?',
                    showCancelButton: true,
                    confirmButtonColor: '#d4a574',
                    cancelButtonColor: '#999',
                    confirmButtonText: 'Yes, Logout',
                    cancelButtonText: 'Cancel'
                }).then((result) => {
                    if (result.isConfirmed) {
                        localStorage.removeItem('admin_user');
                        localStorage.removeItem('admin_token');
                        
                        fetch('../backend/admin_logout.php', {
                            method: 'POST'
                        }).then(() => {
                            window.location.href = 'login.php';
                        });
                    }
                });
            });

            fetch('../backend/admin_session_check.php')
                .then(response => response.json())
                .then(data => {
                    if (data.authenticated && data.admin) {
                        const admin = data.admin;
                        const initial = admin.name?.charAt(0).toUpperCase() || 'A';
                        document.getElementById('userInitial').textContent = initial;
                        document.getElementById('topbarUserName').textContent = admin.name || 'Admin';
                    }
                })
                .catch(error => console.error('Error loading admin info:', error));
        }

        function loadTables() {
            const floor = document.getElementById('filterFloor').value;
            const section = document.getElementById('filterSection').value;
            const status = document.getElementById('filterStatus').value;
            const dateInput = document.getElementById('filterDate').value;
            const mealType = document.getElementById('filterMealType').value;
            const slotTime = document.getElementById('filterSlotTime').value;

            let url = '../backend/online_tables_api.php?action=list';
            if (floor) url += '&floor=' + floor;
            if (section) url += '&section=' + section;
            if (status) url += '&status=' + status;
            if (mealType) url += '&meal_type=' + encodeURIComponent(mealType);
            if (slotTime) url += '&slot_time=' + encodeURIComponent(slotTime);
            const selectedDate = dateInput || new Date().toISOString().split('T')[0];
            url += '&date=' + selectedDate;

            document.getElementById('loading').classList.add('show');

            fetch(url)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        tables = data.data;
                        displayTables();
                        updateStats();
                    } else {
                        Swal.fire('Error', data.message, 'error');
                    }
                    document.getElementById('loading').classList.remove('show');
                })
                .catch(error => {
                    console.error('Error:', error);
                    Swal.fire('Error', 'Failed to load tables', 'error');
                    document.getElementById('loading').classList.remove('show');
                });
        }

        function displayTables() {
            const gridContainer = document.getElementById('tableGrid');
            gridContainer.innerHTML = '';

            if (tables.length === 0) {
                gridContainer.innerHTML = '<div style="grid-column: 1/-1; text-align: center; padding: 40px; color: #999;">No online tables found. Create one to get started!</div>';
                return;
            }

            tables.forEach(table => {
                const gridCard = createTableCard(table);
                gridContainer.appendChild(gridCard);
            });
        }

        function createTableCard(table) {
            const card = document.createElement('div');
            card.className = 'table-card';
            
            card.innerHTML = `
                <div class="table-card-header">
                    <div class="table-number">${table.table_number}</div>
                    <span class="status-badge status-${table.status}">${table.status.toUpperCase()}</span>
                </div>
                <div class="table-info">
                    <div class="info-row">
                        <span class="info-label">Capacity:</span>
                        <div class="capacity-indicator">
                            <span class="chair-icon">${table.current_capacity}</span>
                            <span class="info-value">${table.current_capacity} Guests</span>
                        </div>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Floor:</span>
                        <span class="info-value">Floor ${table.floor_level}</span>
                    </div>
                    ${table.section ? `
                    <div class="info-row">
                        <span class="info-label">Section:</span>
                        <span class="info-value">${table.section}</span>
                    </div>
                    ` : ''}
                    <div class="info-row">
                        <span class="info-label">Type:</span>
                        <span class="info-value">${table.table_type === 'online' ? 'Exclusive Online' : 'Shared'}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Available:</span>
                        <span class="info-value">${table.availability_from} - ${table.availability_to}</span>
                    </div>
                </div>
                <div class="table-card-actions">
                    <button class="btn btn-secondary btn-sm" onclick="viewTable(${table.id})">
                        <i class="fas fa-eye"></i> View
                    </button>
                    <button class="btn btn-danger btn-sm" onclick="deleteTable(${table.id})">
                        <i class="fas fa-trash"></i> Delete
                    </button>
                </div>
            `;
            return card;
        }

        function updateStats() {
            let available = 0, booked = 0, totalCapacity = 0;

            tables.forEach(table => {
                if (table.status === 'available') available++;
                if (table.status === 'booked' || table.status === 'reserved') booked++;
                totalCapacity += parseInt(table.current_capacity);
            });

            document.getElementById('totalTables').textContent = tables.length;
            document.getElementById('availableTables').textContent = available;
            document.getElementById('bookedTables').textContent = booked;
            document.getElementById('totalCapacity').textContent = totalCapacity;
        }

        function loadSections() {
            fetch('../backend/online_tables_api.php?action=get_sections')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const select = document.getElementById('filterSection');
                        data.data.forEach(section => {
                            const option = document.createElement('option');
                            option.value = section;
                            option.textContent = section;
                            select.appendChild(option);
                        });
                    }
                });
        }

        function loadMealTypes() {
            fetch('../backend/meal_slots_api.php?action=get_meal_types')
                .then(response => response.json())
                .then(data => {
                    const mealTypeSelect = document.getElementById('filterMealType');
                    mealTypeSelect.innerHTML = '<option value="">All Meal Types</option>';

                    if (data.success && Array.isArray(data.data)) {
                        data.data
                            .filter(mealType => mealType.status === 'active')
                            .forEach(mealType => {
                                const option = document.createElement('option');
                                option.value = mealType.name;
                                option.textContent = mealType.name;
                                option.dataset.mealTypeId = mealType.id;
                                mealTypeSelect.appendChild(option);
                            });
                    }
                })
                .catch(error => console.error('Error loading meal types:', error));
        }

        function onMealTypeFilterChange() {
            const mealTypeSelect = document.getElementById('filterMealType');
            const slotSelect = document.getElementById('filterSlotTime');
            const selectedOption = mealTypeSelect.options[mealTypeSelect.selectedIndex];
            const mealTypeId = selectedOption ? selectedOption.dataset.mealTypeId : '';

            slotSelect.innerHTML = '<option value="">All Slots</option>';
            slotSelect.disabled = !mealTypeId;

            if (!mealTypeId) {
                loadTables();
                return;
            }

            fetch(`../backend/meal_slots_api.php?action=get_slots&meal_type_id=${encodeURIComponent(mealTypeId)}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success && Array.isArray(data.data)) {
                        data.data
                            .filter(slot => slot.status === 'active')
                            .forEach(slot => {
                                const option = document.createElement('option');
                                option.value = slot.start_time;
                                option.textContent = slot.slot_name || `${slot.start_time} - ${slot.end_time}`;
                                slotSelect.appendChild(option);
                            });
                    }
                    loadTables();
                })
                .catch(error => {
                    console.error('Error loading slots:', error);
                    loadTables();
                });
        }

        function onSlotFilterChange() {
            const slotTime = document.getElementById('filterSlotTime').value;
            const statusSelect = document.getElementById('filterStatus');

            // When slot is selected, default to booked view for quick audit
            if (slotTime && !statusSelect.value) {
                statusSelect.value = 'booked';
            }

            loadTables();
        }

        function saveTable(e) {
            e.preventDefault();

            const data = {
                table_number: document.getElementById('tableNumber').value,
                capacity: parseInt(document.getElementById('tableCapacity').value),
                floor_level: parseInt(document.getElementById('tableFloor').value),
                section: document.getElementById('tableSection').value,
                table_type: document.getElementById('tableType').value,
                availability_from: document.getElementById('availabilityFrom').value,
                availability_to: document.getElementById('availabilityTo').value,
                notes: document.getElementById('tableNotes').value
            };

            const endpoint = currentTableId ? '../backend/online_tables_api.php?action=update' : '../backend/online_tables_api.php?action=create';
            
            if (currentTableId) {
                data.id = currentTableId;
            }

            fetch(endpoint, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    Swal.fire('Success', currentTableId ? 'Table updated successfully!' : 'Table created successfully!', 'success');
                    closeModal();
                    loadTables();
                } else {
                    Swal.fire('Error', result.message, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                Swal.fire('Error', 'Failed to save table', 'error');
            });
        }

        function viewTable(id) {
            const tableId = parseInt(id);
            const table = tables.find(t => parseInt(t.id) === tableId);
            
            if (!table) {
                Swal.fire('Error', 'Table not found', 'error');
                return;
            }

            currentTableId = id;
            document.getElementById('viewModalTitle').textContent = `Table ${table.table_number}`;
            
            let content = `
                <div class="table-info">
                    <div class="info-row">
                        <span class="info-label">Table Number:</span>
                        <span class="info-value">${table.table_number}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Capacity:</span>
                        <span class="info-value">${table.current_capacity} Guests</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Floor Level:</span>
                        <span class="info-value">Floor ${table.floor_level}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Section:</span>
                        <span class="info-value">${table.section || 'Not assigned'}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Table Type:</span>
                        <span class="info-value">${table.table_type === 'online' ? 'Exclusive Online' : 'Shared with Walk-ins'}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Available Hours:</span>
                        <span class="info-value">${table.availability_from} - ${table.availability_to}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Status:</span>
                        <span class="status-badge status-${table.status}" style="margin-left: auto;">${table.status.toUpperCase()}</span>
                    </div>
                    ${table.notes ? `
                    <div class="info-row">
                        <span class="info-label">Notes:</span>
                        <span class="info-value">${table.notes}</span>
                    </div>
                    ` : ''}
                    <div class="info-row">
                        <span class="info-label">Created:</span>
                        <span class="info-value">${new Date(table.created_at).toLocaleDateString()}</span>
                    </div>
                </div>
            `;

            document.getElementById('viewTableContent').innerHTML = content;
            document.getElementById('viewTableModal').classList.add('show');
        }

        function closeViewModal() {
            document.getElementById('viewTableModal').classList.remove('show');
        }

        function editCurrentTable() {
            const tableId = parseInt(currentTableId);
            const table = tables.find(t => parseInt(t.id) === tableId);
            if (!table) return;

            document.getElementById('modalTitle').textContent = `Edit Table ${table.table_number}`;
            document.getElementById('tableNumber').value = table.table_number;
            document.getElementById('tableCapacity').value = table.current_capacity;
            document.getElementById('tableFloor').value = table.floor_level;
            document.getElementById('tableSection').value = table.section || '';
            document.getElementById('tableType').value = table.table_type || 'online';
            document.getElementById('availabilityFrom').value = table.availability_from || '10:00';
            document.getElementById('availabilityTo').value = table.availability_to || '22:00';
            document.getElementById('tableNotes').value = table.notes || '';

            document.getElementById('viewTableModal').classList.remove('show');
            document.getElementById('tableModal').classList.add('show');
            currentTableId = table.id;
        }

        function deleteTable(id) {
            Swal.fire({
                title: 'Delete Table?',
                text: 'This action cannot be undone!',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d4a574',
                cancelButtonColor: '#999',
                confirmButtonText: 'Yes, delete it!'
            }).then((result) => {
                if (result.isConfirmed) {
                    fetch('../backend/online_tables_api.php?action=delete', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ id: id })
                    })
                    .then(response => response.json())
                    .then(result => {
                        if (result.success) {
                            Swal.fire('Deleted!', 'Table deleted successfully!', 'success');
                            loadTables();
                        } else {
                            Swal.fire('Error', result.message, 'error');
                        }
                    });
                }
            });
        }

        function deleteCurrentTable() {
            if (currentTableId) {
                deleteTable(currentTableId);
                closeViewModal();
            }
        }

        function openCreateModal() {
            currentTableId = null;
            document.getElementById('modalTitle').textContent = 'Create New Online Table';
            document.getElementById('tableForm').reset();
            document.getElementById('tableCapacity').value = 4;
            document.getElementById('tableFloor').value = 1;
            document.getElementById('availabilityFrom').value = '10:00';
            document.getElementById('availabilityTo').value = '22:00';
            document.getElementById('tableType').value = 'online';
            document.getElementById('tableModal').classList.add('show');
        }

        function closeModal() {
            document.getElementById('tableModal').classList.remove('show');
            currentTableId = null;
            const sidebar = document.querySelector('.sidebar');
            if (sidebar) {
                sidebar.classList.remove('mobile-open');
            }
        }

        function resetFilters() {
            const today = new Date().toISOString().split('T')[0];
            document.getElementById('filterDate').value = today;
            document.getElementById('filterFloor').value = '';
            document.getElementById('filterSection').value = '';
            document.getElementById('filterStatus').value = '';
            document.getElementById('filterMealType').value = '';
            const slotSelect = document.getElementById('filterSlotTime');
            slotSelect.innerHTML = '<option value="">All Slots</option>';
            slotSelect.disabled = true;
            loadTables();
        }

        window.onclick = function(event) {
            const modal = event.target;
            if (modal.classList.contains('modal')) {
                modal.classList.remove('show');
            }
        }
    </script>
</body>

</html>
