<!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="Admin Dashboard - 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>Admin Dashboard - 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 Styles */
        .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 5px rgba(231, 76, 60, 0.3);
            }
        }

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

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

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

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

        .status-badge.unread {
            background: #cce5ff;
            color: #004085;
        }

        .btn-view {
            padding: 6px 12px;
            background: #d4a574;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.3s ease;
        }

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

        .sidebar-menu a {
            display: flex;
            align-items: center;
            gap: 15px;
        }

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

        .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;
            transition: all 0.3s ease;
            font-size: 13px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .logout-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(231, 76, 60, 0.3);
        }

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

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

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

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

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

        .btn-icon-small {
            width: 36px;
            height: 36px;
            border: none;
            border-radius: 6px;
            background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
            color: white;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .btn-icon-small:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(212, 165, 116, 0.3);
        }

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

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

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

        .dashboard-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 20px;
            margin-bottom: 40px;
        }

        .stat-card {
            background: linear-gradient(135deg, #ffffff 0%, #fafafa 100%);
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            border-left: 4px solid #d4a574;
            position: relative;
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }

        .stat-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 8px 24px rgba(212, 165, 116, 0.15);
            background: linear-gradient(135deg, #ffffff 0%, #fef9f4 100%);
            border-left-color: #8b6f47;
        }

        .stat-card::before {
            content: '';
            position: absolute;
            right: -15px;
            top: -15px;
            width: 80px;
            height: 80px;
            background: radial-gradient(circle, rgba(212, 165, 116, 0.15) 0%, rgba(212, 165, 116, 0.05) 70%);
            border-radius: 50%;
            transition: all 0.3s ease;
        }

        .stat-card:hover::before {
            right: -10px;
            top: -10px;
            background: radial-gradient(circle, rgba(212, 165, 116, 0.25) 0%, rgba(212, 165, 116, 0.1) 70%);
        }

        .stat-icon {
            font-size: 28px;
            color: #d4a574;
            margin-bottom: 10px;
            align-self: flex-start;
        }

        .stat-label {
            font-size: 12px;
            color: #888;
            text-transform: uppercase;
            letter-spacing: 0.8px;
            font-weight: 600;
            margin-bottom: 6px;
        }

        .stat-value {
            font-size: 26px;
            font-weight: 700;
            color: #2c3e50;
            margin-bottom: 8px;
        }

        .stat-change {
            font-size: 11px;
            margin-top: auto;
            color: #27ae60;
            font-weight: 500;
        }

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

        .section-title {
            font-size: 20px;
            font-weight: 700;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 2px solid #f0f0f0;
            display: flex;
            align-items: center;
            gap: 10px;
            color: #333;
        }

        .section-title i {
            color: #d4a574;
        }

        .btn-group {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        .btn-action {
            padding: 12px 20px;
            background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            font-size: 13px;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-action:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(212, 165, 116, 0.3);
        }

        .table-responsive {
            overflow-x: auto;
        }

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

        .admin-table thead th {
            background: #f9f7f4;
            padding: 15px;
            text-align: left;
            font-weight: 600;
            color: #333;
            border-bottom: 2px solid #e8e8e8;
            font-size: 13px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

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

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

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

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

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

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

        /* Responsive Design */
        @media (max-width: 1200px) {
            .dashboard-grid {
                grid-template-columns: repeat(3, 1fr);
                gap: 18px;
            }
        }

        @media (max-width: 992px) {
            .dashboard-grid {
                grid-template-columns: repeat(2, 1fr);
                gap: 18px;
            }
        }

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

            .topbar {
                left: 250px;
                padding: 0 20px;
            }

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

            .dashboard-grid {
                grid-template-columns: repeat(2, 1fr);
                gap: 15px;
                margin-bottom: 30px;
            }

            .stat-card {
                padding: 18px;
            }

            .stat-icon {
                font-size: 24px;
                margin-bottom: 8px;
            }

            .stat-value {
                font-size: 22px;
            }

            .stat-label {
                font-size: 11px;
            }

            .topbar-right {
                gap: 10px;
            }

            .user-info {
                display: none;
            }
        }

        @media (max-width: 576px) {
            .sidebar {
                width: 250px;
                position: fixed;
                left: 0;
                top: 0;
                transform: translateX(-100%);
                transition: transform 0.3s ease;
                z-index: 1001;
            }

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

            .topbar {
                left: 0;
                padding: 0 15px;
            }

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

            .topbar {
                height: 60px;
            }

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

            .sidebar-header {
                padding: 20px 15px;
            }

            .sidebar-menu a {
                padding: 12px 15px;
            }

            .content-section {
                padding: 15px;
            }

            .dashboard-grid {
                grid-template-columns: 1fr;
                gap: 12px;
                margin-bottom: 25px;
            }

            .stat-card {
                padding: 16px;
            }

            .stat-icon {
                font-size: 22px;
                margin-bottom: 6px;
            }

            .stat-value {
                font-size: 20px;
            }

            .stat-label {
                font-size: 10px;
                letter-spacing: 0.6px;
            }

            .stat-change {
                font-size: 10px;
            }

            .admin-table thead th,
            .admin-table tbody td {
                padding: 10px;
                font-size: 12px;
            }

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

            .btn-action {
                width: 100%;
                justify-content: center;
            }
        }

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

        @media (max-width: 576px) {
            .menu-toggle {
                display: block;
            }
        }

        .overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 500;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .overlay.active {
            display: block;
            opacity: 1;
        }

        @media (max-width: 576px) {
            .overlay {
                display: none;
            }

            .overlay.active {
                display: block;
            }
        }

        /* Slider Management Styles */
        .sliders-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 25px;
            margin-top: 25px;
        }

        .slider-card {
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
            transition: all 0.3s ease;
            display: flex;
            flex-direction: column;
        }

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

        .slider-image {
            width: 100%;
            height: 200px;
            object-fit: cover;
            background: #f0f0f0;
        }

        .slider-info {
            padding: 20px;
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        .slider-headline {
            font-size: 18px;
            font-weight: 700;
            color: #333;
            margin: 0 0 8px 0;
            line-height: 1.4;
        }

        .slider-subheadline {
            font-size: 12px;
            color: #d4a574;
            text-transform: uppercase;
            margin: 0 0 10px 0;
        }

        .slider-description {
            font-size: 13px;
            color: #666;
            margin: 0 0 12px 0;
            flex: 1;
        }

        .slider-status {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
            margin-bottom: 12px;
            width: fit-content;
        }

        .slider-status.active {
            background: #d4f1d4;
            color: #27ae60;
        }

        .slider-status.inactive {
            background: #fdd;
            color: #c0392b;
        }

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

        .slider-actions button {
            flex: 1;
            padding: 10px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 12px;
            font-weight: 600;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
        }

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

        .slider-actions .btn-edit:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(212, 165, 116, 0.3);
        }

        .slider-actions .btn-delete {
            background: #f8f8f8;
            color: #c0392b;
            border: 1px solid #e8e8e8;
        }

        .slider-actions .btn-delete:hover {
            background: #c0392b;
            color: white;
        }

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

        /* Ensure SweetAlert is always on top */
        .swal2-container {
            z-index: 2000 !important;
        }

        .modal-content {
            background: white;
            padding: 40px;
            border-radius: 10px;
            max-width: 600px;
            width: 90%;
            max-height: 90vh;
            overflow-y: auto;
            position: relative;
        }

        .slider-modal {
            margin: 20px;
        }

        .modal h2 {
            font-size: 24px;
            font-weight: 700;
            margin-bottom: 25px;
            color: #333;
        }

        .close-modal {
            position: absolute;
            right: 20px;
            top: 20px;
            font-size: 28px;
            cursor: pointer;
            color: #999;
            transition: color 0.3s ease;
        }

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

        .form-group {
            margin-bottom: 20px;
            display: flex;
            flex-direction: column;
        }

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

        .form-group input,
        .form-group textarea,
        .form-group select {
            padding: 12px;
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            font-size: 14px;
            font-family: inherit;
            transition: border-color 0.3s ease;
        }

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

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        .form-row .full-width {
            grid-column: 1 / -1;
        }

        .image-upload-wrapper {
            position: relative;
            border: 2px dashed #d4a574;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            background: #fafafa;
        }

        .image-upload-wrapper:hover {
            border-color: #8b6f47;
            background: #f5f5f5;
        }

        .image-upload-wrapper input[type="file"] {
            display: none;
        }

        .image-upload-wrapper::after {
            content: '📁 Click to upload or drag image here';
            display: block;
            color: #666;
            font-size: 14px;
        }

        .image-preview-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 12px;
            padding: 15px 0 0 0;
        }

        .btn-remove-image {
            padding: 8px 16px;
            background: #c0392b;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 12px;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .btn-remove-image:hover {
            background: #a93226;
        }

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

        .form-actions button {
            flex: 1;
            padding: 12px 25px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .btn-action-secondary {
            background: #f0f0f0;
            color: #333;
            border: 1px solid #e0e0e0;
        }

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

        @media (max-width: 768px) {
            .sliders-grid {
                grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
                gap: 20px;
            }

            .modal-content {
                padding: 30px;
            }

            .form-row {
                grid-template-columns: 1fr;
            }

            .form-actions {
                flex-direction: column;
            }
        }

        @media (max-width: 576px) {
            .sliders-grid {
                grid-template-columns: 1fr;
            }

            .slider-card {
                flex-direction: row;
            }

            .slider-image {
                width: 150px;
                height: 150px;
                min-width: 150px;
            }

            .slider-info {
                padding: 15px;
            }

            .slider-headline {
                font-size: 16px;
            }

            .modal-content {
                padding: 20px;
                width: 95%;
            }
        }
    </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" class="active"><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="blog.php"><i class="fas fa-blog"></i> <span>Blog</span></a></li>
            <li><a href="ingredients.php"><i class="fas fa-leaf"></i> <span>Ingredients</span></a></li>
            <li><a href="tables.php"><i class="fas fa-chair"></i> <span>Dine-in Tables</span></a></li>
            <li><a href="online_tables.php"><i class="fas fa-laptop"></i> <span>Online Tables</span></a></li>
            <li><a href="bookings.php"><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-file-invoice"></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="servers.php"><i class="fas fa-user-secret"></i> <span>Servers</span></a></li>
            <li><a href="purchase_managers.php"><i class="fas fa-handshake"></i> <span>Purchase Managers</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" id="topbarTitle">Dashboard</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>
                <button class="btn-icon-small" onclick="openPasswordModal()" title="Change Password">
                    <i class="fas fa-lock"></i>
                </button>
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
        <!-- Dashboard Section -->
        <div id="dashboard-section" class="section-content">
            <!-- Stats -->
            <div class="dashboard-grid">
                <div class="stat-card">
                    <i class="fas fa-shopping-cart stat-icon"></i>
                    <div class="stat-label">Total Orders</div>
                    <div class="stat-value" id="totalOrders">0</div>
                    <div class="stat-change">
                        <i class="fas fa-arrow-up"></i> This month
                    </div>
                </div>

                <div class="stat-card">
                    <i class="fas fa-calendar-check stat-icon"></i>
                    <div class="stat-label">Bookings</div>
                    <div class="stat-value" id="totalBookings">0</div>
                    <div class="stat-change">
                        <i class="fas fa-arrow-up"></i> Confirmed
                    </div>
                </div>

                <div class="stat-card">
                    <i class="fas fa-envelope stat-icon"></i>
                    <div class="stat-label">Contact Messages</div>
                    <div class="stat-value" id="totalContacts">0</div>
                    <div class="stat-change">
                        <i class="fas fa-arrow-up"></i> New
                    </div>
                </div>

                <div class="stat-card">
                    <i class="fas fa-users stat-icon"></i>
                    <div class="stat-label">Total Users</div>
                    <div class="stat-value" id="totalUsers">0</div>
                    <div class="stat-change">
                        <i class="fas fa-arrow-up"></i> Active
                    </div>
                </div>
            </div>

            <!-- Recent Activity -->
            <div class="content-section">
                <div class="section-title">
                    <i class="fas fa-history"></i>
                    Recent Activity
                </div>
                <div id="recentActivityContainer" style="padding: 20px;">
                    <p style="color: #999; text-align: center; padding: 30px;">
                        <i class="fas fa-spinner fa-spin"></i>
                        Loading recent activities...
                    </p>
                </div>
            </div>
        </div>

        <!-- Sliders Section -->
        <div id="sliders-section" class="section-content" style="display: none;">
            <div class="content-section">
                <div class="section-title">
                    <i class="fas fa-images"></i>
                    Manage Carousel Sliders
                </div>
                <div class="btn-group">
                    <button class="btn-action" id="addSliderBtn">
                        <i class="fas fa-plus"></i> Add New Slider
                    </button>
                </div>

                <!-- Slider List -->
                <div id="slidersContainer" class="sliders-grid">
                    <p style="text-align: center; color: #999; padding: 40px;">Loading sliders...</p>
                </div>
            </div>
        </div>

        <!-- Add/Edit Slider Modal -->
        <div id="sliderModal" class="modal" style="display: none;">
            <div class="modal-content slider-modal">
                <span class="close-modal">&times;</span>
                <h2 id="modalTitle">Add New Slider</h2>
                
                <form id="sliderForm">
                    <div class="form-group">
                        <label for="sliderId" style="display: none;">Slider ID</label>
                        <input type="hidden" id="sliderId">
                    </div>

                    <div class="form-row">
                        <div class="form-group full-width">
                            <label for="slideSubheadline">Sub Headline</label>
                            <input type="text" id="slideSubheadline" placeholder="e.g., Granny Offers You" required>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group full-width">
                            <label for="slideHeadline">Main Headline *</label>
                            <input type="text" id="slideHeadline" placeholder="e.g., The Best Tasting Experience!" required>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group full-width">
                            <label for="slideDescription">Description</label>
                            <textarea id="slideDescription" placeholder="Slide description text" rows="3"></textarea>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label for="slideButtonText">Button Text</label>
                            <input type="text" id="slideButtonText" placeholder="e.g., Reservation Now">
                        </div>
                        <div class="form-group">
                            <label for="slideButtonLink">Button Link</label>
                            <input type="text" id="slideButtonLink" placeholder="e.g., #" value="#">
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label for="slideButtonStyle">Button Style</label>
                            <select id="slideButtonStyle">
                                <option value="btn--primary">Primary</option>
                                <option value="btn--white">White</option>
                                <option value="btn--white btn--bordered">White Bordered</option>
                                <option value="btn--white btn--bordered btn--lg">White Bordered Large</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="slideIsActive">Status</label>
                            <select id="slideIsActive">
                                <option value="1">Active</option>
                                <option value="0">Inactive</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group full-width">
                            <label for="slideImage">Slider Image *</label>
                            <div class="image-upload-wrapper">
                                <input type="file" id="slideImage" accept="image/*" required>
                                <div class="image-preview-container" id="imagePreviewContainer" style="display: none;">
                                    <img id="imagePreview" src="" alt="Preview" style="max-width: 300px; max-height: 200px; border-radius: 8px;">
                                    <button type="button" class="btn-remove-image" id="removeImageBtn">Remove Image</button>
                                </div>
                                <input type="hidden" id="slideImagePath">
                            </div>
                        </div>
                    </div>

                    <div class="form-actions">
                        <button type="submit" class="btn-action" id="submitBtn">Add Slider</button>
                        <button type="button" class="btn-action-secondary" id="cancelBtn">Cancel</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Password Change Modal -->
        <div id="passwordModal" class="modal" style="display: none;">
            <div class="modal-content" style="max-width: 400px;">
                <span class="close-modal" onclick="closePasswordModal()">&times;</span>
                <h2>Change Password</h2>
                
                <form id="passwordForm" style="margin-top: 20px;">
                    <div class="form-group" style="margin-bottom: 15px;">
                        <label for="currentPassword" style="display: block; margin-bottom: 8px; font-weight: 600;">Current Password</label>
                        <input type="password" id="currentPassword" name="currentPassword" placeholder="Enter current password" required 
                            style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; font-family: inherit;">
                    </div>

                    <div class="form-group" style="margin-bottom: 15px;">
                        <label for="newPassword" style="display: block; margin-bottom: 8px; font-weight: 600;">New Password</label>
                        <input type="password" id="newPassword" name="newPassword" placeholder="Enter new password (min 6 characters)" required 
                            style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; font-family: inherit;">
                    </div>

                    <div class="form-group" style="margin-bottom: 20px;">
                        <label for="confirmPassword" style="display: block; margin-bottom: 8px; font-weight: 600;">Confirm New Password</label>
                        <input type="password" id="confirmPassword" name="confirmPassword" placeholder="Confirm new password" required 
                            style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; font-family: inherit;">
                    </div>

                    <div style="display: flex; gap: 10px; justify-content: flex-end;">
                        <button type="button" class="close-modal" onclick="closePasswordModal()" 
                            style="padding: 10px 20px; background: #f0f0f0; color: #333; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">
                            Cancel
                        </button>
                        <button type="submit" style="padding: 10px 20px; background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%); color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">
                            Change Password
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Bookings Section -->
        <div id="bookings-section" class="section-content" style="display: none;">
            <div class="content-section">
                <div class="section-title">
                    <i class="fas fa-calendar-check"></i>
                    Manage Bookings
                </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>ID</th>
                                <th>Guest Name</th>
                                <th>Date</th>
                                <th>Guests</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody id="bookingsTable">
                            <tr>
                                <td colspan="6" style="text-align: center; color: #999;">Loading bookings...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Orders Section -->
        <div id="orders-section" class="section-content" style="display: none;">
            <div class="content-section">
                <div class="section-title">
                    <i class="fas fa-shopping-cart"></i>
                    Manage Orders
                </div>
                <div class="btn-group">
                    <button class="btn-action">
                        <i class="fas fa-plus"></i> New Order
                    </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>Order ID</th>
                                <th>Customer</th>
                                <th>Total</th>
                                <th>Status</th>
                                <th>Date</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody id="ordersTable">
                            <tr>
                                <td colspan="6" style="text-align: center; color: #999;">Loading orders...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Contacts Section -->
        <div id="contacts-section" class="section-content" style="display: none;">
            <div class="content-section">
                <div class="section-title">
                    <i class="fas fa-envelope"></i>
                    Contact Messages
                </div>
                <div class="table-responsive">
                    <table class="admin-table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Name</th>
                                <th>Email</th>
                                <th>Subject</th>
                                <th>Date</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody id="contactsTable">
                            <tr>
                                <td colspan="6" style="text-align: center; color: #999;">Loading contacts...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Feedback Section -->
        <div id="feedback-section" class="section-content" style="display: none;">
            <div class="content-section">
                <div class="section-title">
                    <i class="fas fa-comments"></i>
                    User Feedback
                </div>
                <div class="table-responsive">
                    <table class="admin-table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>User</th>
                                <th>Subject</th>
                                <th>Rating</th>
                                <th>Date</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody id="feedbackTable">
                            <tr>
                                <td colspan="6" style="text-align: center; color: #999;">Loading feedback...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Users Section -->
        <div id="users-section" class="section-content" style="display: none;">
            <div class="content-section">
                <div class="section-title">
                    <i class="fas fa-users"></i>
                    Manage Users
                </div>
                <div class="btn-group">
                    <button class="btn-action">
                        <i class="fas fa-plus"></i> Add User
                    </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>ID</th>
                                <th>Name</th>
                                <th>Email</th>
                                <th>Phone</th>
                                <th>Date</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody id="usersTable">
                            <tr>
                                <td colspan="6" style="text-align: center; color: #999;">Loading users...</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Settings Section -->
        <div id="settings-section" class="section-content" style="display: none;">
            <div class="content-section">
                <div class="section-title">
                    <i class="fas fa-cog"></i>
                    Settings
                </div>
                <p style="color: #666;">Settings and configuration options coming soon...</p>
            </div>
        </div>
    </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>

    <!-- Admin Dashboard 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();

            // Fetch and display dashboard statistics
            fetchDashboardStats();

            // Menu navigation
            const menuLinks = document.querySelectorAll('.menu-link');
            menuLinks.forEach(link => {
                link.addEventListener('click', function(e) {
                    e.preventDefault();
                    const section = this.getAttribute('data-section');
                    switchSection(section);
                    
                    // Close mobile menu
                    const sidebar = document.getElementById('sidebar');
                    const overlay = document.getElementById('menuOverlay');
                    sidebar.classList.remove('active');
                    overlay.classList.remove('active');
                });
            });

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

                // Close menu when clicking outside
                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';
                        });
                    }
                });
            });

            // Load dashboard data
            loadDashboardStats();

            // Auto-load sections
            const bookingsLink = document.querySelector('[data-section="bookings"]');
            const ordersLink = document.querySelector('[data-section="orders"]');
            const contactsLink = document.querySelector('[data-section="contacts"]');
            const feedbackLink = document.querySelector('[data-section="feedback"]');
            const usersLink = document.querySelector('[data-section="users"]');

            if (bookingsLink) {
                bookingsLink.addEventListener('click', loadBookings);
            }
            if (ordersLink) {
                ordersLink.addEventListener('click', loadOrders);
            }
            if (contactsLink) {
                contactsLink.addEventListener('click', loadContacts);
            }
            if (feedbackLink) {
                feedbackLink.addEventListener('click', loadFeedback);
            }
            if (usersLink) {
                usersLink.addEventListener('click', loadUsers);
            }

            // Load initial notification counts
            loadNotificationCounts();

            // Auto-refresh notification counts every 30 seconds
            setInterval(loadNotificationCounts, 30000);
        });

        function fetchDashboardStats() {
            fetch('../backend/get_dashboard_stats.php')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById('totalOrders').textContent = data.total_orders;
                        document.getElementById('totalBookings').textContent = data.total_bookings;
                        document.getElementById('totalContacts').textContent = data.total_contacts;
                        document.getElementById('totalUsers').textContent = data.total_users;
                    } else {
                        console.error('Failed to fetch stats:', data.message);
                        // Keep default values if fetch fails
                    }
                })
                .catch(error => {
                    console.error('Error fetching dashboard stats:', error);
                    // Keep default values if there's an error
                });
        }

        function switchSection(section) {
            // Hide all sections
            document.querySelectorAll('.section-content').forEach(el => {
                el.style.display = 'none';
            });

            // Remove active class from menu
            document.querySelectorAll('.menu-link').forEach(el => {
                el.classList.remove('active');
            });

            // Show selected section
            const sectionEl = document.getElementById(section + '-section');
            if (sectionEl) {
                sectionEl.style.display = 'block';
            }

            // Add active class to clicked menu
            document.querySelector(`[data-section="${section}"]`).classList.add('active');

            // Update topbar title
            const titles = {
                'dashboard': 'Dashboard',
                'sliders': 'Carousel Sliders',
                'bookings': 'Bookings',
                'orders': 'Orders',
                'contacts': 'Contacts',
                'feedback': 'Feedback',
                'users': 'Users',
                'settings': 'Settings'
            };
            document.getElementById('topbarTitle').textContent = titles[section] || 'Dashboard';

            // Load sliders when switching to sliders section
            if (section === 'sliders') {
                loadSliders();
            }
        }

        function loadDashboardStats() {
            // Fetch stats from backend
            console.log('Loading dashboard statistics...');
            
            fetch('../backend/get_recent_activity.php')
                .then(response => {
                    console.log('Recent Activity Response status:', response.status);
                    return response.json();
                })
                .then(data => {
                    console.log('Recent Activity API Response:', data);
                    displayRecentActivity(data);
                })
                .catch(error => {
                    console.error('Error loading recent activities:', error);
                    const container = document.getElementById('recentActivityContainer');
                    if (container) {
                        container.innerHTML = '<p style="color: #c0392b; text-align: center; padding: 30px;"><i class="fas fa-exclamation-circle"></i> Error loading activities</p>';
                    }
                });
        }

        function displayRecentActivity(data) {
            const container = document.getElementById('recentActivityContainer');
            if (!container) return;

            if (!data.success || !data.data || data.data.length === 0) {
                container.innerHTML = '<p style="color: #999; text-align: center; padding: 30px;"><i class="fas fa-inbox"></i> No recent activities</p>';
                return;
            }

            const activitiesHTML = data.data.map(activity => {
                const date = new Date(activity.time);
                const timeString = formatActivityTime(date);
                let typeColor = '#d4a574';
                
                if (activity.type === 'order') typeColor = '#3498db';
                else if (activity.type === 'booking') typeColor = '#2ecc71';
                else if (activity.type === 'contact') typeColor = '#e74c3c';
                else if (activity.type === 'feedback') typeColor = '#f39c12';

                return `
                    <div class="activity-item" style="
                        padding: 15px;
                        border-left: 4px solid ${typeColor};
                        background: #f9f9f9;
                        margin-bottom: 10px;
                        border-radius: 4px;
                        display: flex;
                        gap: 15px;
                    ">
                        <div style="
                            width: 40px;
                            height: 40px;
                            min-width: 40px;
                            border-radius: 50%;
                            background: ${typeColor}20;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                            color: ${typeColor};
                        ">
                            <i class="fas ${activity.icon}"></i>
                        </div>
                        <div style="flex: 1; min-width: 0;">
                            <div style="
                                font-weight: 600;
                                color: #333;
                                margin-bottom: 4px;
                            ">
                                ${escapeHtml(activity.description)}
                            </div>
                            <div style="
                                font-size: 12px;
                                color: #999;
                            ">
                                <i class="fas fa-clock"></i> ${timeString}
                            </div>
                        </div>
                        <div style="
                            display: flex;
                            align-items: center;
                        ">
                            <span class="status-badge ${activity.status}" style="
                                font-size: 11px;
                            ">${activity.status || activity.type}</span>
                        </div>
                    </div>
                `;
            }).join('');

            container.innerHTML = activitiesHTML;
        }

        function formatActivityTime(date) {
            const now = new Date();
            const diffMs = now - date;
            const diffMins = Math.floor(diffMs / 60000);
            const diffHours = Math.floor(diffMs / 3600000);
            const diffDays = Math.floor(diffMs / 86400000);

            if (diffMins < 1) return 'Just now';
            if (diffMins < 60) return diffMins + ' min ago';
            if (diffHours < 24) return diffHours + ' hour' + (diffHours > 1 ? 's' : '') + ' ago';
            if (diffDays < 7) return diffDays + ' day' + (diffDays > 1 ? 's' : '') + ' ago';
            
            return date.toLocaleDateString();
        }

        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        function loadBookings() {
            console.log('Loading bookings...');
            const tableBody = document.getElementById('bookingsTable');
            tableBody.innerHTML = '<tr><td colspan="6" 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 => `
                            <tr>
                                <td>${booking.id}</td>
                                <td>${booking.name}</td>
                                <td>${new Date(booking.booking_date).toLocaleDateString()}</td>
                                <td>${booking.guests}</td>
                                <td><span class="status-badge ${booking.status}">${booking.status}</span></td>
                                <td>
                                    <button class="btn-view" onclick="viewBooking(${booking.id})">
                                        <i class="fas fa-eye"></i> View
                                    </button>
                                </td>
                            </tr>
                        `).join('');
                    } else {
                        const message = data.success === false ? 
                            `<tr><td colspan="6" style="text-align: center; color: #c0392b;">Error: ${data.message}</td></tr>` :
                            '<tr><td colspan="6" 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="6" style="text-align: center; color: #c0392b;">Error: ' + error.message + '</td></tr>';
                });
        }

        function loadOrders() {
            console.log('Loading orders...');
            const tableBody = document.getElementById('ordersTable');
            tableBody.innerHTML = '<tr><td colspan="6" style="text-align: center; color: #999;">Loading orders...</td></tr>';
            
            fetch('../backend/admin_orders_api.php')
                .then(response => {
                    console.log('Orders Response status:', response.status);
                    return response.json();
                })
                .then(data => {
                    console.log('Orders API Response:', data);
                    if (data.success && data.data && data.data.length > 0) {
                        tableBody.innerHTML = data.data.map(order => `
                            <tr>
                                <td>#${order.order_number || order.id}</td>
                                <td>${order.full_name}</td>
                                <td>$${parseFloat(order.total).toFixed(2)}</td>
                                <td><span class="status-badge ${order.status}">${order.status}</span></td>
                                <td>${new Date(order.created_at).toLocaleDateString()}</td>
                                <td>
                                    <button class="btn-view" onclick="viewOrder(${order.id})">
                                        <i class="fas fa-eye"></i> View
                                    </button>
                                </td>
                            </tr>
                        `).join('');
                    } else {
                        const message = data.success === false ? 
                            `<tr><td colspan="6" style="text-align: center; color: #c0392b;">Error: ${data.message}</td></tr>` :
                            '<tr><td colspan="6" style="text-align: center; color: #999;">No orders found</td></tr>';
                        tableBody.innerHTML = message;
                    }
                })
                .catch(error => {
                    console.error('Error loading orders:', error);
                    tableBody.innerHTML = '<tr><td colspan="6" style="text-align: center; color: #c0392b;">Error: ' + error.message + '</td></tr>';
                });
        }

        function loadContacts() {
            console.log('Loading contacts...');
            const tableBody = document.getElementById('contactsTable');
            tableBody.innerHTML = '<tr><td colspan="6" style="text-align: center; color: #999;">Loading contacts...</td></tr>';
            
            fetch('../backend/admin_contacts_api.php')
                .then(response => {
                    console.log('Contacts Response status:', response.status);
                    return response.json();
                })
                .then(data => {
                    console.log('Contacts API Response:', data);
                    if (data.success && data.data && data.data.length > 0) {
                        tableBody.innerHTML = data.data.map(contact => `
                            <tr>
                                <td>${contact.id}</td>
                                <td>${contact.name}</td>
                                <td>${contact.email}</td>
                                <td>${contact.subject}</td>
                                <td>${new Date(contact.created_at).toLocaleDateString()}</td>
                                <td><span class="status-badge ${contact.status}">${contact.status}</span></td>
                            </tr>
                        `).join('');
                    } else {
                        const message = data.success === false ? 
                            `<tr><td colspan="6" style="text-align: center; color: #c0392b;">Error: ${data.message}</td></tr>` :
                            '<tr><td colspan="6" style="text-align: center; color: #999;">No contacts found</td></tr>';
                        tableBody.innerHTML = message;
                    }
                })
                .catch(error => {
                    console.error('Error loading contacts:', error);
                    tableBody.innerHTML = '<tr><td colspan="6" style="text-align: center; color: #c0392b;">Error: ' + error.message + '</td></tr>';
                });
        }

        function loadFeedback() {
            console.log('Loading feedback...');
            const tableBody = document.getElementById('feedbackTable');
            tableBody.innerHTML = '<tr><td colspan="6" style="text-align: center; color: #999;">Loading feedback...</td></tr>';
            
            fetch('../backend/admin_feedback_api.php')
                .then(response => {
                    console.log('Feedback Response status:', response.status);
                    return response.json();
                })
                .then(data => {
                    console.log('Feedback API Response:', data);
                    if (data.success && data.data && data.data.length > 0) {
                        tableBody.innerHTML = data.data.map(feedback => `
                            <tr>
                                <td>${feedback.id}</td>
                                <td>User #${feedback.user_id}</td>
                                <td>${feedback.subject}</td>
                                <td>
                                    <span style="color: #d4a574; font-weight: 700;">
                                        ${'★'.repeat(feedback.rating)}${'☆'.repeat(5 - feedback.rating)}
                                    </span>
                                </td>
                                <td>${new Date(feedback.created_at).toLocaleDateString()}</td>
                                <td><span class="status-badge ${feedback.status}">${feedback.status}</span></td>
                            </tr>
                        `).join('');
                    } else {
                        const message = data.success === false ? 
                            `<tr><td colspan="6" style="text-align: center; color: #c0392b;">Error: ${data.message}</td></tr>` :
                            '<tr><td colspan="6" style="text-align: center; color: #999;">No feedback found</td></tr>';
                        tableBody.innerHTML = message;
                    }
                })
                .catch(error => {
                    console.error('Error loading feedback:', error);
                    tableBody.innerHTML = '<tr><td colspan="6" style="text-align: center; color: #c0392b;">Error: ' + error.message + '</td></tr>';
                });
        }

        function loadUsers() {
            console.log('Loading users...');
            const tableBody = document.getElementById('usersTable');
            tableBody.innerHTML = '<tr><td colspan="6" style="text-align: center; color: #999;">Loading users...</td></tr>';
            
            fetch('../backend/admin_users_api.php')
                .then(response => {
                    console.log('Response status:', response.status);
                    return response.json();
                })
                .then(data => {
                    console.log('Users API Response:', data);
                    if (data.success && data.data && data.data.length > 0) {
                        tableBody.innerHTML = data.data.map(user => `
                            <tr>
                                <td>${user.id}</td>
                                <td>${user.name}</td>
                                <td>${user.email}</td>
                                <td>${user.phone || 'N/A'}</td>
                                <td>${new Date(user.created_at).toLocaleDateString()}</td>
                                <td>
                                    <button class="btn-view" onclick="viewUser(${user.id})">
                                        <i class="fas fa-eye"></i> View
                                    </button>
                                </td>
                            </tr>
                        `).join('');
                    } else {
                        const message = data.success === false ? 
                            `<tr><td colspan="6" style="text-align: center; color: #c0392b;">Error: ${data.message}</td></tr>` :
                            '<tr><td colspan="6" style="text-align: center; color: #999;">No users found</td></tr>';
                        tableBody.innerHTML = message;
                    }
                })
                .catch(error => {
                    console.error('Error loading users:', error);
                    tableBody.innerHTML = '<tr><td colspan="6" style="text-align: center; color: #c0392b;">Error: ' + error.message + '</td></tr>';
                });
        }

        // Load notification counts and update badges
        function loadNotificationCounts() {
            // Load bookings count
            fetch('../backend/admin_bookings_api.php?action=new_count')
                .then(response => response.json())
                .then(data => {
                    updateBadge('bookings', data.count);
                })
                .catch(error => console.error('Error loading bookings count:', error));

            // Load orders count
            fetch('../backend/admin_orders_api.php?action=new_count')
                .then(response => response.json())
                .then(data => {
                    updateBadge('orders', data.count);
                })
                .catch(error => console.error('Error loading orders count:', error));

            // Load contacts count
            fetch('../backend/admin_contacts_api.php?action=new_count')
                .then(response => response.json())
                .then(data => {
                    updateBadge('contacts', data.count);
                })
                .catch(error => console.error('Error loading contacts count:', error));

            // Load feedback count
            fetch('../backend/admin_feedback_api.php?action=new_count')
                .then(response => response.json())
                .then(data => {
                    updateBadge('feedback', data.count);
                })
                .catch(error => console.error('Error loading feedback count:', error));

            // Load users count
            fetch('../backend/admin_users_api.php?action=new_count')
                .then(response => response.json())
                .then(data => {
                    updateBadge('users', data.count);
                })
                .catch(error => console.error('Error loading users count:', error));
        }

        // Update notification badge
        function updateBadge(type, count) {
            const badge = document.querySelector(`.notification-badge[data-type="${type}"]`);
            if (badge) {
                if (count > 0) {
                    badge.textContent = count > 99 ? '99+' : count;
                    badge.classList.remove('hidden');
                } else {
                    badge.classList.add('hidden');
                }
            }
        }

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

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

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

        // ========== SLIDER MANAGEMENT ==========
        const sliderModal = document.getElementById('sliderModal');
        const addSliderBtn = document.getElementById('addSliderBtn');
        const cancelBtn = document.getElementById('cancelBtn');
        const closeModal = document.querySelector('.close-modal');
        const sliderForm = document.getElementById('sliderForm');
        const slideImage = document.getElementById('slideImage');
        const imagePreview = document.getElementById('imagePreview');
        const imagePreviewContainer = document.getElementById('imagePreviewContainer');
        const removeImageBtn = document.getElementById('removeImageBtn');
        const slideImagePath = document.getElementById('slideImagePath');

        // Open modal for adding new slider
        addSliderBtn.addEventListener('click', () => {
            resetSliderForm();
            document.getElementById('modalTitle').textContent = 'Add New Slider';
            document.getElementById('submitBtn').textContent = 'Add Slider';
            sliderModal.style.display = 'flex';
        });

        // Close modal
        cancelBtn.addEventListener('click', () => {
            sliderModal.style.display = 'none';
        });

        closeModal.addEventListener('click', () => {
            sliderModal.style.display = 'none';
        });

        // Close modal when clicking outside
        sliderModal.addEventListener('click', (e) => {
            if (e.target === sliderModal) {
                sliderModal.style.display = 'none';
            }
        });

        // Make upload wrapper clickable
        const imageUploadWrapper = document.querySelector('.image-upload-wrapper');
        if (imageUploadWrapper) {
            imageUploadWrapper.addEventListener('click', (e) => {
                if (e.target.tagName !== 'BUTTON') {
                    slideImage.click();
                }
            });
        }

        // Image upload handler
        slideImage.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = (event) => {
                    imagePreview.src = event.target.result;
                    imagePreviewContainer.style.display = 'flex';
                };
                reader.readAsDataURL(file);
            }
        });

        // Remove image
        removeImageBtn.addEventListener('click', (e) => {
            e.preventDefault();
            slideImage.value = '';
            slideImagePath.value = '';
            imagePreviewContainer.style.display = 'none';
        });

        // Submit slider form
        sliderForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            const sliderId = document.getElementById('sliderId').value;
            const isEditing = !!sliderId;

            // Handle image upload if new image is selected
            let imagePath = slideImagePath.value;
            if (slideImage.files.length > 0) {
                const formData = new FormData();
                formData.append('image', slideImage.files[0]);
                
                try {
                    const response = await fetch('../backend/sliders_api.php?action=upload_image', {
                        method: 'POST',
                        body: formData
                    });
                    const result = await response.json();
                    if (result.success) {
                        imagePath = result.data.path;
                    } else {
                        Swal.fire('Error', result.message, 'error');
                        return;
                    }
                } catch (error) {
                    Swal.fire('Error', 'Failed to upload image', 'error');
                    return;
                }
            }

            if (!imagePath) {
                Swal.fire('Error', 'Please select an image', 'error');
                return;
            }

            const sliderData = {
                image_path: imagePath,
                subheadline: document.getElementById('slideSubheadline').value,
                headline: document.getElementById('slideHeadline').value,
                description: document.getElementById('slideDescription').value,
                button_text: document.getElementById('slideButtonText').value,
                button_link: document.getElementById('slideButtonLink').value,
                button_style: document.getElementById('slideButtonStyle').value,
                is_active: parseInt(document.getElementById('slideIsActive').value)
            };

            if (isEditing) {
                sliderData.id = sliderId;
            }

            const url = isEditing ? '../backend/sliders_api.php?action=update' : '../backend/sliders_api.php?action=create';
            const method = 'POST';

            try {
                const response = await fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(sliderData)
                });

                const result = await response.json();
                if (result.success) {
                    Swal.fire('Success', isEditing ? 'Slider updated successfully' : 'Slider created successfully', 'success');
                    sliderModal.style.display = 'none';
                    loadSliders();
                } else {
                    Swal.fire('Error', result.message, 'error');
                }
            } catch (error) {
                Swal.fire('Error', 'Failed to save slider', 'error');
                console.error(error);
            }
        });

        // Load all sliders
        async function loadSliders() {
            try {
                const response = await fetch('../backend/sliders_api.php?action=get_all');
                const result = await response.json();
                
                const container = document.getElementById('slidersContainer');
                
                if (result.success && result.data.length > 0) {
                    container.innerHTML = result.data.map(slider => `
                        <div class="slider-card" data-id="${slider.id}">
                            <img src="../${slider.image_path}" alt="${slider.headline}" class="slider-image">
                            <div class="slider-info">
                                <div class="slider-subheadline">${slider.subheadline || 'N/A'}</div>
                                <h3 class="slider-headline">${slider.headline}</h3>
                                <p class="slider-description">${slider.description ? slider.description.substring(0, 100) + '...' : 'No description'}</p>
                                <span class="slider-status ${slider.is_active ? 'active' : 'inactive'}">
                                    ${slider.is_active ? 'Active' : 'Inactive'}
                                </span>
                                <div class="slider-actions">
                                    <button class="btn-edit" onclick="editSlider(${slider.id})">
                                        <i class="fas fa-edit"></i> Edit
                                    </button>
                                    <button class="btn-delete" onclick="deleteSlider(${slider.id})">
                                        <i class="fas fa-trash"></i> Delete
                                    </button>
                                </div>
                            </div>
                        </div>
                    `).join('');
                } else {
                    container.innerHTML = '<p style="grid-column: 1/-1; text-align: center; color: #999; padding: 40px;">No sliders found. Add one to get started!</p>';
                }
            } catch (error) {
                console.error('Error loading sliders:', error);
                document.getElementById('slidersContainer').innerHTML = '<p style="color: #c0392b; text-align: center;">Failed to load sliders</p>';
            }
        }

        // Edit slider
        async function editSlider(id) {
            try {
                const response = await fetch(`../backend/sliders_api.php?action=get&id=${id}`);
                const result = await response.json();
                
                if (result.success) {
                    const slider = result.data;
                    
                    document.getElementById('sliderId').value = slider.id;
                    document.getElementById('slideSubheadline').value = slider.subheadline || '';
                    document.getElementById('slideHeadline').value = slider.headline;
                    document.getElementById('slideDescription').value = slider.description || '';
                    document.getElementById('slideButtonText').value = slider.button_text || '';
                    document.getElementById('slideButtonLink').value = slider.button_link || '#';
                    document.getElementById('slideButtonStyle').value = slider.button_style || 'btn--primary';
                    document.getElementById('slideIsActive').value = slider.is_active;
                    document.getElementById('slideImagePath').value = slider.image_path;
                    
                    // Show image preview
                    imagePreview.src = '../' + slider.image_path;
                    imagePreviewContainer.style.display = 'flex';
                    
                    // Hide file input requirement
                    slideImage.required = false;
                    
                    document.getElementById('modalTitle').textContent = 'Edit Slider';
                    document.getElementById('submitBtn').textContent = 'Update Slider';
                    sliderModal.style.display = 'flex';
                } else {
                    Swal.fire('Error', result.message, 'error');
                }
            } catch (error) {
                Swal.fire('Error', 'Failed to load slider', 'error');
                console.error(error);
            }
        }

        // Delete slider
        async function deleteSlider(id) {
            const result = await Swal.fire({
                title: 'Delete Slider?',
                text: 'This action cannot be undone.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#c0392b',
                cancelButtonColor: '#999',
                confirmButtonText: 'Delete',
                cancelButtonText: 'Cancel'
            });

            if (result.isConfirmed) {
                try {
                    const response = await fetch('../backend/sliders_api.php?action=delete', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ id: id })
                    });

                    const deleteResult = await response.json();
                    if (deleteResult.success) {
                        Swal.fire('Deleted', 'Slider deleted successfully', 'success');
                        loadSliders();
                    } else {
                        Swal.fire('Error', deleteResult.message, 'error');
                    }
                } catch (error) {
                    Swal.fire('Error', 'Failed to delete slider', 'error');
                    console.error(error);
                }
            }
        }

        // Reset slider form
        function resetSliderForm() {
            sliderForm.reset();
            document.getElementById('sliderId').value = '';
            slideImagePath.value = '';
            imagePreviewContainer.style.display = 'none';
            slideImage.required = true;
        }

        // Password Modal Functions
        function openPasswordModal() {
            document.getElementById('passwordModal').style.display = 'flex';
        }

        function closePasswordModal() {
            document.getElementById('passwordModal').style.display = 'none';
            document.getElementById('passwordForm').reset();
        }

        // Password form submission
        document.getElementById('passwordForm').addEventListener('submit', function(e) {
            e.preventDefault();

            const currentPassword = document.getElementById('currentPassword').value;
            const newPassword = document.getElementById('newPassword').value;
            const confirmPassword = document.getElementById('confirmPassword').value;

            // Validate passwords
            if (!currentPassword || !newPassword || !confirmPassword) {
                closePasswordModal();
                Swal.fire('Error', 'All fields are required', 'error');
                return;
            }

            if (newPassword.length < 6) {
                closePasswordModal();
                Swal.fire('Error', 'New password must be at least 6 characters', 'error');
                return;
            }

            if (newPassword !== confirmPassword) {
                closePasswordModal();
                Swal.fire('Error', 'New passwords do not match', 'error');
                return;
            }

            // Show loading state
            closePasswordModal();

            // Send to backend
            fetch('../backend/admin_password_api.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: 'change_password',
                    current_password: currentPassword,
                    new_password: newPassword,
                    confirm_password: confirmPassword
                })
            })
            .then(response => response.json())
            .then(data => {
                console.log('Password API Response:', data);
                if (data.success) {
                    Swal.fire('Success', data.message, 'success');
                    document.getElementById('passwordForm').reset();
                } else {
                    Swal.fire('Error', data.message || 'Failed to change password', 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                Swal.fire('Error', 'Network error: ' + error.message, 'error');
            });
        });

        // Close modal when clicking X
        document.getElementById('passwordModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closePasswordModal();
            }
        });
    </script>
</body>

</html>
