<!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="Bookings 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>Bookings 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;
        }

        .admin-name {
            font-size: 11px;
            opacity: 0.8;
            margin-top: 8px;
            padding-top: 8px;
            border-top: 1px solid rgba(255, 255, 255, 0.2);
        }

        .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: rgba(255, 255, 255, 0.8);
            text-decoration: none;
            transition: all 0.3s ease;
            font-weight: 500;
            border-left: 3px solid transparent;
        }

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

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

        .sidebar-menu i {
            width: 20px;
            text-align: center;
            font-size: 16px;
        }

        .notification-badge {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            min-width: 20px;
            height: 20px;
            padding: 0 6px;
            background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
            color: white;
            border-radius: 10px;
            font-size: 11px;
            font-weight: 700;
            margin-left: auto;
            animation: badgePulse 2s infinite;
        }

        .notification-badge.hidden {
            display: none;
        }

        @keyframes badgePulse {
            0%, 100% {
                box-shadow: 0 0 0 0 rgba(231, 76, 60, 0.7);
            }
            50% {
                box-shadow: 0 0 0 10px rgba(231, 76, 60, 0);
            }
        }

        .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);
        }

        /* 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;
            margin-top: 70px;
            padding: 30px;
            min-height: calc(100vh - 70px);
        }

        .content-section {
            background: white;
            border-radius: 10px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .admin-create-booking {
            border: 1px solid #eee;
            border-radius: 10px;
            padding: 18px;
            margin-bottom: 22px;
            background: #fafafa;
        }

        .admin-create-booking h4 {
            margin: 0 0 12px 0;
            font-size: 18px;
            color: #2c3e50;
        }

        .admin-create-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));
            gap: 10px;
        }

        .admin-create-grid input,
        .admin-create-grid select,
        .admin-create-grid textarea {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 13px;
            font-family: inherit;
            background: #fff;
        }

        .admin-create-grid textarea {
            min-height: 42px;
            resize: vertical;
        }

        .admin-create-actions {
            margin-top: 12px;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        .section-title {
            font-size: 24px;
            font-weight: 700;
            margin-bottom: 25px;
            color: #2c3e50;
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .section-title i {
            color: #d4a574;
            font-size: 28px;
        }

        .btn-group {
            display: flex;
            gap: 15px;
            margin-bottom: 25px;
            flex-wrap: wrap;
        }

        .btn-action {
            padding: 12px 25px;
            background: linear-gradient(135deg, #d4a574 0%, #8b6f47 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;
            gap: 8px;
        }

        .btn-action:hover {
            background: linear-gradient(135deg, #8b6f47 0%, #5d4a2f 100%);
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(212, 165, 116, 0.3);
        }

        /* Tables */
        .table-responsive {
            overflow-x: auto;
            margin-top: 20px;
        }

        .admin-table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            border-radius: 8px;
            overflow: hidden;
        }

        .admin-table thead {
            background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            color: white;
        }

        .admin-table th {
            padding: 15px;
            text-align: left;
            font-weight: 600;
            font-size: 13px;
            letter-spacing: 0.5px;
        }

        .admin-table td {
            padding: 15px;
            border-bottom: 1px solid #e8e8e8;
            font-size: 13px;
        }

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

        .status-badge {
            padding: 6px 12px;
            border-radius: 4px;
            font-weight: 600;
            font-size: 12px;
            display: inline-block;
        }

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

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

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

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

        .status-badge.checked_out {
            background: #c3e6cb;
            color: #155724;
        }

        .btn-view {
            padding: 8px 12px;
            background: #d1ecf1;
            color: #0c5460;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-weight: 600;
            font-size: 12px;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }

        .btn-view:hover {
            background: #bee5eb;
            transform: translateY(-2px);
        }

        .btn-approve {
            padding: 8px 12px;
            background: #d4edda;
            color: #155724;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-weight: 600;
            font-size: 12px;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }

        .btn-approve:hover {
            background: #28a745;
            color: white;
            transform: translateY(-2px);
        }

        .btn-reject {
            padding: 8px 12px;
            background: #f8d7da;
            color: #721c24;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-weight: 600;
            font-size: 12px;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 6px;
        }

        .btn-reject:hover {
            background: #dc3545;
            color: white;
            transform: translateY(-2px);
        }

        /* Loader Animation */
        .loader {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #d4a574;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto;
        }

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

        /* Overlay for mobile menu */
        .overlay {
            display: none;
            position: fixed;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.3);
            z-index: 900;
        }

        .overlay.active {
            display: block;
        }

        .sidebar.active {
            transform: translateX(0);
        }

        /* Admin Calendar Styles */
        #adminCalendarGrid > div {
            aspect-ratio: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            min-width: 0;
            overflow: hidden;
            border-radius: 4px;
            cursor: pointer;
            font-weight: 500;
            line-height: 1;
            transition: all 0.2s ease;
            background: white;
            border: 1px solid #e0e0e0;
            color: #333;
        }

        #adminCalendarGrid > div:hover {
            background: #f0f0f0;
            border-color: #d4a574;
        }

        #adminCalendarGrid > div.day-header {
            aspect-ratio: auto;
            min-height: 30px;
            background: #f5f5f5;
            color: #666;
            font-weight: 700;
            cursor: default;
            border: 1px solid #e0e0e0;
            font-size: 11px;
        }

        #adminCalendarGrid > div.day-header:hover {
            background: #f5f5f5;
            border-color: #e0e0e0;
        }

        #adminCalendarGrid > div.other-month {
            color: #ccc;
            background: #fafafa;
            cursor: not-allowed;
        }

        #adminCalendarGrid > div.other-month:hover {
            background: #fafafa;
            border-color: #e0e0e0;
        }

        #adminCalendarGrid > div.selected {
            background: #d4a574;
            color: white;
            border-color: #c59d5f;
            font-weight: 700;
        }

        #adminCalendarGrid > div.today {
            border: 2px solid #3498db;
        }

        #adminCalendarGrid > div.today.selected {
            border: 2px solid #fff;
        }

        /* Responsive Calendar Styles */
        #adminCalendarContainer {
            width: 100%;
            box-sizing: border-box;
            background: #f9f9f9;
            padding: 15px;
            border-radius: 8px;
            border: 1px solid #e0e0e0;
        }

        #adminCalendarGrid {
            display: grid !important;
            grid-template-columns: repeat(7, minmax(0, 1fr)) !important;
            gap: 5px !important;
            font-size: 12px;
            width: 100%;
        }

        /* Extra Large Desktop (1400px+) */
        @media (min-width: 1401px) {
            #adminCalendarGrid > div {
                font-size: 13px !important;
                padding: 8px !important;
            }
        }

        /* Large Desktop (1025px - 1400px) */
        @media (min-width: 1025px) and (max-width: 1400px) {
            #adminCalendarGrid > div {
                font-size: 12px !important;
                padding: 6px !important;
            }
        }

        /* Large Tablet (769px - 1024px) */
        @media (max-width: 1024px) and (min-width: 769px) {
            #adminCalendarGrid > div {
                font-size: 11px !important;
                padding: 5px !important;
            }

            #adminCalendarGrid > div.day-header {
                font-size: 10px !important;
            }
        }

        /* Tablet (481px - 768px) */
        @media (max-width: 768px) and (min-width: 481px) {
            #adminCalendarGrid {
                grid-template-columns: repeat(7, 1fr) !important;
                gap: 4px !important;
            }

            #adminCalendarGrid > div {
                font-size: 10px !important;
                padding: 4px !important;
                min-height: 32px !important;
            }

            #adminCalendarGrid > div.day-header {
                font-size: 9px !important;
                min-height: 28px !important;
            }

            #adminCalendarContainer {
                padding: 10px !important;
            }
        }

        /* Mobile (Landscape & Small Tablets - 481px) */
        @media (max-width: 480px) {
            #adminCalendarGrid {
                grid-template-columns: repeat(7, 1fr) !important;
                gap: 3px !important;
            }

            #adminCalendarGrid > div {
                font-size: 8px !important;
                padding: 3px !important;
                min-height: 25px !important;
            }

            #adminCalendarGrid > div.day-header {
                font-size: 7px !important;
                min-height: 22px !important;
                padding: 2px !important;
            }

            #adminCalendarContainer {
                padding: 8px !important;
            }

            /* Calendar navigation buttons - smaller on mobile */
            #adminCalendarContainer button {
                padding: 4px 6px !important;
                font-size: 10px !important;
            }

            /* Month/year display */
            #currentMonthYearAdmin {
                font-size: 12px !important;
                min-width: auto !important;
            }
        }

        /* Ultra Small Mobile (max 360px) */
        @media (max-width: 360px) {
            #adminCalendarGrid {
                grid-template-columns: repeat(7, 1fr) !important;
                gap: 2px !important;
            }

            #adminCalendarGrid > div {
                font-size: 7px !important;
                padding: 2px !important;
                min-height: 22px !important;
            }

            #adminCalendarGrid > div.day-header {
                font-size: 6px !important;
                min-height: 19px !important;
                padding: 1px !important;
            }

            #adminCalendarContainer {
                padding: 6px !important;
                margin: 0 -5px;
            }

            #adminCalendarContainer button {
                padding: 3px 4px !important;
                font-size: 9px !important;
            }
        }

        /* Available Table Card Styles */
        .available-table-card-admin {
            background: white;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            padding: 12px;
            text-align: center;
            cursor: default;
            transition: all 0.2s ease;
        }

        .available-table-card-admin:hover {
            border-color: #d4a574;
            box-shadow: 0 2px 8px rgba(212, 165, 116, 0.3);
        }

        .available-table-card-admin .table-name {
            font-size: 16px;
            font-weight: 700;
            color: #333;
            margin-bottom: 6px;
        }

        .available-table-card-admin .table-info {
            font-size: 12px;
            color: #777;
            margin: 3px 0;
        }

        .available-table-card-admin .table-capacity {
            background: #d4a574;
            color: white;
            padding: 4px 8px;
            border-radius: 3px;
            display: inline-block;
            font-size: 11px;
            margin-top: 6px;
            font-weight: 600;
        }

        /* Available Tables for Selected Date - Comprehensive Responsive */
        #availableTablesForDateContainer {
            display: grid !important;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)) !important;
            gap: 12px !important;
            min-height: 200px !important;
        }

        .booking-calendar-wrapper {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 30px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .calendar-tables-grid {
            display: grid;
            grid-template-columns: minmax(280px, 1fr) minmax(0, 2fr);
            gap: 30px;
            align-items: start;
            width: 100%;
        }

        .calendar-panel {
            min-width: 0;
        }

        #currentMonthYearAdmin {
            margin: 0;
            color: #333;
            font-size: 14px;
            text-align: center;
            flex: 1;
            min-width: 0;
            padding: 0 6px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .calendar-section-title {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 15px;
            color: #333;
        }

        .calendar-header-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 10px;
            margin-bottom: 15px;
        }

        .calendar-nav-btn {
            padding: 6px 12px;
            background: #d4a574;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            flex-shrink: 0;
        }

        .selected-date-panel {
            margin-top: 12px;
            padding: 10px;
            background: #e8f4f8;
            border-left: 3px solid #3498db;
            border-radius: 3px;
        }

        .selected-date-label {
            margin: 0;
            font-size: 12px;
            color: #555;
        }

        .tables-empty-state {
            grid-column: 1/-1;
            text-align: center;
            color: #999;
            padding: 40px 20px;
        }

        /* Extra Large Desktop (1400px+) */
        @media (min-width: 1401px) {
            #availableTablesForDateContainer {
                grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)) !important;
                gap: 15px !important;
            }
        }

        /* Large Desktop (1200px - 1400px) */
        @media (min-width: 1201px) and (max-width: 1400px) {
            #availableTablesForDateContainer {
                grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)) !important;
                gap: 12px !important;
            }
        }

        /* Desktop (1025px - 1200px) */
        @media (min-width: 1025px) and (max-width: 1200px) {
            #availableTablesForDateContainer {
                grid-template-columns: repeat(auto-fill, minmax(170px, 1fr)) !important;
                gap: 11px !important;
            }
        }

        /* Large Tablet (769px - 1024px) */
        @media (max-width: 1024px) and (min-width: 769px) {
            #availableTablesForDateContainer {
                grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)) !important;
                gap: 10px !important;
                min-height: 150px !important;
            }

            .available-table-card-admin {
                padding: 10px;
            }

            .available-table-card-admin .table-name {
                font-size: 14px;
            }

            .available-table-card-admin .table-info {
                font-size: 11px;
            }
        }

        /* Tablet (481px - 768px) */
        @media (max-width: 768px) and (min-width: 481px) {
            #availableTablesForDateContainer {
                grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)) !important;
                gap: 8px !important;
                min-height: 120px !important;
            }

            .available-table-card-admin {
                padding: 8px;
            }

            .available-table-card-admin .table-name {
                font-size: 13px;
            }

            .available-table-card-admin .table-info {
                font-size: 10px;
            }

            .available-table-card-admin .table-capacity {
                font-size: 9px;
                padding: 3px 5px;
            }
        }

        /* Mobile Landscape (360px - 480px) */
        @media (max-width: 480px) and (min-width: 361px) {
            #availableTablesForDateContainer {
                grid-template-columns: repeat(auto-fill, minmax(110px, 1fr)) !important;
                gap: 6px !important;
                min-height: 100px !important;
            }

            .available-table-card-admin {
                padding: 7px;
            }

            .available-table-card-admin .table-name {
                font-size: 12px;
                margin-bottom: 4px;
            }

            .available-table-card-admin .table-info {
                font-size: 9px;
                margin: 2px 0;
            }

            .available-table-card-admin .table-capacity {
                font-size: 8px;
                padding: 2px 4px;
                margin-top: 4px;
            }
        }

        /* Ultra Small Mobile (max 360px) */
        @media (max-width: 360px) {
            #availableTablesForDateContainer {
                grid-template-columns: repeat(auto-fill, minmax(95px, 1fr)) !important;
                gap: 4px !important;
                min-height: 80px !important;
            }

            .available-table-card-admin {
                padding: 6px;
            }

            .available-table-card-admin .table-name {
                font-size: 11px;
                margin-bottom: 3px;
            }

            .available-table-card-admin .table-info {
                font-size: 8px;
                margin: 1px 0;
            }

            .available-table-card-admin .table-capacity {
                font-size: 7px;
                padding: 2px 3px;
                margin-top: 3px;
            }
        }

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

            .topbar {
                left: 250px;
            }

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

            /* Calendar and Tables Section - Responsive */
            .calendar-tables-grid {
                grid-template-columns: 1fr !important;
                gap: 16px !important;
            }

            .booking-calendar-wrapper {
                padding: 16px;
            }
        }

        @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;
            }

            .topbar {
                left: 0;
            }

            .main-content {
                margin-left: 0;
            }

            .menu-toggle {
                display: block;
            }

            .admin-table {
                font-size: 12px;
            }

            .admin-table th,
            .admin-table td {
                padding: 10px;
            }

            #adminCalendarContainer {
                padding: 12px;
            }

            #availableTablesForDateContainer {
                grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)) !important;
            }

            .calendar-header-row {
                gap: 8px;
            }

            /* Section heading responsive */
            .content-section > div > div:first-child {
                font-size: 15px !important;
            }

            /* Calendar heading */
            .calendar-tables-grid > div:first-child > div:first-child {
                font-size: 14px !important;
                margin-bottom: 12px !important;
            }

            /* Tables heading */
            .calendar-tables-grid > div:last-child > div:first-child {
                font-size: 14px !important;
                margin-bottom: 12px !important;
            }
        }

        @media (max-width: 576px) {
            .topbar-title {
                font-size: 18px;
            }

            .main-content {
                padding: 15px;
            }

            .content-section {
                padding: 15px;
            }

            .btn-group {
                flex-direction: column;
            }

            .btn-action {
                width: 100%;
            }

            /* Calendar and Tables Section - Extra Small Mobile */
            .calendar-tables-grid {
                grid-template-columns: 1fr !important;
                gap: 10px !important;
            }

            .booking-calendar-wrapper {
                padding: 12px;
            }

            #adminCalendarContainer {
                padding: 8px;
                margin-bottom: 10px;
            }

            /* Calendar navigation buttons */
            #adminCalendarContainer button {
                padding: 4px 8px !important;
                font-size: 11px !important;
            }

            .calendar-nav-btn {
                min-width: 34px;
                padding: 4px 8px;
            }

            /* Calendar month/year display */
            #currentMonthYearAdmin {
                font-size: 13px !important;
                min-width: auto !important;
            }

            /* Calendar grid cells */
            #adminCalendarGrid > div {
                font-size: 9px !important;
                padding: 2px !important;
                min-height: 28px;
            }

            #adminCalendarGrid > div.day-header {
                font-size: 8px !important;
                min-height: 24px;
            }

            /* Calendar container section heading */
            #adminCalendarContainer + div {
                padding: 8px !important;
                margin-top: 10px;
            }

            /* Selected date display */
            #selectedDateDisplayAdmin {
                font-size: 13px !important;
            }

            /* Available tables section */
            #availableTablesForDateContainer {
                grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)) !important;
                gap: 8px !important;
            }

            .available-table-card-admin {
                padding: 8px !important;
            }

            .available-table-card-admin .table-name {
                font-size: 14px !important;
            }

            .available-table-card-admin .table-info {
                font-size: 11px !important;
            }

            .available-table-card-admin .table-capacity {
                font-size: 10px !important;
                padding: 3px 6px !important;
            }

            /* Booking table responsive */
            .admin-table {
                font-size: 11px;
            }

            .admin-table th,
            .admin-table td {
                padding: 8px;
            }

            .btn-approve,
            .btn-reject {
                padding: 6px 8px;
                font-size: 11px;
            }

            /* Overall section card padding */
            .content-section {
                padding: 12px !important;
            }

            .calendar-tables-grid > div {
                width: 100% !important;
            }
        }

        @media (max-width: 420px) {
            .calendar-section-title {
                font-size: 14px;
                margin-bottom: 10px;
            }

            .calendar-header-row {
                margin-bottom: 10px;
            }

            #adminCalendarContainer {
                padding: 6px !important;
            }

            #adminCalendarGrid {
                gap: 2px !important;
            }

            #adminCalendarGrid > div {
                font-size: 8px !important;
                min-height: 22px !important;
            }

            #adminCalendarGrid > div.day-header {
                font-size: 7px !important;
                min-height: 18px !important;
            }

            #availableTablesForDateContainer {
                grid-template-columns: repeat(auto-fill, minmax(105px, 1fr)) !important;
                gap: 6px !important;
            }

            .tables-empty-state {
                padding: 20px 10px;
                font-size: 12px;
            }
        }

        /* Modal Styles */
        .modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 2000;
        }

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

        /* Keep SweetAlert above custom assignment modal */
        .swal2-container {
            z-index: 3000 !important;
        }

        .modal-content {
            background: white;
            border-radius: 8px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.3);
            animation: slideIn 0.3s ease;
            width: 90%;
            max-height: 90vh;
            overflow-y: auto;
        }

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

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

        .modal-header h3 {
            margin: 0;
            font-size: 20px;
            color: #333;
        }

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

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

        .modal-body {
            padding: 20px;
        }

        .modal-footer {
            border-top: 1px solid #e0e0e0;
            padding: 15px 20px;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

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

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

        .btn-primary:hover {
            background: #8b6f47;
            transform: translateY(-2px);
        }

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

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

        /* Available Tables Cards */
        .table-card {
            background: white;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 15px;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .table-card:hover {
            border-color: #d4a574;
            box-shadow: 0 4px 12px rgba(212, 165, 116, 0.2);
            transform: translateY(-2px);
        }

        .table-card-header {
            display: flex;
            justify-content: space-between;
            align-items: start;
            gap: 10px;
        }

        .table-card-name {
            font-size: 16px;
            font-weight: 700;
            color: #333;
        }

        .table-card-capacity {
            background: #d4a574;
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 600;
        }

        .table-card-info {
            display: flex;
            flex-direction: column;
            gap: 5px;
            font-size: 13px;
            color: #666;
        }

        .table-card-info-row {
            display: flex;
            justify-content: space-between;
        }

        .table-card-info-label {
            font-weight: 600;
            color: #333;
        }

        .assign-btn {
            background: #d4a574;
            color: white;
            border: none;
            padding: 8px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-weight: 600;
            font-size: 12px;
            width: 100%;
            transition: all 0.3s ease;
        }

        .assign-btn:hover {
            background: #8b6f47;
            transform: translateY(-2px);
        }

        /* Content sections responsive */
        .content-section {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 30px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        @media (max-width: 768px) {
            .content-section {
                padding: 15px;
                margin-bottom: 20px;
            }
        }

        @media (max-width: 576px) {
            .content-section {
                padding: 12px;
                margin-bottom: 15px;
            }
        }

        /* Responsive Available Tables Section */
        #availableTablesContainer {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 15px;
        }

        @media (max-width: 1200px) {
            #availableTablesContainer {
                grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            }
        }

        @media (max-width: 768px) {
            #availableTablesContainer {
                grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
                gap: 12px;
            }
        }

        @media (max-width: 576px) {
            #availableTablesContainer {
                grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
                gap: 8px;
            }

            .table-card {
                padding: 10px !important;
            }

            .table-card-header {
                flex-direction: column !important;
                gap: 4px !important;
            }

            .table-card-name {
                font-size: 14px !important;
            }

            .table-card-capacity {
                font-size: 11px !important;
            }

            .table-card-info {
                gap: 4px !important;
            }

            .table-card-info-row {
                font-size: 11px !important;
            }
        }
    </style>
</head>

<body>
    <!-- Overlay for mobile menu -->
    <div id="menuOverlay" class="overlay"></div>

    <!-- 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="menu.php"><i class="fas fa-utensils"></i> <span>Menu</span></a></li>
            <li><a href="tables.php"><i class="fas fa-chair"></i> <span>Dine-in Tables</span></a></li>
            <li><a href="online_tables.php"><i class="fas fa-laptop"></i> <span>Online Tables</span></a></li>
            <li><a href="bookings.php" class="active"><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>

    <!-- Top Header -->
    <div class="topbar">
        <div style="display: flex; align-items: center; gap: 20px;">
            <button class="menu-toggle" id="menuToggle">
                <i class="fas fa-bars"></i>
            </button>
            <div class="topbar-title">Bookings</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">
        <div class="content-section">
            <div class="section-title">
                <i class="fas fa-calendar-check"></i>
                Manage Bookings
            </div>

            <div class="admin-create-booking">
                <h4><i class="fas fa-plus-circle" style="color:#d4a574; margin-right:8px;"></i>Create Booking (Admin)</h4>
                <form id="adminCreateBookingForm">
                    <div class="admin-create-grid">
                        <input type="text" id="createBookingName" placeholder="Customer Name *" required>
                        <input type="email" id="createBookingEmail" placeholder="Email *" required>
                        <input type="text" id="createBookingPhone" placeholder="Phone *" required>
                        <input type="date" id="createBookingDate" required>
                        <input type="number" id="createBookingGuests" placeholder="Guests *" min="1" required>
                        <select id="createBookingMealType" required>
                            <option value="">Meal Type *</option>
                        </select>
                        <select id="createBookingSlotTime" required>
                            <option value="">Slot Time *</option>
                        </select>
                        <select id="createBookingTableType">
                            <option value="online" selected>Online Table</option>
                            <option value="dine-in">Dine-in Table</option>
                        </select>
                        <select id="createBookingStatus">
                            <option value="confirmed" selected>Confirmed</option>
                            <option value="pending">Pending</option>
                            <option value="checked_in">Checked In</option>
                        </select>
                        <input type="text" id="createBookingDietary" placeholder="Dietary Needs">
                        <textarea id="createBookingRequests" placeholder="Special Requests"></textarea>
                    </div>
                    <div class="admin-create-actions">
                        <button type="button" class="btn-action" id="resetCreateBookingBtn" style="background:#7f8c8d;">
                            <i class="fas fa-undo"></i> Reset
                        </button>
                        <button type="submit" class="btn-action">
                            <i class="fas fa-save"></i> Create Booking
                        </button>
                    </div>
                </form>
            </div>

            <!-- Calendar and Tables Section -->
            <div class="booking-calendar-wrapper">
                <div class="calendar-tables-grid">
                    <!-- Calendar Section -->
                    <div class="calendar-panel">
                        <div class="calendar-section-title">
                            <i class="fas fa-calendar"></i> Select Date
                        </div>
                        <div id="adminCalendarContainer">
                            <div class="calendar-header-row">
                                <button id="prevMonthBtnAdmin" class="calendar-nav-btn">
                                    <i class="fas fa-chevron-left"></i>
                                </button>
                                <h4 id="currentMonthYearAdmin">February 2026</h4>
                                <button id="nextMonthBtnAdmin" class="calendar-nav-btn">
                                    <i class="fas fa-chevron-right"></i>
                                </button>
                            </div>
                            <div id="adminCalendarGrid">
                                <!-- Calendar will be populated by JavaScript -->
                            </div>
                        </div>
                        <div class="selected-date-panel">
                            <p class="selected-date-label"><strong>Selected Date:</strong></p>
                            <p id="selectedDateDisplayAdmin" style="margin: 5px 0 0 0; font-size: 14px; color: #d4a574; font-weight: 600;">Today</p>
                        </div>
                    </div>

                    <!-- Available Tables for Selected Date -->
                    <div class="calendar-panel">
                        <div class="calendar-section-title">
                            <i class="fas fa-table"></i> Table Status for <span id="tablesDateDisplay">Today</span>
                        </div>
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 12px;">
                            <div>
                                <label for="adminMealTypeSelect" style="display:block; font-size:12px; color:#666; margin-bottom:4px;">Meal Type</label>
                                <select id="adminMealTypeSelect" style="width:100%; padding:8px 10px; border:1px solid #ddd; border-radius:6px; font-size:13px;">
                                    <option value="">-- Select meal type --</option>
                                </select>
                            </div>
                            <div>
                                <label for="adminSlotSelect" style="display:block; font-size:12px; color:#666; margin-bottom:4px;">Slot</label>
                                <select id="adminSlotSelect" style="width:100%; padding:8px 10px; border:1px solid #ddd; border-radius:6px; font-size:13px;" disabled>
                                    <option value="">-- Select slot --</option>
                                </select>
                            </div>
                        </div>
                        <div id="availableTablesForDateContainer" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 12px; min-height: 200px;">
                            <div class="tables-empty-state">
                                Select date, meal type, and slot to view table status
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- <div class="btn-group">
                <button class="btn-action">
                    <i class="fas fa-plus"></i> New Booking
                </button>
                <button class="btn-action">
                    <i class="fas fa-download"></i> Export
                </button>
            </div> -->
            <div class="table-responsive">
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Phone</th>
                            <th>Booking Date</th>
                            <th>Slot Time</th>
                            <th>Guests</th>
                            <th>Meal Type</th>
                            <th>Assigned Table</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="bookingsTable">
                        <tr>
                            <td colspan="10" style="text-align: center; color: #999;">Loading bookings...</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Table Assignment Modal -->
    <div id="assignTableModal" class="modal" style="display: none;">
        <div class="modal-content" style="max-width: 500px;">
            <div class="modal-header">
                <h3>Assign Table to Booking</h3>
                <button class="close-btn" onclick="closeAssignModal()">×</button>
            </div>
            <div class="modal-body">
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Booking Details:</label>
                    <div id="bookingDetails" style="background: #f5f5f5; padding: 15px; border-radius: 4px; margin-bottom: 15px;">
                        <p style="margin: 5px 0;"><strong>Name:</strong> <span id="assignBookingName">-</span></p>
                        <p style="margin: 5px 0;"><strong>Guests:</strong> <span id="assignBookingGuests">-</span></p>
                        <p style="margin: 5px 0;"><strong>Date:</strong> <span id="assignBookingDate">-</span></p>
                        <p style="margin: 5px 0;"><strong>Time:</strong> <span id="assignBookingTime">-</span></p>
                    </div>
                    <div id="bookingSeatProgressBox" style="background:#fff8e8; border:1px solid #efd6a8; border-radius:6px; padding:10px 12px; margin-top:10px; font-size:13px;">
                        <p style="margin:2px 0;"><strong>Seat Progress:</strong> <span id="bookingSeatProgressText">Loading...</span></p>
                        <p style="margin:2px 0; color:#8b6f47;">Required: <strong id="bookingRequiredSeats">0</strong> | Assigned: <strong id="bookingAssignedSeats">0</strong> | Remaining: <strong id="bookingRemainingSeats">0</strong></p>
                        <p id="bookingSeatPreview" style="margin:6px 0 0 0; color:#2c3e50; display:none;"></p>
                    </div>
                </div>
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">
                        Select Available Table(s) for Booking Date:
                    </label>
                    <p style="margin: 0 0 10px 0; font-size: 13px; color: #666; padding: 10px; background: #e8f4f8; border-left: 3px solid #3498db; border-radius: 3px;">
                        <i class="fas fa-info-circle"></i> Showing tables available for <strong id="tableFilterDateInfo">-</strong>
                    </p>
                    <div id="assignTableCheckboxes" style="max-height: 220px; overflow-y: auto; border: 1px solid #ddd; border-radius: 6px; padding: 8px; background: #fff;">
                        <div style="font-size: 13px; color: #777; padding: 8px;">Loading tables...</div>
                    </div>
                    <p id="selectedTablesSummary" style="margin: 10px 0 0 0; font-size: 13px; color: #2c3e50;"></p>
                </div>
            </div>
            <div class="modal-footer" style="display: flex; gap: 10px; justify-content: flex-end; padding: 15px; border-top: 1px solid #e0e0e0;">
                <button class="btn btn-secondary" onclick="closeAssignModal()" style="padding: 8px 20px; border: 1px solid #ddd; background: #fff; color: #333; border-radius: 4px; cursor: pointer;">Cancel</button>
                <button class="btn btn-primary" onclick="confirmTableAssignment()" style="padding: 8px 20px; background: #d4a574; color: white; border: none; border-radius: 4px; cursor: pointer;">Assign Table</button>
            </div>
        </div>
    </div>

    <!-- Modal Overlay -->
    <div id="modalOverlay" class="modal-overlay" style="display: none;" onclick="if(!isConfirmationDialogOpen) closeAssignModal()"></div>

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <!-- SweetAlert2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>

    <!-- Bookings Page Script -->
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Check admin authentication
            const adminUser = localStorage.getItem('admin_user');
            if (!adminUser) {
                window.location.href = 'login.php';
                return;
            }

            const admin = JSON.parse(adminUser);
            
            // Update header with admin info
            document.getElementById('sidebarAdminName').textContent = admin.name;
            document.getElementById('topbarUserName').textContent = admin.name;
            document.getElementById('userInitial').textContent = admin.name.charAt(0).toUpperCase();

            // Load bookings on page load
            loadBookings();
            loadNotificationCount();
            
            // Initialize admin calendar for date selection
            initializeAdminCalendar();

            setupAdminCreateBookingForm();

            // Mobile menu toggle
            const menuToggle = document.getElementById('menuToggle');
            const sidebar = document.getElementById('sidebar');
            const overlay = document.getElementById('menuOverlay');

            if (menuToggle && sidebar && overlay) {
                menuToggle.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    sidebar.classList.toggle('active');
                    overlay.classList.toggle('active');
                });

                overlay.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    sidebar.classList.remove('active');
                    overlay.classList.remove('active');
                });

                document.addEventListener('click', function(e) {
                    if (sidebar.classList.contains('active') && 
                        !sidebar.contains(e.target) && 
                        !menuToggle.contains(e.target)) {
                        sidebar.classList.remove('active');
                        overlay.classList.remove('active');
                    }
                });
            }

            // Logout
            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';
                        });
                    }
                });
            });


        });

        function setupAdminCreateBookingForm() {
            const form = document.getElementById('adminCreateBookingForm');
            const resetBtn = document.getElementById('resetCreateBookingBtn');
            const dateInput = document.getElementById('createBookingDate');
            const mealTypeSelect = document.getElementById('createBookingMealType');
            const slotSelect = document.getElementById('createBookingSlotTime');

            if (!form) return;

            const now = new Date();
            const yyyy = now.getFullYear();
            const mm = String(now.getMonth() + 1).padStart(2, '0');
            const dd = String(now.getDate()).padStart(2, '0');
            if (dateInput && !dateInput.value) {
                dateInput.value = `${yyyy}-${mm}-${dd}`;
            }

            async function loadCreateBookingSlotsByMealType(mealTypeId) {
                if (!slotSelect) return;
                slotSelect.innerHTML = '<option value="">Slot Time *</option>';
                slotSelect.disabled = true;

                if (!mealTypeId) return;

                try {
                    const response = await fetch(`../backend/meal_slots_api.php?action=get_slots&meal_type_id=${encodeURIComponent(mealTypeId)}`);
                    const data = await response.json();
                    if (!data.success || !Array.isArray(data.data)) return;

                    const activeSlots = data.data.filter(slot => String(slot.status || '').toLowerCase() === 'active');
                    activeSlots.forEach(slot => {
                        const startTime = String(slot.start_time || '').substring(0, 8);
                        if (!startTime) return;
                        const option = document.createElement('option');
                        option.value = startTime;
                        option.textContent = slot.slot_name || `${startTime.substring(0, 5)} - ${String(slot.end_time || '').substring(0, 5)}`;
                        slotSelect.appendChild(option);
                    });

                    if (activeSlots.length > 0) {
                        slotSelect.disabled = false;
                        slotSelect.value = activeSlots[0].start_time;
                    }
                } catch (e) {
                    console.error('Failed to load create-booking slots:', e);
                }
            }

            async function loadCreateBookingMealTypes() {
                if (!mealTypeSelect) return;
                mealTypeSelect.innerHTML = '<option value="">Meal Type *</option>';
                if (slotSelect) {
                    slotSelect.innerHTML = '<option value="">Slot Time *</option>';
                    slotSelect.disabled = true;
                }

                try {
                    const response = await fetch('../backend/meal_slots_api.php?action=get_meal_types');
                    const data = await response.json();
                    if (!data.success || !Array.isArray(data.data)) return;

                    const activeMeals = data.data.filter(meal => String(meal.status || '').toLowerCase() === 'active');
                    activeMeals.forEach(meal => {
                        const option = document.createElement('option');
                        option.value = meal.id;
                        option.textContent = meal.name;
                        option.dataset.mealName = String(meal.name || '').trim().toLowerCase();
                        mealTypeSelect.appendChild(option);
                    });

                    if (activeMeals.length > 0) {
                        mealTypeSelect.value = String(activeMeals[0].id);
                        await loadCreateBookingSlotsByMealType(activeMeals[0].id);
                    }
                } catch (e) {
                    console.error('Failed to load create-booking meal types:', e);
                }
            }

            loadCreateBookingMealTypes();

            if (mealTypeSelect) {
                mealTypeSelect.addEventListener('change', function() {
                    loadCreateBookingSlotsByMealType(this.value);
                });
            }

            form.addEventListener('submit', async function(e) {
                e.preventDefault();

                const selectedMealOption = mealTypeSelect ? mealTypeSelect.options[mealTypeSelect.selectedIndex] : null;
                const mealTypeName = selectedMealOption ? (selectedMealOption.dataset.mealName || '').trim() : '';

                const payload = {
                    action: 'create_booking',
                    name: document.getElementById('createBookingName').value.trim(),
                    email: document.getElementById('createBookingEmail').value.trim(),
                    phone: document.getElementById('createBookingPhone').value.trim(),
                    booking_date: document.getElementById('createBookingDate').value,
                    slot_time: slotSelect ? slotSelect.value : '',
                    guests: parseInt(document.getElementById('createBookingGuests').value, 10) || 0,
                    meal_type: mealTypeName,
                    table_type: document.getElementById('createBookingTableType').value,
                    status: document.getElementById('createBookingStatus').value,
                    dietary_needs: document.getElementById('createBookingDietary').value.trim(),
                    special_requests: document.getElementById('createBookingRequests').value.trim()
                };

                if (!payload.name || !payload.email || !payload.phone || !payload.booking_date || !payload.slot_time || payload.guests <= 0 || !payload.meal_type) {
                    Swal.fire('Error', 'Please fill all required fields', 'error');
                    return;
                }

                Swal.fire({
                    title: 'Creating booking...',
                    html: '<div class="loader"></div>',
                    allowOutsideClick: false,
                    didOpen: () => Swal.showLoading()
                });

                try {
                    const response = await fetch('../backend/admin_bookings_api.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(payload)
                    });
                    const data = await response.json();
                    Swal.close();

                    if (data.success) {
                        Swal.fire('Success', data.message || 'Booking created', 'success');
                        form.reset();
                        const current = new Date();
                        const cY = current.getFullYear();
                        const cM = String(current.getMonth() + 1).padStart(2, '0');
                        const cD = String(current.getDate()).padStart(2, '0');
                        if (dateInput) dateInput.value = `${cY}-${cM}-${cD}`;
                        loadBookings();
                        loadNotificationCount();
                    } else {
                        Swal.fire('Error', data.message || 'Failed to create booking', 'error');
                    }
                } catch (error) {
                    Swal.close();
                    Swal.fire('Error', 'Failed to create booking', 'error');
                }
            });

            if (resetBtn) {
                resetBtn.addEventListener('click', function() {
                    form.reset();
                    const current = new Date();
                    const cY = current.getFullYear();
                    const cM = String(current.getMonth() + 1).padStart(2, '0');
                    const cD = String(current.getDate()).padStart(2, '0');
                    if (dateInput) dateInput.value = `${cY}-${cM}-${cD}`;
                    loadCreateBookingMealTypes();
                });
            }
        }


        // Admin Calendar Functions
        let adminCalendarCurrentDate = new Date();
        let adminSelectedDate = new Date();
        let adminSelectedDateStr = '';
        let selectedMealTypeName = '';
        let selectedSlotTime = '';
        let selectedSlotLabel = '';
        adminSelectedDate.setHours(0, 0, 0, 0); // Set to midnight for consistent date comparison
        adminCalendarCurrentDate.setHours(0, 0, 0, 0);

        function initializeAdminCalendar() {
            renderAdminCalendar();
            setupAdminCalendarNavigation();
            setupMealAndSlotFilters();
            
            // Load tables for today by default
            loadTablesForSelectedDate(adminSelectedDate);
        }

        function renderAdminCalendar() {
            const year = adminCalendarCurrentDate.getFullYear();
            const month = adminCalendarCurrentDate.getMonth();
            
            // Update header
            const monthNames = ['January', 'February', 'March', 'April', 'May', 'June',
                              'July', 'August', 'September', 'October', 'November', 'December'];
            document.getElementById('currentMonthYearAdmin').textContent = monthNames[month] + ' ' + year;
            
            // Get first day of month and number of days
            const firstDay = new Date(year, month, 1).getDay();
            const daysInMonth = new Date(year, month + 1, 0).getDate();
            
            // Create calendar grid
            const grid = document.getElementById('adminCalendarGrid');
            grid.innerHTML = '';
            
            // Add day headers
            const dayHeaders = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
            dayHeaders.forEach(day => {
                const dayHeaderElement = document.createElement('div');
                dayHeaderElement.className = 'day-header';
                dayHeaderElement.textContent = day;
                grid.appendChild(dayHeaderElement);
            });
            
            // Add empty cells for days before month starts
            for (let i = 0; i < firstDay; i++) {
                const emptyCell = document.createElement('div');
                emptyCell.className = 'other-month';
                emptyCell.textContent = '';
                grid.appendChild(emptyCell);
            }
            
            // Add days of the month
            const today = new Date();
            today.setHours(0, 0, 0, 0); // Set to midnight for comparison
            
            for (let day = 1; day <= daysInMonth; day++) {
                const dayCell = document.createElement('div');
                dayCell.textContent = day;
                
                const cellDate = new Date(year, month, day);
                cellDate.setHours(0, 0, 0, 0); // Set to midnight for comparison
                
                const isPastDate = cellDate < today;
                
                // Check if this is today
                if (cellDate.getTime() === today.getTime()) {
                    dayCell.classList.add('today');
                }
                
                // Check if this is selected date
                if (cellDate.getTime() === adminSelectedDate.getTime()) {
                    dayCell.classList.add('selected');
                }
                
                // Style and disable past dates
                if (isPastDate) {
                    dayCell.classList.add('other-month');
                    dayCell.style.cursor = 'not-allowed';
                    dayCell.style.opacity = '0.4';
                } else {
                    dayCell.addEventListener('click', function() {
                        adminSelectedDate = new Date(year, month, day);
                        adminSelectedDate.setHours(0, 0, 0, 0);
                        renderAdminCalendar();
                        loadTablesForSelectedDate(adminSelectedDate);
                    });
                }
                
                grid.appendChild(dayCell);
            }
        }

        function setupAdminCalendarNavigation() {
            document.getElementById('prevMonthBtnAdmin').addEventListener('click', function() {
                adminCalendarCurrentDate.setMonth(adminCalendarCurrentDate.getMonth() - 1);
                renderAdminCalendar();
            });
            
            document.getElementById('nextMonthBtnAdmin').addEventListener('click', function() {
                adminCalendarCurrentDate.setMonth(adminCalendarCurrentDate.getMonth() + 1);
                renderAdminCalendar();
            });
        }

        function loadTablesForSelectedDate(date) {
            // Format date properly without timezone conversion
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const dateStr = `${year}-${month}-${day}`;
            adminSelectedDateStr = dateStr;
            selectedMealTypeName = '';
            selectedSlotTime = '';
            selectedSlotLabel = '';
            
            const dateFormatted = date.toLocaleDateString('en-US', { 
                weekday: 'long', 
                year: 'numeric', 
                month: 'long', 
                day: 'numeric' 
            });
            
            // Update display
            document.getElementById('selectedDateDisplayAdmin').textContent = dateFormatted;
            document.getElementById('tablesDateDisplay').textContent = dateFormatted;
            
            const mealTypeSelect = document.getElementById('adminMealTypeSelect');
            const slotSelect = document.getElementById('adminSlotSelect');
            const container = document.getElementById('availableTablesForDateContainer');

            mealTypeSelect.innerHTML = '<option value="">-- Select meal type --</option>';
            slotSelect.innerHTML = '<option value="">-- Select slot --</option>';
            slotSelect.disabled = true;
            container.innerHTML = '<div class="tables-empty-state">Select meal type and slot to view table status</div>';

            loadMealTypesForSelectedDate();
        }

        function setupMealAndSlotFilters() {
            const mealTypeSelect = document.getElementById('adminMealTypeSelect');
            const slotSelect = document.getElementById('adminSlotSelect');

            mealTypeSelect.addEventListener('change', function () {
                const selectedOption = this.options[this.selectedIndex];
                selectedMealTypeName = selectedOption ? (selectedOption.dataset.mealName || '') : '';
                selectedSlotTime = '';
                selectedSlotLabel = '';

                slotSelect.innerHTML = '<option value="">-- Select slot --</option>';
                slotSelect.disabled = true;

                const container = document.getElementById('availableTablesForDateContainer');
                container.innerHTML = '<div class="tables-empty-state">Select a slot to view table status</div>';

                if (!this.value) {
                    return;
                }

                fetch(`../backend/meal_slots_api.php?action=get_slots&meal_type_id=${encodeURIComponent(this.value)}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.success && data.data && data.data.length > 0) {
                            data.data
                                .filter(slot => slot.status === 'active')
                                .forEach(slot => {
                                    const option = document.createElement('option');
                                    option.value = slot.start_time;
                                    option.textContent = slot.slot_name || `${slot.start_time} - ${slot.end_time}`;
                                    option.dataset.slotLabel = option.textContent;
                                    slotSelect.appendChild(option);
                                });
                            slotSelect.disabled = false;
                        } else {
                            container.innerHTML = '<div class="tables-empty-state">No active slots found for selected meal type</div>';
                        }
                    })
                    .catch(error => {
                        console.error('Error loading slots:', error);
                        container.innerHTML = '<div class="tables-empty-state" style="color:#c0392b;">Failed to load slots</div>';
                    });
            });

            slotSelect.addEventListener('change', function () {
                selectedSlotTime = this.value || '';
                const selectedOption = this.options[this.selectedIndex];
                selectedSlotLabel = selectedOption ? (selectedOption.dataset.slotLabel || '') : '';

                if (!adminSelectedDateStr || !selectedMealTypeName || !selectedSlotTime) {
                    return;
                }

                loadTableStatusByFilters(adminSelectedDateStr, selectedMealTypeName, selectedSlotTime, selectedSlotLabel);
            });
        }

        function loadMealTypesForSelectedDate() {
            const mealTypeSelect = document.getElementById('adminMealTypeSelect');
            const container = document.getElementById('availableTablesForDateContainer');

            fetch('../backend/meal_slots_api.php?action=get_meal_types')
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.data && data.data.length > 0) {
                        const activeMeals = data.data.filter(meal => meal.status === 'active');
                        activeMeals.forEach(meal => {
                            const option = document.createElement('option');
                            option.value = meal.id;
                            option.textContent = meal.name;
                            option.dataset.mealName = meal.name;
                            mealTypeSelect.appendChild(option);
                        });

                        if (activeMeals.length === 0) {
                            container.innerHTML = '<div class="tables-empty-state">No active meal types configured</div>';
                        }
                    } else {
                        container.innerHTML = '<div class="tables-empty-state">No meal types available</div>';
                    }
                })
                .catch(error => {
                    console.error('Error loading meal types:', error);
                    container.innerHTML = '<div class="tables-empty-state" style="color:#c0392b;">Error loading meal types</div>';
                });
        }

        function loadTableStatusByFilters(dateStr, mealTypeName, slotTime, slotLabel) {
            const container = document.getElementById('availableTablesForDateContainer');
            container.innerHTML = '<div class="tables-empty-state">Loading table status...</div>';

            const query = new URLSearchParams({
                action: 'list',
                date: dateStr,
                meal_type: mealTypeName,
                slot_time: slotTime
            }).toString();

            fetch(`../backend/online_tables_api.php?${query}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.data && data.data.length > 0) {
                        container.innerHTML = data.data.map(table => {
                            const status = (table.status || '').toLowerCase();
                            const statusColor = status === 'booked'
                                ? '#c0392b'
                                : status === 'maintenance'
                                    ? '#f39c12'
                                    : '#27ae60';
                            const statusLabel = status ? (status.charAt(0).toUpperCase() + status.slice(1)) : 'Unknown';

                            return `
                                <div class="available-table-card-admin">
                                    <div class="table-name">${table.table_number}</div>
                                    <div class="table-info">Floor ${table.floor_level}</div>
                                    <div class="table-info">${table.section || 'Not assigned'}</div>
                                    <div class="table-capacity">${table.current_capacity} Chairs</div>
                                    <div class="table-info" style="margin-top:6px; font-weight:700; color:${statusColor};">Status: ${statusLabel}</div>
                                    <div class="table-info" style="font-size:11px;">${mealTypeName} | ${slotLabel || slotTime}</div>
                                </div>
                            `;
                        }).join('');
                    } else {
                        container.innerHTML = '<div style="grid-column: 1/-1; text-align: center; color: #999; padding: 40px 20px;"><i class="fas fa-ban" style="font-size: 24px; margin-bottom: 10px; display: block;"></i>No tables found for selected date/meal/slot</div>';
                    }
                })
                .catch(error => {
                    console.error('Error loading table status:', error);
                    container.innerHTML = '<div style="grid-column: 1/-1; text-align: center; color: #c0392b; padding: 40px 20px;">Error loading table status</div>';
                });
        }

        function loadBookings() {
            console.log('Loading bookings...');
            const tableBody = document.getElementById('bookingsTable');
            tableBody.innerHTML = '<tr><td colspan="9" style="text-align: center; color: #999;">Loading bookings...</td></tr>';
            
            fetch('../backend/admin_bookings_api.php')
                .then(response => {
                    console.log('Bookings Response status:', response.status);
                    return response.json();
                })
                .then(data => {
                    console.log('Bookings API Response:', data);
                    if (data.success && data.data && data.data.length > 0) {
                        tableBody.innerHTML = data.data.map(booking => {
                            let actionButtons = '';
                            
                            if (booking.status === 'pending') {
                                // Both buttons available for pending bookings
                                actionButtons = `
                                    <button class="btn-approve" onclick="approveBooking(${parseInt(booking.id)})" title="Approve">
                                        <i class="fas fa-check"></i>
                                    </button>
                                    <button class="btn-reject" onclick="rejectBooking(${parseInt(booking.id)})" title="Reject">
                                        <i class="fas fa-times"></i>
                                    </button>
                                    <button class="btn-approve" onclick="openAssignTableModal(${parseInt(booking.id)})" title="Assign Table" style="background: #0c5460; color: #d1ecf1;">
                                        <i class="fas fa-chair"></i>
                                    </button>
                                `;
                            } else if (booking.status === 'confirmed') {
                                // Only reject button for confirmed bookings
                                actionButtons = `
                                    <button class="btn-approve" disabled style="opacity: 0.5; cursor: not-allowed;" title="Already Approved">
                                        <i class="fas fa-check"></i>
                                    </button>
                                    <button class="btn-reject" onclick="rejectBooking(${parseInt(booking.id)})" title="Reject">
                                        <i class="fas fa-times"></i>
                                    </button>
                                    <button class="btn-approve" onclick="openAssignTableModal(${parseInt(booking.id)})" title="Assign Table" style="background: #0c5460; color: #d1ecf1;">
                                        <i class="fas fa-chair"></i>
                                    </button>
                                `;
                            } else if (booking.status === 'cancelled') {
                                // Only approve button for cancelled bookings
                                actionButtons = `
                                    <button class="btn-approve" onclick="approveBooking(${parseInt(booking.id)})" title="Approve">
                                        <i class="fas fa-check"></i>
                                    </button>
                                    <button class="btn-reject" disabled style="opacity: 0.5; cursor: not-allowed;" title="Already Rejected">
                                        <i class="fas fa-times"></i>
                                    </button>
                                    <button class="btn-approve" onclick="openAssignTableModal(${parseInt(booking.id)})" title="Assign Table" style="background: #0c5460; color: #d1ecf1;">
                                        <i class="fas fa-chair"></i>
                                    </button>
                                `;
                            }
                            
                            return `
                                <tr>
                                    <td>${booking.name}</td>
                                    <td>${booking.email}</td>
                                    <td>${booking.phone}</td>
                                    <td>${new Date(booking.booking_date).toLocaleDateString()}</td>
                                    <td>${booking.slot_time}</td>
                                    <td>${booking.guests}</td>
                                    <td>${booking.meal_type}</td>
                                    <td>
                                        ${booking.assigned_tables ? 
                                            `<span style="background: #d4edda; color: #155724; padding: 6px 12px; border-radius: 4px; font-weight: 600; font-size: 12px;">${booking.assigned_tables}</span>` : 
                                            `<span style="color: #999; font-style: italic;">Not assigned</span>`
                                        }
                                    </td>
                                    <td><span class="status-badge ${booking.status}">${booking.status}</span></td>
                                    <td style="display: flex; gap: 5px;">
                                        ${actionButtons}
                                    </td>
                                </tr>
                            `;
                        }).join('');
                    } else {
                        const message = data.success === false ? 
                            `<tr><td colspan="9" style="text-align: center; color: #c0392b;">Error: ${data.message}</td></tr>` :
                            '<tr><td colspan="9" style="text-align: center; color: #999;">No bookings found</td></tr>';
                        tableBody.innerHTML = message;
                    }
                })
                .catch(error => {
                    console.error('Error loading bookings:', error);
                    tableBody.innerHTML = '<tr><td colspan="9" style="text-align: center; color: #c0392b;">Error: ' + error.message + '</td></tr>';
                });
        }

        // Function to load and display notification badge count for pending bookings
        function loadNotificationCount() {
            console.log('Loading notification count...');
            
            // Add cache-busting timestamp to ensure fresh data
            fetch('../backend/admin_bookings_api.php?action=new_count&t=' + Date.now())
                .then(response => response.json())
                .then(data => {
                    console.log('Notification count response:', data);
                    console.log('Debug info - All bookings:', data.all_bookings);
                    console.log('Debug info - Pending bookings:', data.debug);
                    if (data.success) {
                        const count = data.count;
                        updateNotificationBadge(count);
                    }
                })
                .catch(error => {
                    console.error('Error loading notification count:', error);
                });
        }

        // Function to update the notification badge with given count
        function updateNotificationBadge(count) {
            const badge = document.querySelector('.notification-badge[data-type="bookings"]');
            
            if (badge) {
                console.log('Updating badge with count:', count);
                if (count > 0) {
                    badge.textContent = count;
                    badge.classList.remove('hidden');
                    console.log('Badge displayed with count:', count);
                } else {
                    badge.classList.add('hidden');
                    badge.textContent = '0';
                    console.log('Badge hidden - no pending bookings');
                }
            } else {
                console.error('Badge element not found');
            }
        }

        function viewBooking(id) {
            Swal.fire('Booking #' + id, 'Booking details would be shown here', 'info');
        }

        function approveBooking(id) {
            Swal.fire({
                icon: 'warning',
                title: 'Approve Booking',
                text: 'Are you sure you want to approve this booking?',
                showCancelButton: true,
                confirmButtonColor: '#d4a574',
                cancelButtonColor: '#999',
                confirmButtonText: 'Yes, Approve',
                cancelButtonText: 'Cancel',
                allowOutsideClick: false,
                allowEscapeKey: false
            }).then((result) => {
                if (result.isConfirmed) {
                    updateBookingStatus(id, 'confirmed', null);
                }
            });
        }

        function rejectBooking(id) {
            Swal.fire({
                title: 'Reject Booking',
                input: 'textarea',
                inputLabel: 'Rejection Reason',
                inputPlaceholder: 'Enter the reason for rejecting this booking...',
                inputAttributes: {
                    'aria-label': 'Rejection reason'
                },
                showCancelButton: true,
                confirmButtonColor: '#d4a574',
                cancelButtonColor: '#999',
                confirmButtonText: 'Yes, Reject',
                cancelButtonText: 'Cancel',
                allowOutsideClick: false,
                allowEscapeKey: false,
                inputValidator: (value) => {
                    if (!value) {
                        return 'Please enter a reason for rejection';
                    }
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    updateBookingStatus(id, 'cancelled', result.value);
                }
            });
        }

        function updateBookingStatus(id, status, reason = null) {
            // Show loading alert
            Swal.fire({
                title: 'Processing...',
                html: '<div class="loader"></div><p style="margin-top: 20px;">Sending email and updating booking...</p>',
                icon: 'info',
                allowOutsideClick: false,
                allowEscapeKey: false,
                didOpen: (modal) => {
                    modal.querySelector('.swal2-confirm').style.display = 'none';
                    modal.querySelector('.swal2-cancel').style.display = 'none';
                }
            });

            fetch('../backend/admin_bookings_api.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    id: id,
                    status: status,
                    reason: reason
                })
            })
            .then(async (response) => {
                const raw = await response.text();
                if (!raw) {
                    throw new Error(`Empty server response (HTTP ${response.status})`);
                }

                let data;
                try {
                    data = JSON.parse(raw);
                } catch (e) {
                    throw new Error(`Invalid server response (HTTP ${response.status}): ${raw.substring(0, 180)}`);
                }

                if (!response.ok) {
                    const msg = data && data.message ? data.message : `HTTP ${response.status}`;
                    throw new Error(msg);
                }

                return data;
            })
            .then(data => {
                console.log('Booking update response:', data);
                if (data.success) {
                    const statusMsg = status === 'confirmed' ? 'approved' : 'cancelled';
                    let htmlMsg = `Booking ${statusMsg} successfully and email sent to customer`;
                    
                    // Add table status info if available
                    if (data.table_updated && data.booking_status === 'confirmed') {
                        htmlMsg += `<br><strong style="color: #28a745;">✓ Table ${data.table_number} marked as booked</strong>`;
                    } else if (data.table_updated && data.booking_status === 'cancelled') {
                        htmlMsg += `<br><strong style="color: #28a745;">✓ Table ${data.table_number} marked as available</strong>`;
                    } else if (data.table_id) {
                        htmlMsg += `<br><span style="color: #ffc107;">⚠ Table ${data.table_number} status update pending</span>`;
                    }
                    
                    Swal.fire({
                        icon: 'success',
                        title: 'Success',
                        html: htmlMsg,
                        confirmButtonColor: '#d4a574',
                        allowOutsideClick: false,
                        allowEscapeKey: false
                    }).then(() => {
                        loadBookings();
                        // Update badge with the pending count from the response
                        if (data.pending_count !== undefined) {
                            console.log('Updating badge from response with count:', data.pending_count);
                            updateNotificationBadge(data.pending_count);
                        } else {
                            // Fallback to loading from API if not in response
                            loadNotificationCount();
                        }
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: data.message || 'Failed to update booking status',
                        confirmButtonColor: '#d4a574',
                        allowOutsideClick: false,
                        allowEscapeKey: false
                    });
                }
            })
            .catch(error => {
                console.error('Error updating booking:', error);
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Error updating booking status: ' + error.message,
                    confirmButtonColor: '#d4a574',
                    allowOutsideClick: false,
                    allowEscapeKey: false
                });
            });
        }



        // Store current booking and table data for assignment
        let currentBookingForAssignment = null;
        let availableTablesData = [];
        let isConfirmationDialogOpen = false;
        let currentBookingSeatProgress = {
            required: 0,
            assigned: 0,
            remaining: 0
        };

        // Open table assignment modal
        function openAssignTableModal(bookingId) {
            console.log('Opening assign table modal for booking ID:', bookingId);
            bookingId = parseInt(bookingId); // Ensure it's an integer
            
            // Load all bookings to find the one with this ID
            fetch('../backend/admin_bookings_api.php')
                .then(response => response.json())
                .then(data => {
                    console.log('Fetched bookings:', data);
                    if (data.success && data.data) {
                        const foundBooking = data.data.find(b => parseInt(b.id) === bookingId);
                        console.log('Found booking:', foundBooking);
                        if (foundBooking) {
                            currentBookingForAssignment = foundBooking;
                            
                            // Update booking details
                            document.getElementById('assignBookingName').textContent = foundBooking.name;
                            document.getElementById('assignBookingGuests').textContent = foundBooking.guests;
                            document.getElementById('assignBookingDate').textContent = new Date(foundBooking.booking_date).toLocaleDateString();
                            document.getElementById('assignBookingTime').textContent = foundBooking.slot_time;
                            loadBookingSeatProgress(bookingId);
                            
                            // Load available tables
                            loadAvailableTablesForAssignment();
                            
                            // Show modal and overlay
                            const modal = document.getElementById('assignTableModal');
                            const overlay = document.getElementById('modalOverlay');
                            console.log('Modal element:', modal);
                            console.log('Overlay element:', overlay);
                            if (modal) {
                                modal.style.cssText = '';
                                modal.style.display = 'flex';
                            }
                            if (overlay) {
                                overlay.style.cssText = '';
                                overlay.style.display = 'block';
                            }
                            console.log('Modal display set to flex');
                        } else {
                            console.error('Booking not found with ID:', bookingId);
                        }
                    } else {
                        console.error('Failed to fetch bookings:', data);
                    }
                })
                .catch(error => {
                    console.error('Error loading booking:', error);
                    alert('Error opening assign table modal: ' + error.message);
                });
        }

        function renderBookingSeatProgressPreview(selectedTables) {
            const preview = document.getElementById('bookingSeatPreview');
            if (!preview) return;

            if (!selectedTables || selectedTables.length === 0) {
                preview.style.display = 'none';
                preview.textContent = '';
                return;
            }

            const totalSelectedSeats = selectedTables.reduce((sum, t) => sum + (parseInt(t.current_capacity || 0, 10) || 0), 0);
            const selectedTableNames = selectedTables.map(t => t.table_number).join(', ');
            const projectedAssigned = currentBookingSeatProgress.assigned + totalSelectedSeats;
            const projectedRemaining = Math.max(0, currentBookingSeatProgress.required - projectedAssigned);
            preview.style.display = 'block';
            preview.textContent = `After assigning [${selectedTableNames}] (${totalSelectedSeats} seats): assigned ${projectedAssigned}, remaining ${projectedRemaining}.`;
        }

        function updateSelectedTablesSummary() {
            const checked = Array.from(document.querySelectorAll('.assign-table-checkbox:checked'));
            const selectedIds = checked.map(c => parseInt(c.value, 10));
            const selectedTables = availableTablesData.filter(t => selectedIds.includes(parseInt(t.id, 10)));
            const selectedSeats = selectedTables.reduce((sum, t) => sum + (parseInt(t.current_capacity || 0, 10) || 0), 0);
            const summaryEl = document.getElementById('selectedTablesSummary');
            if (summaryEl) {
                if (selectedTables.length === 0) {
                    summaryEl.textContent = 'No tables selected.';
                } else {
                    summaryEl.textContent = `${selectedTables.length} table(s) selected, total seats: ${selectedSeats}`;
                }
            }
            renderBookingSeatProgressPreview(selectedTables);
        }

        function loadBookingSeatProgress(bookingId) {
            const seatText = document.getElementById('bookingSeatProgressText');
            const requiredEl = document.getElementById('bookingRequiredSeats');
            const assignedEl = document.getElementById('bookingAssignedSeats');
            const remainingEl = document.getElementById('bookingRemainingSeats');

            if (seatText) seatText.textContent = 'Loading...';
            if (requiredEl) requiredEl.textContent = '0';
            if (assignedEl) assignedEl.textContent = '0';
            if (remainingEl) remainingEl.textContent = '0';
            renderBookingSeatProgressPreview(null);

            fetch(`../backend/admin_bookings_api.php?action=booking_progress&booking_id=${encodeURIComponent(bookingId)}`)
                .then(response => response.json())
                .then(data => {
                    if (!data.success || !data.data) {
                        throw new Error(data.message || 'Failed to load seat progress');
                    }

                    const progress = data.data;
                    currentBookingSeatProgress = {
                        required: parseInt(progress.required_guests || 0, 10),
                        assigned: parseInt(progress.assigned_seats || 0, 10),
                        remaining: parseInt(progress.remaining_seats || 0, 10)
                    };

                    if (requiredEl) requiredEl.textContent = currentBookingSeatProgress.required;
                    if (assignedEl) assignedEl.textContent = currentBookingSeatProgress.assigned;
                    if (remainingEl) remainingEl.textContent = currentBookingSeatProgress.remaining;

                    if (seatText) {
                        seatText.textContent = currentBookingSeatProgress.remaining > 0
                            ? 'Need more tables'
                            : 'Fully assigned';
                        seatText.style.color = currentBookingSeatProgress.remaining > 0 ? '#c26d00' : '#1e7e34';
                        seatText.style.fontWeight = '700';
                    }
                })
                .catch(error => {
                    console.error('Error loading booking seat progress:', error);
                    if (seatText) {
                        seatText.textContent = 'Unable to load progress';
                        seatText.style.color = '#b02a37';
                    }
                });
        }

        function loadAvailableTablesForAssignment() {
            // Get the booking date from the current booking
            if (!currentBookingForAssignment || !currentBookingForAssignment.booking_date) {
                console.error('No booking date available');
                const box = document.getElementById('assignTableCheckboxes');
                if (box) box.innerHTML = '<div style="font-size:13px; color:#777; padding:8px;">No booking date available</div>';
                return;
            }
            
            const bookingDate = currentBookingForAssignment.booking_date;
            const bookingSlotTime = (currentBookingForAssignment.slot_time || '').trim();
            const bookingMealType = (currentBookingForAssignment.meal_type || '').trim();
            const bookingDateFormatted = new Date(bookingDate).toLocaleDateString();
            
            // Update the date info display
            document.getElementById('tableFilterDateInfo').textContent = bookingDateFormatted;
            
            const query = new URLSearchParams({
                action: 'list',
                status: 'available',
                date: bookingDate
            });
            if (bookingSlotTime) {
                query.set('slot_time', bookingSlotTime);
            }
            if (bookingMealType) {
                query.set('meal_type', bookingMealType);
            }

            console.log('Loading online tables for booking date/slot/meal:', bookingDate, bookingSlotTime, bookingMealType);
            
            fetch('../backend/online_tables_api.php?' + query.toString())
                .then(response => response.json())
                .then(data => {
                    console.log('Fetched tables for date ' + bookingDate + ':', data);
                    if (data.success && data.data && data.data.length > 0) {
                        // Keep only available tables as a safety check
                        availableTablesData = data.data.filter(table => table.status === 'available');
                        const box = document.getElementById('assignTableCheckboxes');
                        if (box) {
                            if (availableTablesData.length === 0) {
                                box.innerHTML = '<div style="font-size:13px; color:#777; padding:8px;">No available tables for this slot</div>';
                            } else {
                                box.innerHTML = availableTablesData.map(table => `
                                    <label style="display:flex; align-items:center; gap:10px; padding:8px; border-bottom:1px solid #f1f1f1; cursor:pointer;">
                                        <input type="checkbox" class="assign-table-checkbox" value="${table.id}">
                                        <span style="font-size:13px;">
                                            <strong>${table.table_number}</strong> (${table.current_capacity} chairs)
                                            <span style="color:#777;">- Floor ${table.floor_level}, ${table.section || 'N/A'}</span>
                                        </span>
                                    </label>
                                `).join('');
                            }
                        }
                        
                        console.log('Available tables count:', availableTablesData.length);
                        
                        // Set up event listener for select change
                        setupTableSelectListener();
                    } else {
                    console.error('No tables returned:', data);
                        const box = document.getElementById('assignTableCheckboxes');
                        if (box) box.innerHTML = '<div style="font-size:13px; color:#777; padding:8px;">No available tables for this slot</div>';
                    }
                })
                .catch(error => {
                    console.error('Error loading available tables:', error);
                    const box = document.getElementById('assignTableCheckboxes');
                    if (box) box.innerHTML = '<div style="font-size:13px; color:#c0392b; padding:8px;">Error loading tables</div>';
                });
        }

        // Handle table selection checkboxes
        function setupTableSelectListener() {
            const checkboxes = document.querySelectorAll('.assign-table-checkbox');
            checkboxes.forEach(cb => {
                cb.addEventListener('change', updateSelectedTablesSummary);
            });
            updateSelectedTablesSummary();
        }

        function closeAssignModal() {
            console.log('Closing assign modal');
            const modal = document.getElementById('assignTableModal');
            const overlay = document.getElementById('modalOverlay');
            
            // Force hide by clearing all inline styles and setting display none
            if (modal) {
                modal.style.cssText = '';
                modal.style.display = 'none';
                modal.removeAttribute('aria-hidden');
            }
            if (overlay) {
                overlay.style.cssText = '';
                overlay.style.display = 'none';
            }
            
            // Reset form state
            const checkboxes = document.querySelectorAll('.assign-table-checkbox');
            checkboxes.forEach(cb => { cb.checked = false; });
            const summaryEl = document.getElementById('selectedTablesSummary');
            if (summaryEl) summaryEl.textContent = '';
            renderBookingSeatProgressPreview(null);
            
            // Reset booking data
            currentBookingForAssignment = null;
            
            // Return focus to body
            document.body.focus();
            
            console.log('Modal closed, display:', modal ? modal.style.display : 'N/A');
        }

        function confirmTableAssignment() {
            const selectedCheckboxes = Array.from(document.querySelectorAll('.assign-table-checkbox:checked'));
            const selectedTableIds = selectedCheckboxes.map(cb => parseInt(cb.value, 10)).filter(Number.isFinite);
            
            console.log('=== CONFIRM ASSIGNMENT FUNCTION START ===');
            console.log('Confirm assignment - tableIds:', selectedTableIds);
            console.log('Current booking:', currentBookingForAssignment);

            // Validate table(s) selected
            if (selectedTableIds.length === 0) {
                console.log('ERROR: No table selected');
                Swal.fire({
                    icon: 'warning',
                    title: 'Error',
                    text: 'Please select at least one table',
                    confirmButtonColor: '#d4a574'
                });
                return;
            }
            
            // Validate booking is set
            if (!currentBookingForAssignment || !currentBookingForAssignment.id) {
                console.log('ERROR: No booking data');
                Swal.fire({
                    icon: 'warning',
                    title: 'Error',
                    text: 'No booking selected. Please try again.',
                    confirmButtonColor: '#d4a574'
                });
                return;
            }

            const selectedTables = availableTablesData.filter(t => selectedTableIds.includes(parseInt(t.id, 10)));
            const tableNames = selectedTables.map(t => t.table_number).join(', ');
            const totalSelectedSeats = selectedTables.reduce((sum, t) => sum + (parseInt(t.current_capacity || 0, 10) || 0), 0);

            console.log('Showing confirmation dialog for tables:', tableNames, 'booking:', currentBookingForAssignment.name);
            
            // Store these values before closing modal
            const bookingIdToAssign = currentBookingForAssignment.id;
            const tableIdsToAssign = selectedTableIds;
            
            // Now show the confirmation SweetAlert (without custom modal interference)
            Swal.fire({
                title: 'Assign Selected Tables',
                html: `Assign <strong>${selectedTables.length}</strong> table(s) with total <strong>${totalSelectedSeats}</strong> seats to booking for <strong>${currentBookingForAssignment.name}</strong>?<br><small>${tableNames}</small>`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d4a574',
                cancelButtonColor: '#999',
                confirmButtonText: 'Yes, Assign',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                console.log('Confirmation dialog result:', result);
                console.log('Is Confirmed:', result.isConfirmed);
                
                if (result.isConfirmed && bookingIdToAssign && tableIdsToAssign.length > 0) {
                    console.log('Calling assignTableToBooking with bookingId:', bookingIdToAssign, 'tableIds:', tableIdsToAssign);
                    assignTableToBooking(bookingIdToAssign, tableIdsToAssign);
                } else {
                    console.log('User cancelled the confirmation');
                }
            });
        }

        async function assignTableToBooking(bookingId, tableIds) {
            console.log('=== START ASSIGN TABLE FUNCTION ===');
            console.log('Assigning table IDs:', tableIds, 'to booking ID:', bookingId);
            
            // Show loading alert
            Swal.fire({
                title: 'Processing...',
                html: '<div class="loader"></div><p style="margin-top: 20px;">Assigning selected tables...</p>',
                icon: 'info',
                allowOutsideClick: false,
                allowEscapeKey: false,
                didOpen: (modal) => {
                    const confirm = modal.querySelector('.swal2-confirm');
                    const cancel = modal.querySelector('.swal2-cancel');
                    if (confirm) confirm.style.display = 'none';
                    if (cancel) cancel.style.display = 'none';
                }
            });

            const successTables = [];
            const failedTables = [];

            for (const tableId of tableIds) {
                const requestData = {
                    action: 'assign_table',
                    booking_id: parseInt(bookingId, 10),
                    table_id: parseInt(tableId, 10)
                };
                try {
                    const response = await fetch('../backend/admin_bookings_api.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(requestData),
                        credentials: 'include'
                    });
                    const text = await response.text();
                    let data = {};
                    try {
                        data = JSON.parse(text || '{}');
                    } catch (e) {
                        data = { success: false, message: 'Invalid server response' };
                    }

                    if (response.ok && data.success) {
                        successTables.push(data.table_name || `ID ${tableId}`);
                    } else {
                        failedTables.push(`${tableId}: ${data.message || 'Assignment failed'}`);
                    }
                } catch (error) {
                    failedTables.push(`${tableId}: ${error.message || 'Network error'}`);
                }
            }

            Swal.close();
            currentBookingForAssignment = null;
            closeAssignModal();

            if (failedTables.length === 0) {
                Swal.fire({
                    icon: 'success',
                    title: 'Success!',
                    html: `<p>Assigned <strong>${successTables.length}</strong> table(s): ${successTables.join(', ')}</p>`,
                    confirmButtonColor: '#d4a574'
                });
            } else {
                Swal.fire({
                    icon: 'warning',
                    title: 'Partial Assignment',
                    html: `<p>Assigned: <strong>${successTables.length}</strong><br>Failed: <strong>${failedTables.length}</strong></p><p style="font-size:12px; color:#555;">${failedTables.join('<br>')}</p>`,
                    confirmButtonColor: '#d4a574'
                });
            }

            loadBookings();
            if (adminSelectedDateStr && selectedMealTypeName && selectedSlotTime) {
                loadTableStatusByFilters(adminSelectedDateStr, selectedMealTypeName, selectedSlotTime, selectedSlotLabel);
            } else {
                loadTablesForSelectedDate(adminSelectedDate);
            }
            
            console.log('=== END ASSIGN TABLE FUNCTION ===');
        }
    </script>
</body>

</html>
