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

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

        .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="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>

            <!-- 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> Available Tables for <span id="tablesDateDisplay">Today</span>
                        </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 a date to view available tables
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Available Tables Section -->
            <div style="background: white; padding: 20px; border-radius: 8px; margin-bottom: 30px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                <div style="font-size: 18px; font-weight: 600; margin-bottom: 15px; color: #333;">
                    <i class="fas fa-table"></i> All Available Tables (Today)
                </div>
                <div id="availableTablesContainer" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 15px;">
                    <div style="text-align: center; color: #999;">Loading tables...</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>Booking Time</th>
                            <th>Guests</th>
                            <th>Occasion</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>
                <div style="margin-bottom: 15px;">
                    <label for="assignTableSelect" style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">
                        Select Available Table 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>
                    <select id="assignTableSelect" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px;">
                        <option value="">-- Choose a table --</option>
                    </select>
                </div>
                <div id="selectedTableDetails" style="background: #f5f5f5; padding: 15px; border-radius: 4px; display: none;">
                    <strong style="display: block; margin-bottom: 10px;">Table Details:</strong>
                    <p style="margin: 5px 0;"><strong>Name:</strong> <span id="detailTableName">-</span></p>
                    <p style="margin: 5px 0;"><strong>Capacity:</strong> <span id="detailTableCapacity">-</span></p>
                    <p style="margin: 5px 0;"><strong>Floor:</strong> <span id="detailTableFloor">-</span></p>
                    <p style="margin: 5px 0;"><strong>Section:</strong> <span id="detailTableSection">-</span></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 and available tables on page load
            loadBookings();
            loadAvailableTables();
            loadNotificationCount();
            
            // Initialize admin calendar for date selection
            initializeAdminCalendar();

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


        });


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

        function initializeAdminCalendar() {
            renderAdminCalendar();
            setupAdminCalendarNavigation();
            
            // 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}`;
            
            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;
            
            console.log('Loading tables for date:', dateStr);
            
            // Fetch available tables for this date
            fetch('../backend/tables_api.php?action=list&status=available&date=' + encodeURIComponent(dateStr))
                .then(response => response.json())
                .then(data => {
                    console.log('Tables for ' + dateStr + ':', data);
                    
                    const container = document.getElementById('availableTablesForDateContainer');
                    
                    if (data.success && data.data && data.data.length > 0) {
                        container.innerHTML = data.data.map(table => `
                            <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>
                        `).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 available tables for this date</div>';
                    }
                })
                .catch(error => {
                    console.error('Error loading tables:', error);
                    const container = document.getElementById('availableTablesForDateContainer');
                    container.innerHTML = '<div style="grid-column: 1/-1; text-align: center; color: #c0392b; padding: 40px 20px;">Error loading tables</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.booking_time}</td>
                                    <td>${booking.guests}</td>
                                    <td>${booking.occasion}</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(response => response.json())
            .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
                });
            });
        }



        // Load available tables
        function loadAvailableTables() {
            const container = document.getElementById('availableTablesContainer');
            container.innerHTML = '<div style="text-align: center; color: #999;">Loading tables...</div>';
            
            // Get today's date in YYYY-MM-DD format
            const today = new Date();
            const year = today.getFullYear();
            const month = String(today.getMonth() + 1).padStart(2, '0');
            const day = String(today.getDate()).padStart(2, '0');
            const todayStr = `${year}-${month}-${day}`;
            
            // Fetch available tables for today specifically
            fetch('../backend/tables_api.php?action=list&status=available&date=' + encodeURIComponent(todayStr))
                .then(response => response.json())
                .then(data => {
                    console.log('Available tables for today:', data);
                    if (data.success && data.data && data.data.length > 0) {
                        container.innerHTML = data.data.map(table => `
                            <div class="table-card">
                                <div class="table-card-header">
                                    <span class="table-card-name">${table.table_number}</span>
                                    <span class="table-card-capacity">${table.current_capacity} chairs</span>
                                </div>
                                <div class="table-card-info">
                                    <div class="table-card-info-row">
                                        <span class="table-card-info-label">Floor:</span>
                                        <span>Floor ${table.floor_level}</span>
                                    </div>
                                    <div class="table-card-info-row">
                                        <span class="table-card-info-label">Section:</span>
                                        <span>${table.section || 'Not assigned'}</span>
                                    </div>
                                    <div class="table-card-info-row">
                                        <span class="table-card-info-label">Status:</span>
                                        <span style="color: #28a745; font-weight: 600;">Available</span>
                                    </div>
                                </div>
                            </div>
                        `).join('');
                    } else {
                        container.innerHTML = '<div style="text-align: center; color: #999; padding: 20px;"><i class="fas fa-ban" style="font-size: 20px; margin-bottom: 10px; display: block;"></i>No available tables for today</div>';
                    }
                })
                .catch(error => {
                    console.error('Error loading tables:', error);
                    container.innerHTML = '<div style="text-align: center; color: #c0392b; padding: 20px;">Error loading tables</div>';
                });
        }

        // Store current booking and table data for assignment
        let currentBookingForAssignment = null;
        let availableTablesData = [];
        let isConfirmationDialogOpen = false;

        // 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.booking_time;
                            
                            // 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 loadAvailableTablesForAssignment() {
            // Get the booking date from the current booking
            if (!currentBookingForAssignment || !currentBookingForAssignment.booking_date) {
                console.error('No booking date available');
                const select = document.getElementById('assignTableSelect');
                select.innerHTML = '<option value="">-- No booking date available --</option>';
                return;
            }
            
            const bookingDate = currentBookingForAssignment.booking_date;
            const bookingDateFormatted = new Date(bookingDate).toLocaleDateString();
            
            // Update the date info display
            document.getElementById('tableFilterDateInfo').textContent = bookingDateFormatted;
            
            console.log('Loading tables for booking date:', bookingDate);
            
            fetch('../backend/tables_api.php?action=list&status=available&date=' + encodeURIComponent(bookingDate))
                .then(response => response.json())
                .then(data => {
                    console.log('Fetched tables for date ' + bookingDate + ':', data);
                    if (data.success && data.data) {
                        // When date parameter is provided, trust the backend filtering
                        // Don't filter by status='available' again as backend already handled it
                        availableTablesData = data.data;
                        
                        // Populate dropdown
                        const select = document.getElementById('assignTableSelect');
                        select.innerHTML = '<option value="">-- Choose a table --</option>';
                        
                        availableTablesData.forEach(table => {
                            const option = document.createElement('option');
                            option.value = table.id;
                            option.textContent = `${table.table_number} (${table.current_capacity} chairs)`;
                            select.appendChild(option);
                        });
                        
                        console.log('Available tables count:', availableTablesData.length);
                        
                        // Set up event listener for select change
                        setupTableSelectListener();
                    } else {
                        console.error('No tables returned:', data);
                        const select = document.getElementById('assignTableSelect');
                        select.innerHTML = '<option value="">-- No available tables for this date --</option>';
                    }
                })
                .catch(error => {
                    console.error('Error loading available tables:', error);
                    const select = document.getElementById('assignTableSelect');
                    select.innerHTML = '<option value="">-- Error loading tables --</option>';
                });
        }

        // Handle table selection - set up event listener properly
        function setupTableSelectListener() {
            const tableSelect = document.getElementById('assignTableSelect');
            if (tableSelect) {
                tableSelect.addEventListener('change', function() {
                    const tableId = this.value;
                    const detailsDiv = document.getElementById('selectedTableDetails');
                    
                    if (tableId) {
                        const selectedTable = availableTablesData.find(t => t.id == tableId);
                        if (selectedTable) {
                            document.getElementById('detailTableName').textContent = selectedTable.table_number;
                            document.getElementById('detailTableCapacity').textContent = selectedTable.current_capacity + ' chairs';
                            document.getElementById('detailTableFloor').textContent = 'Floor ' + selectedTable.floor_level;
                            document.getElementById('detailTableSection').textContent = selectedTable.section || 'Not assigned';
                            detailsDiv.style.display = 'block';
                        }
                    } else {
                        detailsDiv.style.display = 'none';
                    }
                });
            }
        }

        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 tableSelect = document.getElementById('assignTableSelect');
            if (tableSelect) tableSelect.value = '';
            
            const detailsDiv = document.getElementById('selectedTableDetails');
            if (detailsDiv) detailsDiv.style.display = 'none';
            
            // 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 tableId = document.getElementById('assignTableSelect').value;
            
            console.log('=== CONFIRM ASSIGNMENT FUNCTION START ===');
            console.log('Confirm assignment - tableId:', tableId);
            console.log('Current booking:', currentBookingForAssignment);
            
            // Close the custom modal and overlay FIRST (before any alerts)
            const modal = document.getElementById('assignTableModal');
            const overlay = document.getElementById('modalOverlay');
            if (modal) modal.style.display = 'none';
            if (overlay) overlay.style.display = 'none';
            
            // Validate table is selected
            if (!tableId || tableId === '') {
                console.log('ERROR: No table selected');
                Swal.fire({
                    icon: 'warning',
                    title: 'Error',
                    text: 'Please select a 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;
            }

            // Find the selected table details for display
            const selectedTable = availableTablesData && availableTablesData.length > 0 
                ? availableTablesData.find(t => t.id == tableId)
                : null;
            const tableName = (selectedTable && selectedTable.table_number) ? selectedTable.table_number : 'Selected Table';

            console.log('Showing confirmation dialog for table:', tableName, 'booking:', currentBookingForAssignment.name);
            
            // Store these values before closing modal
            const bookingIdToAssign = currentBookingForAssignment.id;
            const tableIdToAssign = tableId;
            
            console.log('Custom modal closed. Now showing confirmation dialog.');
            
            // Now show the confirmation SweetAlert (without custom modal interference)
            Swal.fire({
                title: 'Assign Table',
                html: `Are you sure you want to assign <strong>${tableName}</strong> to the booking for <strong>${currentBookingForAssignment.name}</strong>?`,
                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 && tableIdToAssign) {
                    console.log('Calling assignTableToBooking with bookingId:', bookingIdToAssign, 'tableId:', tableIdToAssign);
                    assignTableToBooking(bookingIdToAssign, tableIdToAssign);
                } else {
                    console.log('User cancelled the confirmation');
                    currentBookingForAssignment = null;
                }
            });
        }

        function assignTableToBooking(bookingId, tableId) {
            console.log('=== START ASSIGN TABLE FUNCTION ===');
            console.log('Assigning table ID:', tableId, 'to booking ID:', bookingId);
            
            // Show loading alert
            Swal.fire({
                title: 'Processing...',
                html: '<div class="loader"></div><p style="margin-top: 20px;">Assigning table to booking...</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';
                }
            });

            // Make sure data is sent as integers
            const requestData = {
                action: 'assign_table',
                booking_id: parseInt(bookingId),
                table_id: parseInt(tableId)
            };
            
            console.log('Sending request with data:', requestData);

            fetch('../backend/admin_bookings_api.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestData),
                credentials: 'include'
            })
            .then(response => {
                console.log('Response received. Status:', response.status);
                return response.text().then(text => {
                    console.log('Raw response text:', text);
                    return { status: response.status, text: text };
                });
            })
            .then(({ status, text }) => {
                console.log('Processing response. Status:', status, 'Text:', text);
                
                if (status !== 200) {
                    console.error('HTTP Error:', status);
                    Swal.fire({
                        icon: 'error',
                        title: 'HTTP Error',
                        text: 'Server returned status ' + status,
                        confirmButtonColor: '#d4a574'
                    });
                    return;
                }
                
                try {
                    const data = JSON.parse(text);
                    console.log('Parsed JSON data:', data);
                    
                    if (data.success === true) {
                        console.log('SUCCESS TRUE - Showing success message');
                        
                        // Close the loading dialog
                        Swal.close();
                        
                        // Reset state
                        currentBookingForAssignment = null;
                        console.log('Current booking reset to null');
                        
                        // Show success message
                        setTimeout(() => {
                            console.log('Showing success dialog');
                            Swal.fire({
                                icon: 'success',
                                title: 'Success!',
                                html: `<p>Table <strong>${data.table_name || 'assigned'}</strong> has been successfully assigned to the booking!</p>`,
                                confirmButtonColor: '#d4a574'
                            }).then((result) => {
                                console.log('Success dialog closed');
                                document.body.focus();
                                
                                // Reload data
                                loadBookings();
                                loadAvailableTables();
                            });
                        }, 300);
                    } else {
                        console.log('SUCCESS is FALSE or undefined:', data.success);
                        // Close loading dialog
                        Swal.close();
                        
                        // Show error
                        Swal.fire({
                            icon: 'error',
                            title: 'Assignment Failed',
                            text: data.message || 'Failed to assign table',
                            confirmButtonColor: '#d4a574'
                        });
                    }
                } catch (parseError) {
                    console.error('JSON Parse Error:', parseError);
                    console.error('Failed to parse text:', text);
                    // Close loading dialog
                    Swal.close();
                    
                    Swal.fire({
                        icon: 'error',
                        title: 'Parse Error',
                        text: 'Invalid JSON response: ' + text.substring(0, 100),
                        confirmButtonColor: '#d4a574'
                    });
                }
            })
            .catch(error => {
                console.error('Network/Fetch Error:', error);
                // Close loading dialog
                Swal.close();
                
                Swal.fire({
                    icon: 'error',
                    title: 'Network Error',
                    text: error.message || 'Failed to communicate with server',
                    confirmButtonColor: '#d4a574'
                });
            });
            
            console.log('=== END ASSIGN TABLE FUNCTION ===');
        }
    </script>
</body>

</html>
