<!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="Granny Restaurant">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="description" content="Online Tables - Granny Restaurant Manager">
    <link href="../assets/images/favicon/favicon.png" rel="icon">

    <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">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <link rel="stylesheet" href="manager-styles.css">

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

    <style>
        .main-content {
            padding: 30px;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 0;
        }

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

        .page-header h1 {
            color: #1e3c72;
            font-size: 28px;
        }

        .page-subtext {
            color: #666;
            font-size: 14px;
            margin-top: 6px;
        }

        .stats {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 15px;
            margin-bottom: 25px;
        }

        .stat-card {
            background: white;
            padding: 18px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .stat-title {
            font-size: 12px;
            color: #666;
            text-transform: uppercase;
            margin-bottom: 8px;
            font-weight: 600;
        }

        .stat-value {
            font-size: 28px;
            font-weight: 700;
            color: #1e3c72;
        }

        .controls {
            background: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 25px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            align-items: end;
        }

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

        .control-group label {
            font-size: 12px;
            color: #666;
            font-weight: 600;
            text-transform: uppercase;
        }

        .control-group input,
        .control-group select {
            padding: 10px 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-family: inherit;
            min-width: 170px;
        }

        .btn {
            padding: 10px 15px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            font-size: 13px;
            transition: all 0.3s ease;
        }

        .btn-primary {
            color: white;
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 10px rgba(30, 60, 114, 0.25);
        }

        .tables-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 15px;
        }

        .table-card {
            background: white;
            border-radius: 10px;
            padding: 18px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            border-left: 5px solid #28a745;
        }

        .table-card.booked {
            border-left-color: #ffc107;
        }

        .table-card.maintenance {
            border-left-color: #dc3545;
        }

        .table-card.occupied {
            border-left-color: #0d6efd;
        }

        .table-number {
            font-size: 24px;
            font-weight: 700;
            color: #1e3c72;
            margin-bottom: 8px;
        }

        .status-badge {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 700;
            margin-bottom: 12px;
            text-transform: uppercase;
        }

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

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

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

        .status-occupied {
            background: #cfe2ff;
            color: #084298;
        }

        .table-meta {
            color: #555;
            font-size: 13px;
            margin-bottom: 6px;
        }

        .table-meta strong {
            color: #333;
        }

        .table-actions {
            display: flex;
            gap: 8px;
            margin-top: 12px;
            flex-wrap: wrap;
        }

        .table-actions button {
            flex: 1;
            padding: 8px 10px;
            border: 1px solid #ddd;
            background: white;
            border-radius: 6px;
            font-size: 12px;
            cursor: pointer;
            transition: all 0.2s ease;
            font-weight: 600;
        }

        .table-actions .btn-assign-server {
            color: #0c5460;
            border-color: #0c5460;
        }

        .table-actions .btn-assign-server:hover {
            background: #d1ecf1;
        }

        .table-actions .btn-release {
            color: #dc3545;
            border-color: #dc3545;
        }

        .table-actions .btn-release:hover {
            background: #f8d7da;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 2000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
        }

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

        .modal-content {
            background: white;
            padding: 24px;
            border-radius: 10px;
            width: 100%;
            max-width: 460px;
        }

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

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

        .modal-header .close {
            border: none;
            background: none;
            font-size: 24px;
            color: #777;
            cursor: pointer;
        }

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

        .form-group label {
            display: block;
            margin-bottom: 6px;
            font-weight: 600;
            color: #333;
            font-size: 14px;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-family: inherit;
        }

        .modal-actions {
            display: flex;
            gap: 8px;
            justify-content: flex-end;
            margin-top: 18px;
        }

        .modal-actions button {
            padding: 10px 16px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
        }

        .close-modal {
            background: #6c757d;
            color: white;
        }

        .confirm-action {
            background: #28a745;
            color: white;
        }

        .empty-state {
            grid-column: 1 / -1;
            text-align: center;
            background: white;
            padding: 45px 20px;
            border-radius: 10px;
            color: #999;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .empty-state i {
            font-size: 40px;
            margin-bottom: 10px;
            opacity: 0.5;
        }

        @media (max-width: 1200px) {
            .tables-grid {
                grid-template-columns: repeat(3, 1fr);
            }

            .stats {
                grid-template-columns: repeat(2, 1fr);
            }
        }

        @media (max-width: 900px) {
            .tables-grid {
                grid-template-columns: repeat(2, 1fr);
            }
        }

        @media (max-width: 768px) {
            .main-content {
                padding: 15px;
            }

            .page-header {
                padding: 15px;
            }

            .page-header h1 {
                font-size: 20px;
            }

            .controls {
                padding: 15px;
            }

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

            .tables-grid,
            .stats {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>

<body>
    <div class="dashboard-container">
        <?php include 'sidebar.php'; ?>

        <div class="main-content">
            <div class="container">
                <div class="page-header">
                    <div>
                        <h1><i class="fas fa-laptop"></i> Online Reservation Tables</h1>
                        <p class="page-subtext">Shows tables configured for online reservations.</p>
                    </div>
                </div>

                <div class="stats">
                    <div class="stat-card">
                        <div class="stat-title">Total</div>
                        <div class="stat-value" id="totalTables">0</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-title">Available</div>
                        <div class="stat-value" id="availableTables">0</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-title">Booked</div>
                        <div class="stat-value" id="bookedTables">0</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-title">Maintenance</div>
                        <div class="stat-value" id="maintenanceTables">0</div>
                    </div>
                </div>

                <div class="controls">
                    <div class="control-group">
                        <label for="filterDate">Date</label>
                        <input type="date" id="filterDate">
                    </div>

                    <div class="control-group">
                        <label for="filterFloor">Floor</label>
                        <select id="filterFloor">
                            <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="control-group">
                        <label for="filterSection">Section</label>
                        <select id="filterSection">
                            <option value="">All Sections</option>
                        </select>
                    </div>

                    <div class="control-group">
                        <label for="filterStatus">Status</label>
                        <select id="filterStatus">
                            <option value="">All Status</option>
                            <option value="available">Available</option>
                            <option value="booked">Booked</option>
                            <option value="occupied">Occupied</option>
                            <option value="maintenance">Maintenance</option>
                        </select>
                    </div>

                    <div class="control-group">
                        <label for="filterMealType">Meal Type</label>
                        <select id="filterMealType">
                            <option value="">All Meal Types</option>
                        </select>
                    </div>

                    <div class="control-group">
                        <label for="filterSlotTime">Slot Timing</label>
                        <select id="filterSlotTime" disabled>
                            <option value="">All Slots</option>
                        </select>
                    </div>

                    <button class="btn" id="resetFiltersBtn" type="button">
                        <i class="fas fa-undo"></i> Reset Filters
                    </button>

                    <button class="btn btn-primary" id="refreshBtn">
                        <i class="fas fa-sync"></i> Refresh
                    </button>
                </div>

                <div class="tables-grid" id="tablesGrid">
                    <div class="empty-state">
                        <i class="fas fa-spinner fa-spin"></i>
                        <p>Loading online tables...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="modal" id="onlineServerModal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Assign Server to Online Table</h2>
                <button class="close" onclick="closeModal('onlineServerModal')">&times;</button>
            </div>
            <form id="onlineServerForm">
                <div class="form-group">
                    <label>Table</label>
                    <input type="text" id="onlineServerTableDisplay" readonly disabled>
                    <input type="hidden" id="onlineServerTableId">
                    <input type="hidden" id="onlineServerBookingId">
                    <input type="hidden" id="onlineServerTableIds">
                </div>
                <div class="form-group">
                    <label>Select Server</label>
                    <select id="onlineServerSelect" required>
                        <option value="">Select a server</option>
                    </select>
                </div>
                <div class="modal-actions">
                    <button type="button" class="close-modal" onclick="closeModal('onlineServerModal')">Cancel</button>
                    <button type="submit" class="confirm-action">Assign Server</button>
                </div>
            </form>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        let allTables = [];
        let mealTypes = [];

        $(document).ready(function() {
            checkAuthentication();
            setDefaultDate();

            $('#filterDate, #filterFloor, #filterSection, #filterStatus, #filterSlotTime').on('change', loadOnlineTables);
            $('#filterMealType').on('change', handleMealTypeChange);
            $('#refreshBtn').on('click', loadOnlineTables);
            $('#resetFiltersBtn').on('click', resetFilters);
            $('#onlineServerForm').on('submit', submitOnlineServerAssign);

            loadMealTypes().always(function() {
                loadServers();
                loadOnlineTables();
            });
        });

        function checkAuthentication() {
            if (!localStorage.getItem('manager_id')) {
                window.location.href = 'login.php';
            }
        }

        function setDefaultDate() {
            const today = new Date().toISOString().split('T')[0];
            $('#filterDate').val(today);
        }

        function resetFilters() {
            setDefaultDate();
            $('#filterFloor').val('');
            $('#filterSection').val('');
            $('#filterStatus').val('');
            $('#filterMealType').val('');
            setSlotOptions([], null, true);
            loadOnlineTables();
        }

        function loadMealTypes() {
            return $.ajax({
                url: '../backend/meal_slots_api.php',
                method: 'GET',
                dataType: 'json',
                data: {
                    action: 'get_meal_types'
                },
                success: function(response) {
                    if (!response.success) {
                        throw new Error(response.message || 'Failed to load meal types');
                    }

                    mealTypes = (response.data || []).filter(mt => (mt.status || '').toLowerCase() === 'active');

                    let options = '<option value="">All Meal Types</option>';
                    mealTypes.forEach(mealType => {
                        options += `<option value="${escapeHtml(String(mealType.id))}" data-name="${escapeHtml(mealType.name || '')}">${escapeHtml(mealType.name || '')}</option>`;
                    });

                    $('#filterMealType').html(options);
                },
                error: function() {
                    mealTypes = [];
                    $('#filterMealType').html('<option value="">All Meal Types</option>');
                    setSlotOptions([], null, true);
                }
            });
        }

        function handleMealTypeChange() {
            const mealTypeId = $('#filterMealType').val();

            if (!mealTypeId) {
                setSlotOptions([], null, true);
                loadOnlineTables();
                return;
            }

            loadSlotsByMealType(mealTypeId, function() {
                loadOnlineTables();
            });
        }

        function loadSlotsByMealType(mealTypeId, onComplete) {
            const currentSlot = $('#filterSlotTime').val();

            $.ajax({
                url: '../backend/meal_slots_api.php',
                method: 'GET',
                dataType: 'json',
                data: {
                    action: 'get_slots',
                    meal_type_id: mealTypeId
                },
                success: function(response) {
                    if (!response.success) {
                        throw new Error(response.message || 'Failed to load slots');
                    }

                    setSlotOptions(response.data || [], currentSlot, false);
                    if (typeof onComplete === 'function') onComplete();
                },
                error: function() {
                    setSlotOptions([], null, true);
                    if (typeof onComplete === 'function') onComplete();
                }
            });
        }

        function setSlotOptions(slots, selectedValue, disable) {
            let options = '<option value="">All Slots</option>';
            (slots || []).forEach(slot => {
                const startTime = (slot.start_time || '').toString().substring(0, 8);
                if (!startTime) return;
                const label = slot.slot_name || `${startTime.substring(0, 5)} - ${(slot.end_time || '').toString().substring(0, 5)}`;
                options += `<option value="${escapeHtml(startTime)}">${escapeHtml(label)}</option>`;
            });

            $('#filterSlotTime').html(options);
            if (selectedValue && $('#filterSlotTime option[value="' + selectedValue + '"]').length) {
                $('#filterSlotTime').val(selectedValue);
            }

            $('#filterSlotTime').prop('disabled', !!disable);
        }

        function loadOnlineTables() {
            const params = new URLSearchParams();
            params.append('action', 'list');

            const date = $('#filterDate').val();
            const floor = $('#filterFloor').val();
            const section = $('#filterSection').val();
            const status = $('#filterStatus').val();
            const selectedMealOption = $('#filterMealType option:selected');
            const mealType = (selectedMealOption.data('name') || '').toString().trim();
            const slotTime = $('#filterSlotTime').val();

            if (date) params.append('date', date);
            if (floor) params.append('floor', floor);
            if (section) params.append('section', section);
            if (status) params.append('status', status);
            if (mealType) params.append('meal_type', mealType);
            if (slotTime) params.append('slot_time', slotTime);

            $('#tablesGrid').html(`
                <div class="empty-state">
                    <i class="fas fa-spinner fa-spin"></i>
                    <p>Loading online tables...</p>
                </div>
            `);

            $.ajax({
                url: `../backend/online_tables_api.php?${params.toString()}`,
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (!response.success) {
                        throw new Error(response.message || 'Failed to load online tables');
                    }

                    allTables = response.data || [];
                    updateSectionFilter(allTables);
                    renderTables(allTables);
                    updateStats(allTables);
                },
                error: function() {
                    $('#tablesGrid').html(`
                        <div class="empty-state">
                            <i class="fas fa-exclamation-circle"></i>
                            <p>Unable to load online reservation tables.</p>
                        </div>
                    `);
                    Swal.fire('Error', 'Failed to load online tables', 'error');
                }
            });
        }

        function loadServers() {
            $.ajax({
                url: '../backend/manager_tables_api.php?action=get_servers',
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (!response.success) return;

                    let options = '<option value="">Select a server</option>';
                    (response.data || []).forEach(server => {
                        const activeCount = parseInt(server.active_orders_count || 0, 10);
                        const maxCount = parseInt(server.max_active_orders || 1, 10);
                        const label = `${server.name || ''} (${activeCount}/${maxCount})`;
                        options += `<option value="${escapeHtml(String(server.id))}">${escapeHtml(label)}</option>`;
                    });
                    $('#onlineServerSelect').html(options);
                }
            });
        }

        function updateSectionFilter(tables) {
            const current = $('#filterSection').val();
            const sections = [...new Set((tables || [])
                .map(t => (t.section || '').trim())
                .filter(Boolean))]
                .sort((a, b) => a.localeCompare(b));

            let options = '<option value="">All Sections</option>';
            sections.forEach(section => {
                options += `<option value="${escapeHtml(section)}">${escapeHtml(section)}</option>`;
            });

            $('#filterSection').html(options);
            if (current && sections.includes(current)) {
                $('#filterSection').val(current);
            }
        }

        function renderTables(tables) {
            if (!tables || tables.length === 0) {
                $('#tablesGrid').html(`
                    <div class="empty-state">
                        <i class="fas fa-table"></i>
                        <p>No online tables found for selected filters.</p>
                    </div>
                `);
                return;
            }

            let html = '';
            const groupedBookingMap = {};
            const renderedGroupedBookingIds = new Set();
            const standaloneTables = [];

            (tables || []).forEach(table => {
                const status = (table.status || 'available').toLowerCase();
                const bookingId = parseInt(table.active_booking_id || 0, 10);
                const canGroup = bookingId > 0 && (status === 'booked' || status === 'occupied');
                if (canGroup) {
                    if (!groupedBookingMap[bookingId]) {
                        groupedBookingMap[bookingId] = [];
                    }
                    groupedBookingMap[bookingId].push(table);
                } else {
                    standaloneTables.push(table);
                }
            });

            Object.keys(groupedBookingMap).forEach((bookingIdKey) => {
                if (renderedGroupedBookingIds.has(bookingIdKey)) return;
                renderedGroupedBookingIds.add(bookingIdKey);

                const groupTables = groupedBookingMap[bookingIdKey] || [];
                if (groupTables.length === 0) return;

                const first = groupTables[0];
                const status = (first.status || 'booked').toLowerCase();
                const cardClass = ['booked', 'maintenance', 'occupied'].includes(status) ? status : '';
                const fromTime = (first.availability_from || '').toString().substring(0, 5) || '-';
                const toTime = (first.availability_to || '').toString().substring(0, 5) || '-';
                const tableIds = groupTables.map(t => parseInt(t.id, 10)).filter(Number.isFinite);
                const tableNumbers = groupTables.map(t => String(t.table_number || '-'));
                const totalCapacity = groupTables.reduce((sum, t) => sum + (parseInt(t.current_capacity || t.base_capacity || 0, 10) || 0), 0);
                const hasAssignedServer = groupTables.some(t => !!(t.assigned_server_name || '').toString().trim());
                const serverName = groupTables.find(t => !!(t.assigned_server_name || '').toString().trim())?.assigned_server_name || '';
                const bookingId = parseInt(first.active_booking_id || 0, 10);
                const displayLabel = `${tableNumbers.join(', ')}`;
                const tableIdsCsv = tableIds.join(',');

                html += `
                    <div class="table-card ${cardClass}">
                        <div class="table-number">Tables ${escapeHtml(tableNumbers.join(', '))}</div>
                        <div class="status-badge status-${status}">${escapeHtml(status)}</div>
                        <div class="table-meta"><strong>Tables:</strong> ${escapeHtml(tableNumbers.join(', '))}</div>
                        <div class="table-meta"><strong>Total Capacity:</strong> ${escapeHtml(String(totalCapacity))}</div>
                        <div class="table-meta"><strong>Floor:</strong> ${escapeHtml(String(first.floor_level || '-'))}</div>
                        <div class="table-meta"><strong>Section:</strong> ${escapeHtml(first.section || '-')}</div>
                        <div class="table-meta"><strong>Slot Window:</strong> ${escapeHtml(fromTime)} - ${escapeHtml(toTime)}</div>
                        <div class="table-meta"><strong>Type:</strong> ${escapeHtml(first.table_type || 'online')}</div>
                        ${hasAssignedServer ? `<div class="table-meta"><strong>Server:</strong> ${escapeHtml(serverName)}</div>` : ''}
                        <div class="table-actions">
                            <button class="btn-assign-server" type="button" onclick="openOnlineServerModalGroup(${bookingId}, '${escapeHtml(tableIdsCsv)}', '${escapeHtml(displayLabel)}')">
                                <i class="fas fa-user"></i> ${hasAssignedServer ? 'Change Server (Group)' : 'Assign Server (Group)'}
                            </button>
                            <button class="btn-release" type="button" onclick="releaseOnlineBookingGroup(${bookingId}, '${escapeHtml(tableIdsCsv)}')">
                                <i class="fas fa-door-open"></i> Release Group
                            </button>
                        </div>
                    </div>
                `;
            });

            standaloneTables.forEach(table => {
                const status = (table.status || 'available').toLowerCase();
                const cardClass = ['booked', 'maintenance', 'occupied'].includes(status) ? status : '';
                const fromTime = (table.availability_from || '').toString().substring(0, 5) || '-';
                const toTime = (table.availability_to || '').toString().substring(0, 5) || '-';
                const tableId = parseInt(table.id, 10);
                const tableNumber = (table.table_number || '').toString();
                const canManage = (status === 'booked' || status === 'occupied');
                const hasAssignedServer = !!(table.assigned_server_name || '').toString().trim();
                const serverInfo = hasAssignedServer ? `
                    <div class="table-meta"><strong>Server:</strong> ${escapeHtml(table.assigned_server_name)}</div>
                ` : '';
                const actions = canManage ? `
                    <div class="table-actions">
                        <button class="btn-assign-server" type="button" onclick="openOnlineServerModal(${tableId}, '${escapeHtml(tableNumber)}')">
                            <i class="fas fa-user"></i> ${hasAssignedServer ? 'Change Server' : 'Assign Server'}
                        </button>
                        <button class="btn-release" type="button" onclick="releaseOnlineTable(${tableId})">
                            <i class="fas fa-door-open"></i> Release
                        </button>
                    </div>
                ` : '';

                html += `
                    <div class="table-card ${cardClass}">
                        <div class="table-number">Table ${escapeHtml(table.table_number || '-')}</div>
                        <div class="status-badge status-${status}">${escapeHtml(status)}</div>
                        <div class="table-meta"><strong>Capacity:</strong> ${escapeHtml(String(table.current_capacity || table.base_capacity || '-'))}</div>
                        <div class="table-meta"><strong>Floor:</strong> ${escapeHtml(String(table.floor_level || '-'))}</div>
                        <div class="table-meta"><strong>Section:</strong> ${escapeHtml(table.section || '-')}</div>
                        <div class="table-meta"><strong>Slot Window:</strong> ${escapeHtml(fromTime)} - ${escapeHtml(toTime)}</div>
                        <div class="table-meta"><strong>Type:</strong> ${escapeHtml(table.table_type || 'online')}</div>
                        ${serverInfo}
                        ${actions}
                    </div>
                `;
            });

            $('#tablesGrid').html(html);
        }

        function openOnlineServerModal(tableId, tableNumber) {
            $('#onlineServerTableId').val(tableId);
            $('#onlineServerBookingId').val('');
            $('#onlineServerTableIds').val(String(tableId));
            $('#onlineServerTableDisplay').val(tableNumber);
            $('#onlineServerModal').addClass('show');
        }

        function openOnlineServerModalGroup(bookingId, tableIdsCsv, label) {
            $('#onlineServerTableId').val('');
            $('#onlineServerBookingId').val(bookingId);
            $('#onlineServerTableIds').val(tableIdsCsv || '');
            $('#onlineServerTableDisplay').val(label || '');
            $('#onlineServerModal').addClass('show');
        }

        function closeModal(modalId) {
            $('#' + modalId).removeClass('show');
        }

        async function submitOnlineServerAssign(e) {
            e.preventDefault();

            const tableId = parseInt($('#onlineServerTableId').val(), 10);
            const bookingId = parseInt($('#onlineServerBookingId').val(), 10);
            const tableIdsCsv = ($('#onlineServerTableIds').val() || '').toString();
            const tableIds = tableIdsCsv.split(',').map(v => parseInt(v, 10)).filter(Number.isFinite);
            const serverId = parseInt($('#onlineServerSelect').val(), 10);
            const selectedMealOption = $('#filterMealType option:selected');
            const mealType = (selectedMealOption.data('name') || '').toString().trim();
            const slotTime = ($('#filterSlotTime').val() || '').toString().trim();
            const date = ($('#filterDate').val() || '').toString().trim();

            if ((!tableId && tableIds.length === 0) || !serverId) {
                Swal.fire('Error', 'Select a server to continue', 'error');
                return;
            }

            const targetTableIds = tableIds.length > 0 ? tableIds : [tableId];
            const failures = [];
            let successCount = 0;

            for (const tid of targetTableIds) {
                try {
                    const response = await $.ajax({
                        url: '../backend/online_tables_api.php?action=assign_server',
                        method: 'POST',
                        contentType: 'application/json',
                        dataType: 'json',
                        data: JSON.stringify({
                            table_id: tid,
                            server_id: serverId,
                            date: date,
                            meal_type: mealType,
                            slot_time: slotTime
                        })
                    });
                    if (response && response.success) {
                        successCount++;
                    } else {
                        failures.push(`Table ID ${tid}: ${response?.message || 'Failed'}`);
                    }
                } catch (err) {
                    failures.push(`Table ID ${tid}: Request failed`);
                }
            }

            closeModal('onlineServerModal');
            loadServers();
            loadOnlineTables();

            if (failures.length === 0) {
                const msg = 'Server assigned successfully';
                Swal.fire('Success', msg, 'success');
            } else {
                Swal.fire('Warning', `Assigned ${successCount}/${targetTableIds.length}. ${failures.join(' | ')}`, 'warning');
            }
        }

        function releaseOnlineTable(tableId) {
            const selectedMealOption = $('#filterMealType option:selected');
            const mealType = (selectedMealOption.data('name') || '').toString().trim();
            const slotTime = ($('#filterSlotTime').val() || '').toString().trim();
            const date = ($('#filterDate').val() || '').toString().trim();

            Swal.fire({
                title: 'Release Table?',
                text: 'This will release the current booking allocation for selected filters.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc3545',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, Release'
            }).then((result) => {
                if (!result.isConfirmed) return;

                $.ajax({
                    url: '../backend/online_tables_api.php?action=release_by_table',
                    method: 'POST',
                    contentType: 'application/json',
                    dataType: 'json',
                    data: JSON.stringify({
                        table_id: tableId,
                        date: date,
                        meal_type: mealType,
                        slot_time: slotTime
                    }),
                    success: function(response) {
                        if (response.success) {
                            Swal.fire('Success', 'Table released successfully', 'success');
                            loadServers();
                            loadOnlineTables();
                        } else {
                            Swal.fire('Error', response.message || 'Failed to release table', 'error');
                        }
                    },
                    error: function() {
                        Swal.fire('Error', 'Failed to release table', 'error');
                    }
                });
            });
        }

        async function releaseOnlineBookingGroup(bookingId, tableIdsCsv) {
            const selectedMealOption = $('#filterMealType option:selected');
            const mealType = (selectedMealOption.data('name') || '').toString().trim();
            const slotTime = ($('#filterSlotTime').val() || '').toString().trim();
            const date = ($('#filterDate').val() || '').toString().trim();
            const tableIds = String(tableIdsCsv || '').split(',').map(v => parseInt(v, 10)).filter(Number.isFinite);

            if (tableIds.length === 0) {
                Swal.fire('Error', 'No tables found in this selection', 'error');
                return;
            }

            const confirm = await Swal.fire({
                title: 'Release Selected Tables?',
                text: 'This will release all selected tables for current slot.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc3545',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, Release'
            });
            if (!confirm.isConfirmed) return;

            let successCount = 0;
            const failures = [];
            for (const tid of tableIds) {
                try {
                    const response = await $.ajax({
                        url: '../backend/online_tables_api.php?action=release_by_table',
                        method: 'POST',
                        contentType: 'application/json',
                        dataType: 'json',
                        data: JSON.stringify({
                            table_id: tid,
                            date: date,
                            meal_type: mealType,
                            slot_time: slotTime
                        })
                    });
                    if (response && response.success) {
                        successCount++;
                    } else {
                        failures.push(`Table ID ${tid}: ${response?.message || 'Failed'}`);
                    }
                } catch (err) {
                    failures.push(`Table ID ${tid}: Request failed`);
                }
            }

            loadServers();
            loadOnlineTables();
            if (failures.length === 0) {
                Swal.fire('Success', 'Released selected tables successfully', 'success');
            } else {
                Swal.fire('Warning', `Released ${successCount}/${tableIds.length}. ${failures.join(' | ')}`, 'warning');
            }
        }

        function updateStats(tables) {
            const total = tables.length;
            const available = tables.filter(t => (t.status || '').toLowerCase() === 'available').length;
            const booked = tables.filter(t => (t.status || '').toLowerCase() === 'booked').length;
            const maintenance = tables.filter(t => (t.status || '').toLowerCase() === 'maintenance').length;

            $('#totalTables').text(total);
            $('#availableTables').text(available);
            $('#bookedTables').text(booked);
            $('#maintenanceTables').text(maintenance);
        }

        function escapeHtml(str) {
            return String(str)
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#039;');
        }

        function logout() {
            Swal.fire({
                title: 'Logout Confirmation',
                text: 'Are you sure you want to logout?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc3545',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, logout'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: '../backend/manager_logout.php',
                        method: 'POST',
                        complete: function() {
                            localStorage.removeItem('manager_id');
                            localStorage.removeItem('manager_name');
                            localStorage.removeItem('manager_email');
                            localStorage.removeItem('manager_shift');
                            window.location.href = 'login.php';
                        }
                    });
                }
            });
        }

        $(document).on('click', function(e) {
            if ($(e.target).hasClass('modal')) {
                $(e.target).removeClass('show');
            }
        });
    </script>

    <script src="manager-sidebar.js"></script>
</body>

</html>
