<!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="Table Management - 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>Table Management - Granny Restaurant</title>

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

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

        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            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;
        }

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

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

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

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(42, 82, 152, 0.3);
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn-success:hover {
            background: #218838;
        }

        .btn-warning {
            background: #ffc107;
            color: #333;
        }

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

        .btn-info {
            background: #17a2b8;
            color: white;
        }

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

        .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 select,
        .control-group input {
            padding: 10px 15px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-family: inherit;
            font-size: 14px;
        }

        /* Table Grid */
        .tables-grid {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 20px;
            margin-bottom: 30px;
        }

        .table-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            transition: all 0.3s ease;
            cursor: pointer;
            position: relative;
            display: flex;
            flex-direction: column;
        }

        .table-card.available {
            cursor: pointer;
        }

        .table-card.available:hover {
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
            transform: translateY(-3px);
            background: #f9f9f9;
        }

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

        .table-card.available {
            border-left: 5px solid #28a745;
        }

        .table-card.booked {
            border-left: 5px solid #ffc107;
        }

        .table-card.occupied {
            border-left: 5px solid #007bff;
        }

        .table-card.maintenance {
            border-left: 5px solid #dc3545;
            opacity: 0.6;
        }

        .table-card.merged {
            border-left: 5px solid #2196F3;
            opacity: 0.75;
        }

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

        .table-capacity {
            font-size: 12px;
            color: #666;
            margin-bottom: 15px;
        }

        .table-status {
            display: inline-block;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            margin-bottom: 15px;
        }

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

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

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

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

        .table-section {
            font-size: 11px;
            color: #999;
            margin-bottom: 15px;
            text-transform: uppercase;
        }

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

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

        .table-actions button:hover {
            background: #f8f9fa;
            border-color: #1e3c72;
            color: #1e3c72;
        }

        .table-actions .btn-allocate {
            color: #28a745;
            border-color: #28a745;
        }

        .table-actions .btn-allocate:hover {
            background: #d4edda;
        }

        .table-actions .btn-merge {
            color: #ffc107;
            border-color: #ffc107;
        }

        .table-actions .btn-merge:hover {
            background: #fff3cd;
        }

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

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

        .table-actions .btn-info {
            color: #0c5460;
            border-color: #0c5460;
            background: white;
            border: 1px solid #0c5460;
            cursor: pointer;
            padding: 8px 12px;
            font-weight: 600;
            border-radius: 6px;
            transition: all 0.3s ease;
        }

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

        .table-actions .btn-warning {
            color: #ffc107;
            border-color: #ffc107;
        }

        .table-actions .btn-warning:hover:not(:disabled) {
            background: #fff3cd;
        }

        .table-actions .btn-maintenance {
            color: #6c757d;
            border-color: #6c757d;
        }

        .table-actions .btn-maintenance:hover:not(:disabled) {
            background: #e2e3e5;
        }

        .table-actions .btn-success {
            color: #28a745;
            border-color: #28a745;
            background: white;
        }

        .table-actions .btn-success:hover {
            background: #d4edda;
        }

        .table-actions button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .table-actions button:disabled:hover {
            background: white;
            border-color: #ddd;
            color: #999;
        }

        .table-server {
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px solid #eee;
            font-size: 13px;
        }

        .table-server strong {
            color: #1e3c72;
        }

        .table-merged {
            margin-top: 10px;
            padding: 8px 10px;
            background: #e7f3ff;
            border-left: 3px solid #2196F3;
            border-radius: 3px;
            font-size: 12px;
            color: #1565c0;
        }


        /* Responsive Table Grid */
        @media (max-width: 1440px) and (min-width: 1025px) {
            .tables-grid {
                grid-template-columns: repeat(3, 1fr);
            }
        }

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

        @media (max-width: 768px) {
            .page-header {
                flex-direction: column;
                text-align: center;
                gap: 15px;
            }

            .controls {
                flex-direction: column;
                align-items: stretch;
            }

            .control-group {
                width: 100%;
            }

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

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

        .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: 30px;
            border-radius: 10px;
            max-width: 500px;
            width: 100%;
            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 {
            color: #1e3c72;
            font-size: 20px;
            margin: 0;
        }

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

        .modal-header .close:hover {
            color: #333;
        }

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

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

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

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

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

        .modal-actions button {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s ease;
        }

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

        .close-modal:hover {
            background: #5a6268;
        }

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

        .confirm-action:hover {
            background: #218838;
        }
    </style>
</head>

<body>
    <div class="dashboard-container">
        <?php include 'sidebar.php'; ?>
        <div class="main-content">
            <div class="container">
                <div class="page-header">
            <h1><i class="fas fa-table"></i> Table Management</h1>
            <div class="header-actions">
                <button class="btn btn-primary" onclick="refreshTables()">
                    <i class="fas fa-sync"></i> Refresh
                </button>
            </div>
        </div>

        <div class="controls">
            <div style="width: 100%; font-size: 12px; font-weight: 700; color: #1e3c72; text-transform: uppercase; letter-spacing: 0.4px;">
                Direct Dining Filters
            </div>
            <div class="control-group">
                <label><i class="fas fa-calendar-alt"></i> Select Date</label>
                <input type="date" id="filterDate" onchange="filterTables()" style="padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px; width: 100%;">
            </div>

            <div class="control-group">
                <label>Floor</label>
                <select id="filterFloor" onchange="filterTables()">
                    <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>Section</label>
                <select id="filterSection" onchange="filterTables()">
                    <option value="">All Sections</option>
                    <option value="indoor">Indoor</option>
                    <option value="outdoor">Outdoor</option>
                    <option value="vip">VIP</option>
                </select>
            </div>

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

            <div class="control-group">
                <label>Capacity</label>
                <input type="number" id="filterCapacity" placeholder="Minimum guests" min="1" onchange="filterTables()">
            </div>
        </div>

        <div class="tables-grid" id="tablesGrid">
            <div style="text-align: center; padding: 40px; color: #999;">
                <i class="fas fa-spinner fa-spin" style="font-size: 32px; margin-bottom: 15px;"></i>
                <p>Loading tables...</p>
            </div>
        </div>
            </div>
        </div>
    </div>

    <!-- Allocate Table Modal -->
    <div class="modal" id="allocateModal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Allocate Table <strong id="allocateTableNumber"></strong></h2>
                <button class="close" onclick="closeModal('allocateModal')">&times;</button>
            </div>
            <form id="allocateForm">
                <div class="form-group">
                    <label>Customer Name</label>
                    <input type="text" id="customerName" placeholder="Enter customer name" required>
                </div>

                <div class="form-group">
                    <label>Assign Server</label>
                    <select id="serverSelect" required>
                        <option value="">Select a server</option>
                    </select>
                </div>

                <div class="form-group">
                    <label>Notes (Optional)</label>
                    <textarea id="allocateNotes" placeholder="Add any notes..."></textarea>
                </div>

                <div class="modal-actions">
                    <button type="button" class="close-modal" onclick="closeModal('allocateModal')">Cancel</button>
                    <button type="submit" class="confirm-action">Allocate Table</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Merge Tables Modal -->
    <div class="modal" id="mergeModal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Merge Tables</h2>
                <button class="close" onclick="closeModal('mergeModal')">&times;</button>
            </div>
            <form id="mergeForm">
                <div class="form-group">
                    <label>Primary Table</label>
                    <input type="text" id="primaryTableDisplay" readonly disabled>
                    <input type="hidden" id="primaryTableId">
                </div>

                <div class="form-group">
                    <label>Select Tables to Merge</label>
                    <div id="tablesToMerge" style="border: 1px solid #ddd; border-radius: 6px; padding: 15px; max-height: 300px; overflow-y: auto;">
                        <!-- Tables will be populated here -->
                    </div>
                </div>

                <div class="modal-actions">
                    <button type="button" class="close-modal" onclick="closeModal('mergeModal')">Cancel</button>
                    <button type="submit" class="confirm-action">Merge Tables</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Assign Server Modal -->
    <div class="modal" id="serverModal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Assign Server to Table</h2>
                <button class="close" onclick="closeModal('serverModal')">&times;</button>
            </div>
            <form id="serverForm">
                <div class="form-group">
                    <label>Table</label>
                    <input type="text" id="serverTableDisplay" readonly disabled>
                    <input type="hidden" id="serverTableId">
                </div>

                <div class="form-group">
                    <label>Select Server</label>
                    <select id="serverAssignSelect" required>
                        <option value="">Select a server</option>
                    </select>
                </div>

                <div class="modal-actions">
                    <button type="button" class="close-modal" onclick="closeModal('serverModal')">Cancel</button>
                    <button type="submit" class="confirm-action">Assign Server</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Maintenance Modal -->
    <div class="modal" id="maintenanceModal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Set Table for Maintenance</h2>
                <button class="close" onclick="closeModal('maintenanceModal')">&times;</button>
            </div>
            <form id="maintenanceForm">
                <div class="form-group">
                    <label>Table</label>
                    <input type="text" id="maintenanceTableDisplay" readonly disabled>
                    <input type="hidden" id="maintenanceTableId">
                </div>

                <div class="form-group">
                    <label>Reason for Maintenance</label>
                    <textarea id="maintenanceReason" placeholder="e.g., Cleaning, Repair, Inspection..."></textarea>
                </div>

                <div class="modal-actions">
                    <button type="button" class="close-modal" onclick="closeModal('maintenanceModal')">Cancel</button>
                    <button type="submit" class="confirm-action">Set Maintenance</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Allocate Guests Modal -->
    <div class="modal" id="allocateGuestsModal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Allocate Table <strong id="guestTableNumber"></strong></h2>
                <button class="close" onclick="closeModal('allocateGuestsModal')">&times;</button>
            </div>
            <form id="allocateGuestsForm">
                <div class="form-group">
                    <label>Table Capacity</label>
                    <input type="text" id="tableCapacityDisplay" readonly disabled>
                </div>

                <div class="form-group">
                    <label>Number of Guests</label>
                    <input type="number" id="numberOfGuests" min="1" required placeholder="Enter number of guests">
                    <small style="color: #666; margin-top: 5px; display: block;">Must not exceed table capacity</small>
                </div>

                <div class="modal-actions">
                    <button type="button" class="close-modal" onclick="closeModal('allocateGuestsModal')">Cancel</button>
                    <button type="submit" class="confirm-action">Allocate Table</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Assign Remaining Seats Modal -->
    <div class="modal" id="remainingSeatsModal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Assign Remaining Seats</h2>
                <button class="close" onclick="closeModal('remainingSeatsModal')">&times;</button>
            </div>
            <form id="remainingSeatsForm">
                <input type="hidden" id="remainingSeatsTableId">

                <div class="form-group">
                    <label>Table</label>
                    <input type="text" id="remainingSeatsTableDisplay" readonly disabled>
                </div>

                <div class="form-group">
                    <label>Assigned Server</label>
                    <input type="text" id="remainingSeatsServerDisplay" readonly disabled>
                </div>

                <div class="form-group">
                    <label>Current Remaining Seats</label>
                    <input type="text" id="remainingSeatsCountDisplay" readonly disabled>
                </div>

                <div class="form-group">
                    <label>Guests to Add</label>
                    <input type="number" id="remainingSeatsGuests" min="1" required placeholder="Enter guests to assign">
                    <small style="color: #666; margin-top: 5px; display: block;">These seats will be assigned to the currently assigned server</small>
                </div>

                <div class="modal-actions">
                    <button type="button" class="close-modal" onclick="closeModal('remainingSeatsModal')">Cancel</button>
                    <button type="submit" class="confirm-action">Assign Seats</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 currentAllocatingTable = null;

        // Global function to add manager_id to API URLs
        function getManagerApiUrl(action, additionalParams = '') {
            const managerId = localStorage.getItem('manager_id');
            const separator = additionalParams ? '&' : '?';
            return `../backend/manager_tables_api.php?action=${action}&manager_id=${managerId}${additionalParams ? separator + additionalParams : ''}`;
        }

        $(document).ready(function() {
            // Initialize date picker to today's date
            const today = new Date().toISOString().split('T')[0];
            $('#filterDate').val(today);
             
            checkAuthentication();
            fixMergedTablesStatus(); // Fix any existing merged tables with wrong status
            loadTables();
            loadServers();
        });

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

        function fixMergedTablesStatus() {
            const managerId = localStorage.getItem('manager_id');
            $.ajax({
                url: `../backend/fix_merged_tables.php?manager_id=${managerId}`,
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.success && response.affected_tables.length > 0) {
                        console.log('Fixed merged tables:', response.affected_tables);
                    }
                },
                error: function() {
                    // Silent fail - this is a background fix, not critical
                    console.log('Merged tables are already correct');
                }
            });
        }

        function loadTables() {
            const selectedDate = $('#filterDate').val();
             
            $.ajax({
                url: getManagerApiUrl('list', `date=${selectedDate}`),
                method: 'GET',
                success: function(response) {
                    if (response.success) {
                        allTables = response.data;
                        displayTables(allTables);
                    } else {
                        Swal.fire('Error', response.message, 'error');
                    }
                },
                error: function() {
                    Swal.fire('Error', 'Failed to load tables', 'error');
                }
            });
        }

        function loadServers() {
            $.ajax({
                url: getManagerApiUrl('get_servers'),
                method: 'GET',
                success: function(response) {
                    if (response.success) {
                        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);
                            options += `<option value="${server.id}">${server.name} (${activeCount}/${maxCount})</option>`;
                        });
                        $('#serverSelect').html(options);
                        $('#serverAssignSelect').html(options);
                    }
                }
            });
        }

                function displayTables(tables) {
            let html = '';

            // Show only direct dining tables and hide online reservation tables on this page.
            // Also show active tables (not merged) or main merged tables (which contain "+").
            const visibleTables = tables.filter(table =>
                table.table_source !== 'online' &&
                (table.status !== 'merged' || table.table_number.includes('+'))
            );

            visibleTables.forEach(table => {
                const isOnlineTable = table.table_source === 'online';
                const statusClass = table.status === 'available' ? 'available' :
                                   (table.status === 'occupied' ? 'occupied' :
                                   (table.status === 'booked' ? 'booked' : 'maintenance'));
                const isMerged = table.status === 'merged' || table.table_number.includes('+');
                const mergedClass = isMerged ? 'merged' : '';
                const statusText = table.status === 'merged' ? 'MERGED' :
                                   (table.table_number.includes('+') ? table.status.charAt(0).toUpperCase() + table.status.slice(1) + ' (Merged)' :
                                    table.status.charAt(0).toUpperCase() + table.status.slice(1));
                const sourceLabel = isOnlineTable ? 'Online Booking' : 'Direct Dining';

                const clickHandler = (!isOnlineTable && table.status === 'available')
                    ? `onclick="openAllocateGuestsModal(${table.id}, '${table.table_number}', ${table.current_capacity})"`
                    : '';

                let seatsDisplay = `${table.current_capacity} seats`;
                let seatsInfo = '';
                const guestCount = parseInt(table.number_of_guests, 10);
                const hasGuestCount = !Number.isNaN(guestCount) && guestCount > 0;
                const remainingSeats = hasGuestCount ? (table.current_capacity - guestCount) : table.current_capacity;
                if (table.status === 'occupied' && hasGuestCount) {
                    if (remainingSeats <= 0) {
                        seatsInfo = `<div style="color: #dc3545; font-weight: 600; margin-top: 5px;"><i class="fas fa-exclamation-circle"></i> Fully Occupied</div>`;
                    } else {
                        seatsInfo = `<div style="color: #28a745; margin-top: 5px;"><i class="fas fa-chair"></i> ${remainingSeats} seat${remainingSeats !== 1 ? 's' : ''} remaining</div>`;
                    }
                }

                let serverInfo = '';
                if ((table.status === 'occupied' || table.status === 'booked') && table.assigned_server_name) {
                    serverInfo = `<div style="margin-top: 8px; padding: 8px; background: #e7f3ff; border-radius: 4px; font-size: 12px; color: #0c5460;">
                        <i class="fas fa-user-tie"></i> <strong>Server:</strong> ${table.assigned_server_name}
                    </div>`;
                }

                html += `
                    <div class="table-card ${statusClass} ${mergedClass}" ${clickHandler}>
                        <div class="table-number">${table.table_number}</div>
                        <div class="table-capacity">
                            <i class="fas fa-users"></i> ${seatsDisplay}
                        </div>
                        <div>
                            <span class="table-status status-${isMerged ? 'merged' : statusClass}">${statusText}</span>
                        </div>
                        <div class="table-section">${table.section || 'General'}</div>
                        <div style="font-size: 11px; color: ${isOnlineTable ? '#8b6f47' : '#666'}; margin-bottom: 8px; font-weight: 600;">
                            <i class="fas ${isOnlineTable ? 'fa-globe' : 'fa-utensils'}"></i> ${sourceLabel}
                        </div>
                        ${seatsInfo}
                        ${serverInfo}
                        ${(!isOnlineTable && (table.status === 'occupied' || table.status === 'booked')) ? `
                            <div class="table-actions">
                                ${!table.assigned_server_name ? `
                                    <button class="btn-info" onclick="event.stopPropagation(); openServerModal(${table.id}, '${table.table_number}')" style="width: 100%; margin-top: 10px;">
                                        <i class="fas fa-user"></i> Assign Server
                                    </button>
                                ` : `
                                    <button class="btn-info" onclick="event.stopPropagation(); openServerModal(${table.id}, '${table.table_number}')" style="width: 100%; margin-top: 10px;">
                                        <i class="fas fa-user"></i> Change Server
                                    </button>
                                `}
                                ${(table.status === 'occupied' && table.assigned_server_name && hasGuestCount && remainingSeats > 0) ? `
                                    <button class="btn-success" onclick="event.stopPropagation(); openRemainingSeatsModal(${table.id})" style="width: 100%; margin-top: 5px;">
                                        <i class="fas fa-chair"></i> Assign Remaining Seats
                                    </button>
                                ` : ''}
                                <button class="btn-release" onclick="event.stopPropagation(); releaseTable(${table.id})" style="width: 100%; margin-top: 5px;">
                                    <i class="fas fa-door-open"></i> Release
                                </button>
                            </div>
                        ` : ''}
                        ${(!isOnlineTable && table.status === 'maintenance') ? `
                            <div class="table-actions">
                                <button class="btn-release" onclick="event.stopPropagation(); exitMaintenance(${table.id})" style="width: 100%; margin-top: 10px;">
                                    <i class="fas fa-check"></i> Exit Maintenance
                                </button>
                            </div>
                        ` : ''}
                        ${(!isOnlineTable && table.status !== 'occupied' && table.status !== 'booked' && table.status !== 'maintenance' && !isMerged) ? `
                            <div class="table-actions">
                                <button class="btn-merge" onclick="event.stopPropagation(); openMergeModal(${table.id}, '${table.table_number}')" style="flex: 1; margin-top: 10px;">
                                    <i class="fas fa-object-group"></i> Merge
                                </button>
                                <button class="btn-maintenance" onclick="event.stopPropagation(); openMaintenanceModal(${table.id}, '${table.table_number}')" style="flex: 1; margin-top: 10px; margin-left: 5px;" title="Set table for maintenance">
                                    <i class="fas fa-wrench"></i> Maintenance
                                </button>
                            </div>
                        ` : ''}
                        ${(!isOnlineTable && isMerged && table.table_number.includes('+') && table.status !== 'booked') ? `
                            <div class="table-actions">
                                <button class="btn-warning" onclick="event.stopPropagation(); unmergeTable(${table.id})" style="flex: 1; margin-top: 10px;" title="Unmerge table">
                                    <i class="fas fa-link"></i> Unmerge
                                </button>
                                <button class="btn-maintenance" onclick="event.stopPropagation(); openMaintenanceModal(${table.id}, '${table.table_number}')" style="flex: 1; margin-top: 10px; margin-left: 5px;" title="Set table for maintenance">
                                    <i class="fas fa-wrench"></i> Maintenance
                                </button>
                            </div>
                        ` : ''}
                        ${isOnlineTable ? `
                            <div style="margin-top: 10px; padding: 8px; border-radius: 6px; background: #fff9f0; color: #8b6f47; font-size: 12px; font-weight: 600;">
                                View only: managed from Online Tables/Reservations
                            </div>
                        ` : ''}
                    </div>
                `;
            });

            if (visibleTables.length === 0) {
                html = '<div style="text-align: center; padding: 40px; color: #999; grid-column: 1/-1;"><i class="fas fa-inbox" style="font-size: 32px; margin-bottom: 15px;"></i><p>No tables found</p></div>';
            }

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

        function filterTables() {
            // When filters change, reload tables with the new date and filters
            loadTables();

            // After tables are loaded, apply client-side filters
            setTimeout(() => {
                const floor = $('#filterFloor').val();
                const section = $('#filterSection').val();
                const status = $('#filterStatus').val();
                const capacity = $('#filterCapacity').val();

                let filtered = allTables.filter(table => {
                    let actualStatus = table.status;
                    if (status && actualStatus === 'merged') return false;
                    if (floor && table.floor_level != floor) return false;
                    if (section && table.section !== section) return false;
                    if (status && actualStatus !== status && actualStatus !== 'merged') return false;
                    if (capacity && table.current_capacity < capacity) return false;
                    return true;
                });

                displayTables(filtered);
            }, 100);
        }


        function openAllocateModal(tableId, tableNumber) {
            $('#allocateTableNumber').text(tableNumber);
            $('form#allocateForm').data('tableId', tableId);
            $('#allocateModal').addClass('show');
        }

        function openAllocateGuestsModal(tableId, tableNumber, capacity) {
            currentAllocatingTable = tableId;
            $('#guestTableNumber').text(tableNumber);
            $('#tableCapacityDisplay').val(`${capacity} seats`);
            $('#numberOfGuests').val('');
            $('#numberOfGuests').attr('max', capacity);
            $('#allocateGuestsModal').addClass('show');
        }

        function openMergeModal(tableId, tableNumber) {
            $('#primaryTableDisplay').val(`${tableNumber}`);
            $('#primaryTableId').val(tableId);
            
            let checkboxes = '';
            allTables.forEach(table => {
                // Only allow available tables that are not already merged
                if (table.id !== tableId && table.status === 'available' && !table.table_number.includes('+')) {
                    checkboxes += `
                        <label style="display: block; padding: 10px; border-bottom: 1px solid #eee;">
                            <input type="checkbox" value="${table.id}" class="merge-checkbox">
                            ${table.table_number} (${table.current_capacity} seats)
                        </label>
                    `;
                }
            });

            $('#tablesToMerge').html(checkboxes);
            $('#mergeModal').addClass('show');
        }

        function openServerModal(tableId, tableNumber) {
            $('#serverTableDisplay').val(`${tableNumber}`);
            $('#serverTableId').val(tableId);
            $('#serverModal').addClass('show');
        }

        function openMaintenanceModal(tableId, tableNumber) {
            $('#maintenanceTableDisplay').val(`${tableNumber}`);
            $('#maintenanceTableId').val(tableId);
            $('#maintenanceReason').val('');
            $('#maintenanceModal').addClass('show');
        }

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

            const guestCount = parseInt(table.number_of_guests, 10);
            if (Number.isNaN(guestCount) || guestCount <= 0) {
                Swal.fire('Error', 'No current guest allocation found for this table', 'error');
                return;
            }

            const remainingSeats = parseInt(table.current_capacity, 10) - guestCount;
            if (remainingSeats <= 0) {
                Swal.fire('Info', 'No remaining seats available on this table', 'info');
                return;
            }

            if (!table.assigned_server_name) {
                Swal.fire('Error', 'Assign a server before assigning remaining seats', 'error');
                return;
            }

            $('#remainingSeatsTableId').val(table.id);
            $('#remainingSeatsTableDisplay').val(table.table_number);
            $('#remainingSeatsServerDisplay').val(table.assigned_server_name);
            $('#remainingSeatsCountDisplay').val(`${remainingSeats} seat${remainingSeats !== 1 ? 's' : ''}`);
            $('#remainingSeatsGuests').val('');
            $('#remainingSeatsGuests').attr('max', remainingSeats);
            $('#remainingSeatsModal').addClass('show');
        }

        function exitMaintenance(tableId) {
            Swal.fire({
                title: 'Exit Maintenance?',
                text: 'Are you sure you want to restore this table to available status?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#28a745',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, Restore'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: getManagerApiUrl('exit_maintenance'),
                        method: 'POST',
                        contentType: 'application/json',
                        dataType: 'json',
                        data: JSON.stringify({ table_id: tableId }),
                        success: function(response) {
                            if (response.success) {
                                Swal.fire('Success', 'Table restored from maintenance', 'success');
                                loadTables();
                            } else {
                                Swal.fire('Error', response.message, 'error');
                            }
                        }
                    });
                }
            });
        }

        function releaseTable(tableId) {
            Swal.fire({
                title: 'Release Table?',
                text: 'Are you sure you want to release this table?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc3545',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, Release'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: getManagerApiUrl('release'),
                        method: 'POST',
                        contentType: 'application/json',
                        dataType: 'json',
                        data: JSON.stringify({ table_id: tableId }),
                        success: function(response) {
                            if (response.success) {
                                Swal.fire('Success', 'Table released successfully', 'success');
                                loadTables();
                                loadServers(); // Refresh available servers list
                            } else {
                                Swal.fire('Error', response.message, 'error');
                            }
                        }
                    });
                }
            });
        }

        function unmergeTable(mainTableId) {
            Swal.fire({
                title: 'Unmerge Table?',
                text: 'This will restore all merged tables back to their original state.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#ffc107',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, Unmerge'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: getManagerApiUrl('unmerge'),
                        method: 'POST',
                        contentType: 'application/json',
                        dataType: 'json',
                        data: JSON.stringify({ main_table_id: parseInt(mainTableId) }),
                        success: function(response) {
                            if (response.success) {
                                Swal.fire('Success', 'Tables unmerged successfully', 'success');
                                loadTables();
                            } else {
                                Swal.fire('Error', response.message, 'error');
                            }
                        },
                        error: function() {
                            Swal.fire('Error', 'Failed to unmerge tables', 'error');
                        }
                    });
                }
            });
        }

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

        function refreshTables() {
            loadTables();
            Swal.fire('Success', 'Tables refreshed', 'success');
        }

        // Form submissions
        $('#allocateGuestsForm').on('submit', function(e) {
            e.preventDefault();
            const numberOfGuests = parseInt($('#numberOfGuests').val());
            const maxCapacity = parseInt($('#tableCapacityDisplay').val());
            const bookingDate = $('#filterDate').val();

            if (numberOfGuests > maxCapacity) {
                Swal.fire('Error', 'Number of guests cannot exceed table capacity', 'error');
                return;
            }

            $.ajax({
                url: getManagerApiUrl('allocate_guests'),
                method: 'POST',
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify({
                    table_id: currentAllocatingTable,
                    number_of_guests: numberOfGuests,
                    booking_date: bookingDate
                }),
                success: function(response) {
                    if (response.success) {
                        Swal.fire('Success', 'Table allocated successfully', 'success');
                        closeModal('allocateGuestsModal');
                        loadTables();
                    } else {
                        Swal.fire('Error', response.message, 'error');
                    }
                },
                error: function() {
                    Swal.fire('Error', 'Failed to allocate table', 'error');
                }
            });
        });

        $('#allocateForm').on('submit', function(e) {
            e.preventDefault();
            const tableId = $(this).data('tableId');
            const customerName = $('#customerName').val();
            const serverId = $('#serverSelect').val();
            const notes = $('#allocateNotes').val();
            const bookingDate = $('#filterDate').val();

            $.ajax({
                url: getManagerApiUrl('allocate'),
                method: 'POST',
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify({
                    table_id: tableId,
                    customer_name: customerName,
                    notes: notes,
                    booking_date: bookingDate
                }),
                success: function(response) {
                    if (response.success) {
                        if (serverId) {
                            assignServer(response.data.assignment_id, tableId, serverId);
                        } else {
                            Swal.fire('Success', 'Table allocated successfully', 'success');
                            closeModal('allocateModal');
                            loadTables();
                        }
                    } else {
                        Swal.fire('Error', response.message, 'error');
                    }
                }
            });
        });

        $('#mergeForm').on('submit', function(e) {
            e.preventDefault();
            const primaryTableId = $('#primaryTableId').val();
            const mergeTableIds = [];

            $('.merge-checkbox:checked').each(function() {
                mergeTableIds.push(parseInt($(this).val()));
            });

            if (mergeTableIds.length === 0) {
                Swal.fire('Error', 'Please select at least one table to merge', 'error');
                return;
            }

            $.ajax({
                url: getManagerApiUrl('merge'),
                method: 'POST',
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify({
                    primary_table_id: parseInt(primaryTableId),
                    merge_table_ids: mergeTableIds
                }),
                success: function(response) {
                    if (response.success) {
                        closeModal('mergeModal');
                        Swal.fire('Success', 'Tables merged successfully', 'success');
                        // Force full page reload to ensure database changes are reflected
                        setTimeout(function() {
                            location.reload();
                        }, 1000);
                    } else {
                        Swal.fire('Error', response.message, 'error');
                    }
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.error('Merge error:', textStatus, errorThrown);
                    Swal.fire('Error', 'Failed to merge tables', 'error');
                }
            });
        });

        $('#serverForm').on('submit', function(e) {
            e.preventDefault();
            const tableId = $('#serverTableId').val();
            const serverId = $('#serverAssignSelect').val();

            assignServer(null, tableId, serverId);
        });

        $('#maintenanceForm').on('submit', function(e) {
            e.preventDefault();
            const tableId = $('#maintenanceTableId').val();
            const reason = $('#maintenanceReason').val();

            $.ajax({
                url: getManagerApiUrl('set_maintenance'),
                method: 'POST',
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify({
                    table_id: tableId,
                    reason: reason
                }),
                success: function(response) {
                    if (response.success) {
                        Swal.fire('Success', 'Table set to maintenance successfully', 'success');
                        closeModal('maintenanceModal');
                        loadTables();
                    } else {
                        Swal.fire('Error', response.message, 'error');
                    }
                }
            });
        });

        $('#remainingSeatsForm').on('submit', function(e) {
            e.preventDefault();

            const tableId = parseInt($('#remainingSeatsTableId').val(), 10);
            const guestsToAdd = parseInt($('#remainingSeatsGuests').val(), 10);
            const maxSeats = parseInt($('#remainingSeatsGuests').attr('max'), 10);

            if (Number.isNaN(guestsToAdd) || guestsToAdd <= 0) {
                Swal.fire('Error', 'Please enter a valid number of guests', 'error');
                return;
            }

            if (!Number.isNaN(maxSeats) && guestsToAdd > maxSeats) {
                Swal.fire('Error', `Cannot assign more than ${maxSeats} remaining seat${maxSeats !== 1 ? 's' : ''}`, 'error');
                return;
            }

            $.ajax({
                url: getManagerApiUrl('assign_remaining_seats'),
                method: 'POST',
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify({
                    table_id: tableId,
                    additional_guests: guestsToAdd
                }),
                success: function(response) {
                    if (response.success) {
                        closeModal('remainingSeatsModal');
                        Swal.fire('Success', response.message, 'success');
                        loadTables();
                    } else {
                        Swal.fire('Error', response.message, 'error');
                    }
                },
                error: function() {
                    Swal.fire('Error', 'Failed to assign remaining seats', 'error');
                }
            });
        });

        function assignServer(assignmentId, tableId, serverId) {
            $.ajax({
                url: getManagerApiUrl('assign_server'),
                method: 'POST',
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify({
                    table_id: tableId,
                    server_id: serverId
                }),
                success: function(response) {
                    if (response.success) {
                        Swal.fire('Success', 'Server assigned successfully', 'success');
                        closeModal('allocateModal');
                        closeModal('serverModal');
                        loadTables();
                        loadServers(); // Refresh available servers list
                    } else {
                        Swal.fire('Error', response.message, 'error');
                    }
                }
            });
        }

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

    <!-- Manager Sidebar Script -->
    <script src="manager-sidebar.js"></script>
</body>

</html>

