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

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

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

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

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

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

    <title>Table Management - Granny Restaurant</title>

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

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

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

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

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

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

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

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

        .sidebar-menu li {
            margin: 0;
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        .btn-primary {
            background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(212, 165, 116, 0.4);
            color: white;
            text-decoration: none;
        }

        .btn-secondary {
            background: #e0e0e0;
            color: #333;
        }

        .btn-secondary:hover {
            background: #d0d0d0;
            color: #333;
            text-decoration: none;
        }

        .btn-secondary.active {
            background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
            color: white;
        }

        .btn-secondary.active:hover {
            background: linear-gradient(135deg, #c9935d 0%, #7d6239 100%);
            color: white;
            text-decoration: none;
        }

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

        .btn-danger:hover {
            background: #c0392b;
            color: white;
            text-decoration: none;
        }

        .btn-warning {
            background: #f39c12;
            color: white;
        }

        .btn-warning:hover {
            background: #e67e22;
            color: white;
            text-decoration: none;
        }

        .btn-success {
            background: #27ae60;
            color: white;
        }

        .btn-success:hover {
            background: #229954;
            color: white;
            text-decoration: none;
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        /* Table List View */
        .table-list {
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .table-list table {
            width: 100%;
            border-collapse: collapse;
        }

        .table-list th {
            background: #2c3e50;
            color: white;
            padding: 15px;
            text-align: left;
            font-weight: 600;
            font-size: 13px;
            text-transform: uppercase;
        }

        .table-list td {
            padding: 15px;
            border-bottom: 1px solid #eee;
            font-size: 14px;
        }

        .table-list tr:hover {
            background: #f9f9f9;
        }

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

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

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

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

        @keyframes slideIn {
            from {
                transform: translateY(-50px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        .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 {
            margin: 0;
            font-size: 22px;
            font-weight: 600;
            color: #2c3e50;
        }

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

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

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

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

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

        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: #d4a574;
            box-shadow: 0 0 0 3px rgba(212, 165, 116, 0.1);
        }

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

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

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

        /* View Toggle */
        .view-toggle {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }

        .view-toggle button {
            padding: 8px 16px;
            border: 2px solid #ddd;
            background: white;
            cursor: pointer;
            border-radius: 4px;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .view-toggle button.active {
            background: #d4a574;
            color: white;
            border-color: #d4a574;
        }

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

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

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

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

        /* Floor View */
        .floor-section {
            margin-bottom: 30px;
        }

        .floor-title {
            font-size: 18px;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 15px;
            padding: 10px 15px;
            background: #f9f9f9;
            border-left: 4px solid #d4a574;
            border-radius: 4px;
        }

        /* Table Merge Interface */
        .table-merge-area {
            background: #f9f9f9;
            padding: 15px;
            border-radius: 8px;
            margin-top: 20px;
            border: 2px dashed #d4a574;
        }

        .table-merge-area h4 {
            margin-top: 0;
            color: #2c3e50;
            font-size: 14px;
            font-weight: 600;
        }

        .selected-tables {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 15px;
        }

        .selected-table-badge {
            background: #d4a574;
            color: white;
            padding: 8px 12px;
            border-radius: 20px;
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 13px;
        }

        .selected-table-badge button {
            background: none;
            border: none;
            color: white;
            cursor: pointer;
            font-size: 16px;
            padding: 0;
        }

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

        .loading.show {
            display: block;
        }

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

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

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

            .topbar {
                left: 250px;
            }

            .main-content {
                margin-left: 250px;
            }
        }

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

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

            .topbar {
                left: 0;
            }

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

            .menu-toggle {
                display: block;
            }

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

            .header {
                flex-direction: column;
                gap: 15px;
                background: white;
                padding: 15px;
                border-radius: 8px;
                box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
                margin-bottom: 20px;
            }

            .header-actions {
                width: 100%;
                flex-direction: column;
            }

            .filters {
                flex-direction: column;
            }

            .filter-group {
                width: 100%;
            }

            .modal-content {
                width: 95%;
                max-width: 90vw;
            }

            .topbar-title {
                font-size: 18px;
            }
        }

        @media (max-width: 576px) {
            .topbar {
                padding: 0 15px;
            }

            .topbar-right {
                gap: 15px;
            }

            .user-info {
                display: none;
            }
        }
        .sidebar-footer {
            /* padding: 20px; */
            border-top: 1px solid rgba(255, 255, 255, 0.1);
            position: absolute;
            /* bottom: 0; */
            width: 100%;
        }

        .logout-btn {
            width: 100%;
            padding: 12px;
            background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            font-size: 14px;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .logout-btn:hover {
            background: linear-gradient(135deg, #c0392b 0%, #a93226 100%);
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(231, 76, 60, 0.3);
        }
    </style>
</head>

<body>
    <!-- Sidebar -->
    <div class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <i class="fas fa-crown sidebar-logo"></i>
            <h2>Admin Portal</h2>
            <p>Granny Restaurant</p>
            <div class="admin-name" id="sidebarAdminName">Admin</div>
        </div>

        <ul class="sidebar-menu">
            <li><a href="dashboard.php"><i class="fas fa-chart-line"></i> <span>Dashboard</span></a></li>
            <li><a href="carousel.php"><i class="fas fa-images"></i> <span>Carousel</span></a></li>
            <li><a href="gallery.php"><i class="fas fa-th-large"></i> <span>Gallery</span></a></li>
            <li><a href="chefs.php"><i class="fas fa-user-tie"></i> <span>Chefs</span></a></li>
            <li><a href="tables.php" class="active"><i class="fas fa-chair"></i> <span>Tables</span></a></li>
            <li><a href="menu.php"><i class="fas fa-utensils"></i> <span>Menu</span></a></li>
            <li><a href="bookings.php"><i class="fas fa-calendar-check"></i> <span>Bookings</span><span class="notification-badge hidden" data-type="bookings">0</span></a></li>
            <li><a href="orders.php"><i class="fas fa-shopping-cart"></i> <span>Orders</span><span class="notification-badge hidden" data-type="orders">0</span></a></li>
            <li><a href="contacts.php"><i class="fas fa-envelope"></i> <span>Contacts</span><span class="notification-badge hidden" data-type="contacts">0</span></a></li>
            <li><a href="feedback.php"><i class="fas fa-comments"></i> <span>Feedback</span><span class="notification-badge hidden" data-type="feedback">0</span></a></li>
            <li><a href="users.php"><i class="fas fa-users"></i> <span>Users</span></a></li>
            <li><a href="settings.php"><i class="fas fa-cog"></i> <span>Settings</span></a></li>
        </ul>

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

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

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

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

    <!-- Main Content -->
    <div class="main-content">
        <!-- Header -->
        <div class="header">
            <div>
                <h1><i class="fas fa-chair"></i> Table Management</h1>
                <p style="margin: 5px 0 0 0; color: #999; font-size: 13px;">Manage restaurant tables, capacity, and bookings</p>
            </div>
            <div class="header-actions">
                <button class="btn btn-primary" onclick="openCreateModal()">
                    <i class="fas fa-plus"></i> Create Table
                </button>
            </div>
        </div>

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

        <!-- Filters -->
        <div class="filters">
            <div class="filter-group">
                <label for="filterFloor">Floor Level</label>
                <select id="filterFloor" onchange="loadTables()">
                    <option value="">All Floors</option>
                    <option value="1">Floor 1</option>
                    <option value="2">Floor 2</option>
                    <option value="3">Floor 3</option>
                </select>
            </div>
            <div class="filter-group">
                <label for="filterSection">Section</label>
                <select id="filterSection" onchange="loadTables()">
                    <option value="">All Sections</option>
                </select>
            </div>
            <div class="filter-group">
                <label for="filterStatus">Status</label>
                <select id="filterStatus" onchange="loadTables()">
                    <option value="">All Status</option>
                    <option value="available">Available</option>
                    <option value="booked">Booked</option>
                    <option value="maintenance">Maintenance</option>
                </select>
            </div>
            <div class="filter-group" style="margin-top: auto;">
                <button class="btn btn-secondary" onclick="resetFilters()">
                    <i class="fas fa-redo"></i> Reset Filters
                </button>
            </div>
        </div>

        <!-- View Toggle -->
        <div class="view-toggle">
            <button class="btn-toggle active" onclick="switchView('grid')">
                <i class="fas fa-th"></i> Grid View
            </button>
            <button class="btn-toggle" onclick="switchView('list')">
                <i class="fas fa-list"></i> List View
            </button>
        </div>

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

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

        <!-- List View -->
        <div id="listView" style="display: none;">
            <div class="table-list">
                <table>
                    <thead>
                        <tr>
                            <th>Table No.</th>
                            <th>Capacity</th>
                            <th>Floor</th>
                            <th>Section</th>
                            <th>Status</th>
                            <th>Notes</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="tableListBody"></tbody>
                </table>
            </div>
        </div>

        <!-- Merge Tables Section -->
        <div style="margin-top: 40px;">
            <div class="table-merge-area">
                <h4><i class="fas fa-code-branch"></i> Merge Tables</h4>
                <p style="font-size: 12px; color: #666; margin-bottom: 15px;">
                    Select multiple tables from the grid above by clicking their checkboxes, then use this area to merge them.
                </p>
                <div class="selected-tables" id="selectedTables"></div>
                <div style="display: flex; gap: 10px;">
                    <button class="btn btn-primary" onclick="mergeTables()" id="mergeBtn" disabled>
                        <i class="fas fa-link"></i> Merge Selected
                    </button>
                    <button class="btn btn-secondary" onclick="clearSelection()">
                        <i class="fas fa-times"></i> Clear Selection
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Create/Edit Table Modal -->
    <div id="tableModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modalTitle">Create New Table</h2>
                <button class="modal-close" onclick="closeModal()">&times;</button>
            </div>
            <form id="tableForm">
                <div class="form-group">
                    <label for="tableNumber">Table Number <span style="color: #d4a574;">*</span></label>
                    <input type="text" id="tableNumber" placeholder="e.g., T-01, A-01" required>
                </div>
                <div class="form-group">
                    <label for="tableCapacity">Capacity (Chairs) <span style="color: #d4a574;">*</span></label>
                    <input type="number" id="tableCapacity" value="4" min="1" max="20" required>
                </div>
                <div class="form-group">
                    <label for="tableFloor">Floor Level <span style="color: #d4a574;">*</span></label>
                    <select id="tableFloor" required>
                        <option value="1">Floor 1</option>
                        <option value="2">Floor 2</option>
                        <option value="3">Floor 3</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="tableSection">Section</label>
                    <input type="text" id="tableSection" placeholder="e.g., Dining Area, VIP Corner">
                </div>
                <div class="form-group">
                    <label for="tableNotes">Notes</label>
                    <textarea id="tableNotes" placeholder="Any special notes about this table..."></textarea>
                </div>
                <div class="modal-actions">
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save Table</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Check Availability Modal -->
    <div id="availabilityModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Check Availability</h2>
                <button class="modal-close" onclick="closeAvailabilityModal()">&times;</button>
            </div>
            <form id="availabilityForm">
                <div class="form-group">
                    <label for="availDate">Date <span style="color: #d4a574;">*</span></label>
                    <input type="date" id="availDate" required>
                </div>
                <div class="form-group">
                    <label for="availTime">Time <span style="color: #d4a574;">*</span></label>
                    <input type="time" id="availTime" required>
                </div>
                <div class="form-group">
                    <label for="availGuests">Number of Guests <span style="color: #d4a574;">*</span></label>
                    <input type="number" id="availGuests" min="1" value="4" required>
                </div>
                <div id="availabilityResults" style="margin-top: 20px;"></div>
                <div class="modal-actions">
                    <button type="button" class="btn btn-secondary" onclick="closeAvailabilityModal()">Close</button>
                </div>
            </form>
        </div>
    </div>

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

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

    <script>
        let currentView = 'grid';
        let tables = [];
        let selectedTables = [];
        let currentTableId = null;

        // Helper function to get display notes (removes merge metadata)
        function getDisplayNotes(notes) {
            if (!notes) return '';
            // Remove the "Merge Info: {...}" part and return only user-added notes
            return notes.replace(/Merge Info:\s*\[[\s\S]*?\]/g, '').trim();
        }

        // Initialize
        document.addEventListener('DOMContentLoaded', function() {
            loadTables();
            loadSections();
            document.getElementById('tableForm').addEventListener('submit', saveTable);
            document.getElementById('availabilityForm').addEventListener('submit', checkAvailability);
            
            // Initialize mobile menu
            initMobileMenu();
            
            // Close sidebar when clicking on menu items
            document.querySelectorAll('.sidebar-menu a').forEach(link => {
                link.addEventListener('click', function() {
                    if (window.innerWidth <= 768) {
                        const sidebar = document.querySelector('.sidebar');
                        if (sidebar) {
                            sidebar.classList.remove('mobile-open');
                        }
                    }
                });
            });

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

        // Load tables from API
        function loadTables() {
            const floor = document.getElementById('filterFloor').value;
            const section = document.getElementById('filterSection').value;
            const status = document.getElementById('filterStatus').value;

            let url = '../backend/tables_api.php?action=list';
            if (floor) url += '&floor=' + floor;
            if (section) url += '&section=' + section;
            if (status) url += '&status=' + status;

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

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

        // Display tables in grid view
        function displayTables() {
            const gridContainer = document.getElementById('tableGrid');
            const listBody = document.getElementById('tableListBody');
            
            gridContainer.innerHTML = '';
            listBody.innerHTML = '';

            // Show active tables (not merged) or main merged tables (which contain "+")
            const displayTables = tables.filter(table => 
                table.status !== 'merged' || table.table_number.includes('+')
            );

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

            displayTables.forEach(table => {
                // Grid view
                const gridCard = createTableCard(table);
                gridContainer.appendChild(gridCard);

                // List view
                const listRow = document.createElement('tr');
                const displayNotes = getDisplayNotes(table.notes);
                listRow.innerHTML = `
                    <td><strong>${table.table_number}</strong></td>
                    <td><span class="chair-icon">${table.current_capacity}</span></td>
                    <td>Floor ${table.floor_level}</td>
                    <td>${table.section || '-'}</td>
                    <td><span class="status-badge status-${table.status}">${table.status.toUpperCase()}</span></td>
                    <td>${displayNotes ? displayNotes.substring(0, 30) + '...' : '-'}</td>
                    <td>
                        <button class="btn btn-sm btn-primary" onclick="viewTable(${table.id})">View</button>
                        <button class="btn btn-sm btn-danger" onclick="deleteTable(${table.id})">Delete</button>
                    </td>
                `;
                listBody.appendChild(listRow);
            });
            
            // Update button styling after displaying tables
            updateSelectButtons();
        }

        // Create table card element
        function createTableCard(table) {
            const card = document.createElement('div');
            card.className = 'table-card';
            const isSelected = selectedTables.includes(String(table.id));
            const isMerged = table.status === 'merged' || table.table_number.includes('+');
            const displayNotes = getDisplayNotes(table.notes);
            
            card.innerHTML = `
                <div class="table-card-header">
                    <div class="table-number">${table.table_number}</div>
                    <span class="status-badge status-${table.status}">${table.status.toUpperCase()}</span>
                </div>
                <div class="table-info">
                    <div class="info-row">
                        <span class="info-label">Capacity:</span>
                        <div class="capacity-indicator">
                            <span class="chair-icon">${table.current_capacity}</span>
                            <span class="info-value">${table.current_capacity} Chairs</span>
                        </div>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Floor:</span>
                        <span class="info-value">Floor ${table.floor_level}</span>
                    </div>
                    ${table.section ? `
                    <div class="info-row">
                        <span class="info-label">Section:</span>
                        <span class="info-value">${table.section}</span>
                    </div>
                    ` : ''}
                    ${displayNotes ? `
                    <div class="info-row">
                        <span class="info-label">Notes:</span>
                        <span class="info-value">${displayNotes.substring(0, 40)}...</span>
                    </div>
                    ` : ''}
                </div>
                <div class="table-card-actions">
                    <button class="btn btn-secondary btn-sm" onclick="viewTable(${table.id})">
                        <i class="fas fa-eye"></i> View
                    </button>
                    ${!isMerged ? `
                    <button class="btn btn-secondary btn-sm ${isSelected ? 'active' : ''}" onclick="selectTableForMerge('${table.id}')" id="select-${table.id}" ${table.status === 'booked' ? 'disabled style="opacity: 0.5; cursor: not-allowed;"' : ''} title="${table.status === 'booked' ? 'Cannot select a booked table' : 'Select for merge'}">
                        <i class="fas fa-check"></i> ${isSelected ? 'Selected' : 'Select'}
                    </button>
                    ` : `
                    <button class="btn btn-warning btn-sm" onclick="unmergeTable(${table.id})" ${table.status === 'booked' ? 'disabled style="opacity: 0.5; cursor: not-allowed;"' : ''} title="${table.status === 'booked' ? 'Cannot unmerge a booked table' : 'Unmerge table'}">
                        <i class="fas fa-link"></i> Unmerge
                    </button>
                    `}
                    <button class="btn btn-danger btn-sm" onclick="deleteTable(${table.id})">
                        <i class="fas fa-trash"></i> Delete
                    </button>
                </div>
            `;
            return card;
        }

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

            // Count active tables (not merged) or main merged tables (which contain "+")
            const activeTables = tables.filter(table => 
                table.status !== 'merged' || table.table_number.includes('+')
            );

            activeTables.forEach(table => {
                if (table.status === 'available') available++;
                if (table.status === 'booked') booked++;
                // if (table.status === 'merged') booked++; // Merged tables count as booked
                totalCapacity += parseInt(table.current_capacity);
            });

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

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

        // Open create modal
        function openCreateModal() {
            currentTableId = null;
            document.getElementById('modalTitle').textContent = 'Create New Table';
            document.getElementById('tableForm').reset();
            document.getElementById('tableCapacity').value = 4;
            document.getElementById('tableFloor').value = 1;
            document.getElementById('tableModal').classList.add('show');
        }

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

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

        // Initialize mobile sidebar handlers
        function initMobileMenu() {
            const menuToggle = document.getElementById('menuToggle');
            const menuToggleTop = document.getElementById('menuToggleTop');
            const sidebar = document.querySelector('.sidebar');

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

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

            // Close sidebar when clicking on menu items
            document.querySelectorAll('.sidebar-menu a').forEach(link => {
                link.addEventListener('click', function() {
                    if (window.innerWidth <= 768) {
                        if (sidebar) {
                            sidebar.classList.remove('mobile-open');
                        }
                    }
                });
            });

            // Close sidebar when clicking outside
            document.addEventListener('click', function(event) {
                if (window.innerWidth <= 768 && sidebar) {
                    if (!sidebar.contains(event.target) && !menuToggle?.contains(event.target) && !menuToggleTop?.contains(event.target)) {
                        sidebar.classList.remove('mobile-open');
                    }
                }
            });
              document.getElementById('logoutBtn').addEventListener('click', function() {
                Swal.fire({
                    icon: 'warning',
                    title: 'Confirm Logout',
                    text: 'Are you sure you want to logout?',
                    showCancelButton: true,
                    confirmButtonColor: '#d4a574',
                    cancelButtonColor: '#999',
                    confirmButtonText: 'Yes, Logout',
                    cancelButtonText: 'Cancel'
                }).then((result) => {
                    if (result.isConfirmed) {
                        localStorage.removeItem('admin_user');
                        localStorage.removeItem('admin_token');
                        
                        fetch('../backend/admin_logout.php', {
                            method: 'POST'
                        }).then(() => {
                            window.location.href = 'login.php';
                        });
                    }
                });
            });

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

        // Save table
        function saveTable(e) {
            e.preventDefault();

            let notes = document.getElementById('tableNotes').value;
            
            // If this is an existing table with merge metadata, preserve it
            if (currentTableId) {
                const table = tables.find(t => parseInt(t.id) === parseInt(currentTableId));
                if (table && table.notes) {
                    const mergeInfo = table.notes.match(/Merge Info:\s*\[[\s\S]*?\]/);
                    if (mergeInfo) {
                        // Preserve merge metadata
                        notes = notes.trim() ? notes + '\n' + mergeInfo[0] : mergeInfo[0];
                    }
                }
            }

            const data = {
                table_number: document.getElementById('tableNumber').value,
                capacity: parseInt(document.getElementById('tableCapacity').value),
                floor_level: parseInt(document.getElementById('tableFloor').value),
                section: document.getElementById('tableSection').value,
                notes: notes
            };

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

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

        // View table details
        function viewTable(id) {
            console.log('viewTable called with id:', id, 'type:', typeof id);
            console.log('tables array:', tables);
            
            // Convert id to number for comparison
            const tableId = parseInt(id);
            const table = tables.find(t => parseInt(t.id) === tableId);
            console.log('found table:', table);
            
            if (!table) {
                console.error('Table not found with id:', id);
                Swal.fire('Error', 'Table not found', 'error');
                return;
            }

            currentTableId = id;
            document.getElementById('viewModalTitle').textContent = `Table ${table.table_number}`;
            
            const displayNotes = getDisplayNotes(table.notes);
            let content = `
                <div class="table-info">
                    <div class="info-row">
                        <span class="info-label">Table Number:</span>
                        <span class="info-value">${table.table_number}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Base Capacity:</span>
                        <span class="info-value">${table.base_capacity} Chairs</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Current Capacity:</span>
                        <span class="info-value">${table.current_capacity} Chairs</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Floor Level:</span>
                        <span class="info-value">Floor ${table.floor_level}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Section:</span>
                        <span class="info-value">${table.section || 'Not assigned'}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Status:</span>
                        <span class="status-badge status-${table.status}" style="margin-left: auto;">${table.status.toUpperCase()}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Notes:</span>
                        <span class="info-value">${displayNotes || 'None'}</span>
                    </div>
                    <div class="info-row">
                        <span class="info-label">Created:</span>
                        <span class="info-value">${new Date(table.created_at).toLocaleDateString()}</span>
                    </div>
                </div>
            `;

            document.getElementById('viewTableContent').innerHTML = content;
            const modal = document.getElementById('viewTableModal');
            if (modal) {
                modal.classList.add('show');
                console.log('Modal shown');
            } else {
                console.error('Modal element not found');
            }
        }

        // Close view modal
        function closeViewModal() {
            document.getElementById('viewTableModal').classList.remove('show');
            // Don't clear currentTableId yet - it's needed for edit function
        }

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

            document.getElementById('modalTitle').textContent = `Edit Table ${table.table_number}`;
            document.getElementById('tableNumber').value = table.table_number;
            document.getElementById('tableCapacity').value = table.current_capacity;
            document.getElementById('tableFloor').value = table.floor_level;
            document.getElementById('tableSection').value = table.section || '';
            document.getElementById('tableNotes').value = getDisplayNotes(table.notes);

            // Close view modal and open edit modal
            document.getElementById('viewTableModal').classList.remove('show');
            document.getElementById('tableModal').classList.add('show');
            currentTableId = table.id; // Keep the ID for saving
        }

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

        // Delete current table
        function deleteCurrentTable() {
            if (currentTableId) {
                deleteTable(currentTableId);
                closeViewModal();
            }
        }

        // Select table for merge
        function selectTableForMerge(id) {
            // Convert ID to string for consistency
            const tableId = String(id);
            
            console.log('selectTableForMerge called with id:', tableId);
            console.log('selectedTables before:', selectedTables);
            
            if (selectedTables.includes(tableId)) {
                selectedTables = selectedTables.filter(t => t !== tableId);
                console.log('Removed table from selection');
            } else {
                selectedTables.push(tableId);
                console.log('Added table to selection');
            }
            
            console.log('selectedTables after:', selectedTables);
            
            updateSelectedTablesDisplay();
            updateSelectButtons();
        }

        // Update select button styling
        function updateSelectButtons() {
            tables.forEach(table => {
                const button = document.getElementById(`select-${table.id}`);
                if (button) {
                    const isSelected = selectedTables.includes(String(table.id));
                    button.classList.toggle('active', isSelected);
                    button.innerHTML = isSelected ? '<i class="fas fa-check"></i> Selected' : '<i class="fas fa-check"></i> Select';
                }
            });
        }

        // Update selected tables display
        function updateSelectedTablesDisplay() {
            const container = document.getElementById('selectedTables');
            container.innerHTML = '';

            selectedTables.forEach(id => {
                const table = tables.find(t => String(t.id) === id);
                if (table) {
                    const badge = document.createElement('div');
                    badge.className = 'selected-table-badge';
                    badge.innerHTML = `
                        ${table.table_number} (${table.current_capacity} chairs)
                        <button type="button" onclick="selectTableForMerge('${id}')">×</button>
                    `;
                    container.appendChild(badge);
                }
            });

            document.getElementById('mergeBtn').disabled = selectedTables.length < 2;
        }

        // Merge tables
        function mergeTables() {
            if (selectedTables.length < 2) {
                Swal.fire('Error', 'Select at least 2 tables to merge', 'error');
                return;
            }

            Swal.fire({
                title: 'Merge Tables?',
                text: `This will merge ${selectedTables.length} tables into one larger table.`,
                icon: 'info',
                showCancelButton: true,
                confirmButtonColor: '#d4a574',
                cancelButtonColor: '#999',
                confirmButtonText: 'Yes, merge them!'
            }).then((result) => {
                if (result.isConfirmed) {
                    fetch('../backend/tables_api.php?action=merge', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ table_ids: selectedTables })
                    })
                    .then(response => response.json())
                    .then(result => {
                        if (result.success) {
                            Swal.fire('Success', 'Tables merged successfully!', 'success');
                            selectedTables = [];
                            updateSelectedTablesDisplay();
                            updateSelectButtons();
                            loadTables();
                        } else {
                            Swal.fire('Error', result.message, 'error');
                        }
                    });
                }
            });
        }

        // Unmerge a merged table back to original tables
        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: '#d4a574',
                cancelButtonColor: '#999',
                confirmButtonText: 'Yes, unmerge them!'
            }).then((result) => {
                if (result.isConfirmed) {
                    console.log('Unmerging table ID:', mainTableId);
                    fetch('../backend/tables_api.php?action=unmerge', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ main_table_id: parseInt(mainTableId) })
                    })
                    .then(response => response.json())
                    .then(result => {
                        console.log('Unmerge response:', result);
                        if (result.success) {
                            Swal.fire('Success', 'Tables unmerged successfully!', 'success');
                            setTimeout(() => loadTables(), 500);
                        } else {
                            Swal.fire('Error', result.message, 'error');
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        Swal.fire('Error', 'Failed to unmerge tables', 'error');
                    });
                }
            });
        }

        // Clear selection
        function clearSelection() {
            selectedTables = [];
            updateSelectedTablesDisplay();
        }

        // Switch view
        function switchView(view) {
            currentView = view;
            document.querySelectorAll('.btn-toggle').forEach(btn => btn.classList.remove('active'));
            event.target.closest('button').classList.add('active');

            if (view === 'grid') {
                document.getElementById('gridView').style.display = 'block';
                document.getElementById('listView').style.display = 'none';
            } else {
                document.getElementById('gridView').style.display = 'none';
                document.getElementById('listView').style.display = 'block';
            }
        }

        // Reset filters
        function resetFilters() {
            document.getElementById('filterFloor').value = '';
            document.getElementById('filterSection').value = '';
            document.getElementById('filterStatus').value = '';
            loadTables();
        }

        // Check availability
        function checkAvailability(e) {
            e.preventDefault();

            const date = document.getElementById('availDate').value;
            const time = document.getElementById('availTime').value;
            const guests = document.getElementById('availGuests').value;

            fetch(`../backend/tables_api.php?action=get_availability&date=${date}&time=${time}&guests=${guests}`)
                .then(response => response.json())
                .then(data => {
                    const resultsDiv = document.getElementById('availabilityResults');
                    if (data.success && data.data.length > 0) {
                        let html = '<p style="margin-bottom: 15px; color: #27ae60; font-weight: 600;">Available Tables:</p>';
                        html += '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px;">';
                        data.data.forEach(table => {
                            html += `
                                <div style="background: #d4edda; padding: 10px; border-radius: 4px; text-align: center;">
                                    <div style="font-weight: 600; font-size: 16px;">${table.table_number}</div>
                                    <div style="font-size: 12px; color: #666;">Capacity: ${table.current_capacity}</div>
                                </div>
                            `;
                        });
                        html += '</div>';
                        resultsDiv.innerHTML = html;
                    } else {
                        resultsDiv.innerHTML = '<p style="color: #721c24; background: #f8d7da; padding: 15px; border-radius: 4px;">No tables available for the selected date and time.</p>';
                    }
                });
        }

        // Open availability modal
        function openAvailabilityModal() {
            const today = new Date().toISOString().split('T')[0];
            document.getElementById('availDate').value = today;
            document.getElementById('availabilityModal').classList.add('show');
        }

        // Close availability modal
        function closeAvailabilityModal() {
            document.getElementById('availabilityModal').classList.remove('show');
        }

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

</html>
