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

        /* Tabs */
        .tabs-container {
            display: flex;
            gap: 10px;
            margin-bottom: 30px;
            border-bottom: 2px solid #e8e8e8;
        }

        .tab-btn {
            padding: 12px 25px;
            background: none;
            border: none;
            color: #999;
            cursor: pointer;
            font-weight: 600;
            font-size: 14px;
            position: relative;
            transition: all 0.3s ease;
            border-bottom: 3px solid transparent;
            margin-bottom: -2px;
        }

        .tab-btn:hover {
            color: #d4a574;
        }

        .tab-btn.active {
            color: #d4a574;
            border-bottom-color: #d4a574;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        /* Categories Grid */
        .categories-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .category-card {
            background: white;
            border: 2px solid #e8e8e8;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            transition: all 0.3s ease;
        }

        .category-card:hover {
            border-color: #d4a574;
            box-shadow: 0 5px 15px rgba(212, 165, 116, 0.2);
            transform: translateY(-3px);
        }

        .category-card h4 {
            font-size: 16px;
            color: #2c3e50;
            margin-bottom: 10px;
            font-weight: 700;
        }

        .category-card p {
            font-size: 12px;
            color: #999;
            margin-bottom: 15px;
        }

        .category-actions {
            display: flex;
            gap: 8px;
            justify-content: center;
        }

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

        .btn-small:hover {
            background: #8b6f47;
        }

        .btn-small.delete {
            background: #e74c3c;
        }

        .btn-small.delete:hover {
            background: #c0392b;
        }

        /* Photos Grid */
        .photos-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .photo-card {
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
            transition: all 0.3s ease;
        }

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

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

        .photo-info {
            padding: 15px;
        }

        .photo-name {
            font-size: 14px;
            color: #2c3e50;
            font-weight: 600;
            margin-bottom: 5px;
        }

        .photo-category {
            font-size: 11px;
            color: #d4a574;
            font-weight: 600;
            text-transform: uppercase;
            margin-bottom: 10px;
        }

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

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

        .modal-content {
            background: white;
            padding: 40px;
            border-radius: 10px;
            width: 90%;
            max-width: 600px;
            max-height: 90vh;
            overflow-y: auto;
            position: relative;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
        }

        .modal-content h2 {
            font-size: 24px;
            color: #2c3e50;
            margin-bottom: 25px;
        }

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

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

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

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

        .form-group input,
        .form-group 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;
            width: 100%;
        }

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

        .image-upload-wrapper {
            position: relative;
            border: 2px dashed #d4a574;
            border-radius: 8px;
            padding: 30px;
            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;
        }

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

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

            .topbar {
                left: 250px;
            }

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

            .categories-grid,
            .photos-grid {
                grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            }
        }

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

            .categories-grid,
            .photos-grid {
                grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
                gap: 15px;
            }

            .modal-content {
                padding: 30px;
            }

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

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

            .main-content {
                padding: 15px;
            }

            .content-section {
                padding: 20px;
            }

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

            .btn-action {
                width: 100%;
            }

            .categories-grid,
            .photos-grid {
                grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
                gap: 10px;
            }

            .modal-content {
                padding: 20px;
                width: 95%;
            }

            .photo-image {
                height: 150px;
            }
        }
    </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" class="active"><i class="fas fa-image"></i> <span>Gallery</span></a></li>
            <li><a href="chefs.php"><i class="fas fa-user-tie"></i> <span>Chefs</span></a></li>
            <li><a href="menu.php"><i class="fas fa-utensils"></i> <span>Menu</span></a></li>
            <li><a href="tables.php"><i class="fas fa-chair"></i> <span>Dine-in Tables</span></a></li>
            <li><a href="online_tables.php"><i class="fas fa-laptop"></i> <span>Online Tables</span></a></li>
            <li><a href="bookings.php"><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">Gallery Management</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">
        <!-- Tabs -->
        <div class="tabs-container">
            <button class="tab-btn active" data-tab="categories">
                <i class="fas fa-tag"></i> Categories
            </button>
            <button class="tab-btn" data-tab="photos">
                <i class="fas fa-image"></i> Photos
            </button>
        </div>

        <!-- Categories Tab -->
        <div id="categories" class="tab-content active">
            <div class="content-section">
                <div class="section-title">
                    <i class="fas fa-tag"></i>
                    Manage Categories
                </div>
                <p style="color: #999; margin-bottom: 20px;">Create and manage gallery categories before uploading photos</p>
                <div class="btn-group">
                    <button class="btn-action" id="addCategoryBtn">
                        <i class="fas fa-plus"></i> Add Category
                    </button>
                </div>

                <!-- Categories Grid -->
                <div id="categoriesContainer" class="categories-grid">
                    <p style="text-align: center; color: #999; padding: 40px; grid-column: 1/-1;">Loading categories...</p>
                </div>
            </div>
        </div>

        <!-- Photos Tab -->
        <div id="photos" class="tab-content">
            <div class="content-section">
                <div class="section-title">
                    <i class="fas fa-image"></i>
                    Manage Gallery Photos
                </div>
                <p style="color: #999; margin-bottom: 20px;">Add, edit, or delete photos from your gallery</p>
                <div class="btn-group">
                    <button class="btn-action" id="addPhotoBtn">
                        <i class="fas fa-plus"></i> Upload Photo
                    </button>
                </div>

                <!-- Category Filter -->
                <div style="margin-bottom: 20px;">
                    <label style="font-weight: 600; color: #2c3e50; margin-right: 10px;">Filter by Category:</label>
                    <select id="categoryFilter" style="padding: 10px; border: 1px solid #e0e0e0; border-radius: 6px; font-size: 14px;">
                        <option value="">All Photos</option>
                    </select>
                </div>

                <!-- Photos Grid -->
                <div id="photosContainer" class="photos-grid">
                    <p style="text-align: center; color: #999; padding: 40px; grid-column: 1/-1;">Loading photos...</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Add/Edit Category Modal -->
    <div id="categoryModal" class="modal" style="display: none;">
        <div class="modal-content" style="max-width: 500px;">
            <span class="close-modal" id="closeCategoryModal">&times;</span>
            <h2 id="categoryModalTitle">Add New Category</h2>
            
            <form id="categoryForm">
                <input type="hidden" id="categoryId">

                <div class="form-group">
                    <label for="categoryName">Category Name *</label>
                    <input type="text" id="categoryName" placeholder="e.g., Food, Ambiance, Team" required>
                </div>

                <div class="form-group">
                    <label for="categoryDescription">Description</label>
                    <textarea id="categoryDescription" placeholder="Brief description of this category" rows="3"></textarea>
                </div>

                <div class="form-actions">
                    <button type="submit" class="btn-action" id="submitCategoryBtn">Add Category</button>
                    <button type="button" class="btn-action-secondary" id="cancelCategoryBtn">Cancel</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Add/Edit Photo Modal -->
    <div id="photoModal" class="modal" style="display: none;">
        <div class="modal-content" style="max-width: 600px;">
            <span class="close-modal" id="closePhotoModal">&times;</span>
            <h2 id="photoModalTitle">Upload New Photo</h2>
            
            <form id="photoForm">
                <input type="hidden" id="photoId">

                <div class="form-group">
                    <label for="photoCategory">Category *</label>
                    <select id="photoCategory" required>
                        <option value="">Select a category</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="photoName">Photo Name *</label>
                    <input type="text" id="photoName" placeholder="e.g., Grilled Salmon" required>
                </div>

                <div class="form-group">
                    <label for="photoImage">Photo Image *</label>
                    <div class="image-upload-wrapper">
                        <input type="file" id="photoImage" 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="photoImagePath">
                    </div>
                </div>

                <div class="form-actions">
                    <button type="submit" class="btn-action" id="submitPhotoBtn">Upload Photo</button>
                    <button type="button" class="btn-action-secondary" id="cancelPhotoBtn">Cancel</button>
                </div>
            </form>
        </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>

    <!-- Gallery Management 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);
            document.getElementById('sidebarAdminName').textContent = admin.name;
            document.getElementById('topbarUserName').textContent = admin.name;
            document.getElementById('userInitial').textContent = admin.name.charAt(0).toUpperCase();

            // Load initial data
            loadCategories();
            loadPhotos();

            // Tab switching
            document.querySelectorAll('.tab-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const tabName = this.getAttribute('data-tab');
                    switchTab(tabName);
                });
            });

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

            loadNotificationCounts();
            setInterval(loadNotificationCounts, 30000);
        });

        // Tab switching function
        function switchTab(tabName) {
            document.querySelectorAll('.tab-content').forEach(el => {
                el.classList.remove('active');
            });
            document.querySelectorAll('.tab-btn').forEach(el => {
                el.classList.remove('active');
            });

            document.getElementById(tabName).classList.add('active');
            event.target.closest('.tab-btn').classList.add('active');
        }

        // ========== CATEGORY MANAGEMENT ==========
        const categoryModal = document.getElementById('categoryModal');
        const addCategoryBtn = document.getElementById('addCategoryBtn');
        const closeCategoryModal = document.getElementById('closeCategoryModal');
        const categoryForm = document.getElementById('categoryForm');
        const cancelCategoryBtn = document.getElementById('cancelCategoryBtn');

        addCategoryBtn.addEventListener('click', () => {
            resetCategoryForm();
            document.getElementById('categoryModalTitle').textContent = 'Add New Category';
            document.getElementById('submitCategoryBtn').textContent = 'Add Category';
            categoryModal.style.display = 'flex';
        });

        closeCategoryModal.addEventListener('click', () => {
            categoryModal.style.display = 'none';
        });

        cancelCategoryBtn.addEventListener('click', () => {
            categoryModal.style.display = 'none';
        });

        categoryModal.addEventListener('click', (e) => {
            if (e.target === categoryModal) {
                categoryModal.style.display = 'none';
            }
        });

        categoryForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            const categoryId = document.getElementById('categoryId').value;
            const isEditing = !!categoryId;

            const categoryData = {
                name: document.getElementById('categoryName').value,
                description: document.getElementById('categoryDescription').value
            };

            if (isEditing) {
                categoryData.id = categoryId;
            }

            const url = isEditing ? '../backend/gallery_api.php?action=update_category' : '../backend/gallery_api.php?action=create_category';

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

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

        function resetCategoryForm() {
            categoryForm.reset();
            document.getElementById('categoryId').value = '';
        }

        async function loadCategories() {
            try {
                const response = await fetch('../backend/gallery_api.php?action=get_categories');
                const result = await response.json();
                
                const container = document.getElementById('categoriesContainer');
                const categoryFilter = document.getElementById('categoryFilter');
                
                // Clear existing options (except "All Photos")
                while (categoryFilter.options.length > 1) {
                    categoryFilter.remove(1);
                }

                if (result.success && result.data.length > 0) {
                    container.innerHTML = result.data.map(category => `
                        <div class="category-card">
                            <h4>${category.name}</h4>
                            <p>${category.description || 'No description'}</p>
                            <div class="category-actions">
                                <button class="btn-small" onclick="editCategory(${category.id})">
                                    <i class="fas fa-edit"></i> Edit
                                </button>
                                <button class="btn-small delete" onclick="deleteCategory(${category.id})">
                                    <i class="fas fa-trash"></i> Delete
                                </button>
                            </div>
                        </div>
                    `).join('');

                    // Add categories to filter dropdown
                    result.data.forEach(category => {
                        const option = document.createElement('option');
                        option.value = category.id;
                        option.textContent = category.name;
                        categoryFilter.appendChild(option);
                    });
                } else {
                    container.innerHTML = '<p style="grid-column: 1/-1; text-align: center; color: #999; padding: 40px;">No categories found. Create one to get started!</p>';
                }
            } catch (error) {
                console.error('Error loading categories:', error);
                document.getElementById('categoriesContainer').innerHTML = '<p style="color: #c0392b; text-align: center;">Failed to load categories</p>';
            }
        }

        async function editCategory(id) {
            try {
                const response = await fetch(`../backend/gallery_api.php?action=get_category&id=${id}`);
                const result = await response.json();
                
                if (result.success) {
                    const category = result.data;
                    document.getElementById('categoryId').value = category.id;
                    document.getElementById('categoryName').value = category.name;
                    document.getElementById('categoryDescription').value = category.description || '';
                    
                    document.getElementById('categoryModalTitle').textContent = 'Edit Category';
                    document.getElementById('submitCategoryBtn').textContent = 'Update Category';
                    categoryModal.style.display = 'flex';
                } else {
                    Swal.fire('Error', result.message, 'error');
                }
            } catch (error) {
                Swal.fire('Error', 'Failed to load category', 'error');
                console.error(error);
            }
        }

        async function deleteCategory(id) {
            const result = await Swal.fire({
                title: 'Delete Category?',
                text: 'This action cannot be undone. Photos in this category will remain but lose category assignment.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#c0392b',
                cancelButtonColor: '#999',
                confirmButtonText: 'Delete',
                cancelButtonText: 'Cancel'
            });

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

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

        // ========== PHOTO MANAGEMENT ==========
        const photoModal = document.getElementById('photoModal');
        const addPhotoBtn = document.getElementById('addPhotoBtn');
        const closePhotoModal = document.getElementById('closePhotoModal');
        const photoForm = document.getElementById('photoForm');
        const cancelPhotoBtn = document.getElementById('cancelPhotoBtn');
        const photoImage = document.getElementById('photoImage');
        const imagePreview = document.getElementById('imagePreview');
        const imagePreviewContainer = document.getElementById('imagePreviewContainer');
        const removeImageBtn = document.getElementById('removeImageBtn');
        const photoImagePath = document.getElementById('photoImagePath');
        const categoryFilter = document.getElementById('categoryFilter');

        addPhotoBtn.addEventListener('click', async () => {
            resetPhotoForm();
            document.getElementById('photoModalTitle').textContent = 'Upload New Photo';
            document.getElementById('submitPhotoBtn').textContent = 'Upload Photo';
            
            // Load fresh categories for the dropdown
            try {
                const response = await fetch('../backend/gallery_api.php?action=get_categories');
                const result = await response.json();
                
                const photoCategorySelect = document.getElementById('photoCategory');
                // Clear existing options (except "Select a category")
                while (photoCategorySelect.options.length > 1) {
                    photoCategorySelect.remove(1);
                }
                
                if (result.success && result.data.length > 0) {
                    result.data.forEach(category => {
                        const option = document.createElement('option');
                        option.value = category.id;
                        option.textContent = category.name;
                        photoCategorySelect.appendChild(option);
                    });
                }
            } catch (error) {
                console.error('Error loading categories:', error);
            }
            
            photoModal.style.display = 'flex';
        });

        closePhotoModal.addEventListener('click', () => {
            photoModal.style.display = 'none';
        });

        cancelPhotoBtn.addEventListener('click', () => {
            photoModal.style.display = 'none';
        });

        photoModal.addEventListener('click', (e) => {
            if (e.target === photoModal) {
                photoModal.style.display = 'none';
            }
        });

        // Image upload handler
        photoImage.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();
            photoImage.value = '';
            photoImagePath.value = '';
            imagePreviewContainer.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') {
                    photoImage.click();
                }
            });
        }

        // Submit photo form
        photoForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            const photoId = document.getElementById('photoId').value;
            const isEditing = !!photoId;

            let imagePath = photoImagePath.value;
            if (photoImage.files.length > 0) {
                const formData = new FormData();
                formData.append('image', photoImage.files[0]);
                
                try {
                    const response = await fetch('../backend/gallery_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 photoData = {
                category_id: document.getElementById('photoCategory').value,
                name: document.getElementById('photoName').value,
                image_path: imagePath
            };

            if (isEditing) {
                photoData.id = photoId;
            }

            const url = isEditing ? '../backend/gallery_api.php?action=update_photo' : '../backend/gallery_api.php?action=create_photo';

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

                const result = await response.json();
                if (result.success) {
                    Swal.fire('Success', isEditing ? 'Photo updated successfully' : 'Photo uploaded successfully', 'success');
                    photoModal.style.display = 'none';
                    loadPhotos();
                } else {
                    Swal.fire('Error', result.message, 'error');
                }
            } catch (error) {
                Swal.fire('Error', 'Failed to save photo', 'error');
                console.error(error);
            }
        });

        function resetPhotoForm() {
            photoForm.reset();
            document.getElementById('photoId').value = '';
            photoImagePath.value = '';
            imagePreviewContainer.style.display = 'none';
            photoImage.required = true;
        }

        async function loadPhotos() {
            try {
                const response = await fetch('../backend/gallery_api.php?action=get_photos');
                const result = await response.json();
                
                const container = document.getElementById('photosContainer');
                const photoCategorySelect = document.getElementById('photoCategory');

                // Clear existing options (except "Select a category")
                while (photoCategorySelect.options.length > 1) {
                    photoCategorySelect.remove(1);
                }

                if (result.success && result.data.length > 0) {
                    container.innerHTML = result.data.map(photo => `
                        <div class="photo-card">
                            <img src="../${photo.image_path}" alt="${photo.name}" class="photo-image">
                            <div class="photo-info">
                                <div class="photo-category">${photo.category_name || 'Uncategorized'}</div>
                                <div class="photo-name">${photo.name}</div>
                                <div class="photo-actions">
                                    <button class="btn-small" onclick="editPhoto(${photo.id})" style="flex: 1;">
                                        <i class="fas fa-edit"></i> Edit
                                    </button>
                                    <button class="btn-small delete" onclick="deletePhoto(${photo.id})" style="flex: 1;">
                                        <i class="fas fa-trash"></i> Delete
                                    </button>
                                </div>
                            </div>
                        </div>
                    `).join('');

                    // Load categories for photo form
                    if (result.categories) {
                        result.categories.forEach(category => {
                            const option = document.createElement('option');
                            option.value = category.id;
                            option.textContent = category.name;
                            photoCategorySelect.appendChild(option);
                        });
                    }
                } else {
                    container.innerHTML = '<p style="grid-column: 1/-1; text-align: center; color: #999; padding: 40px;">No photos found. Upload one to get started!</p>';
                }
            } catch (error) {
                console.error('Error loading photos:', error);
                document.getElementById('photosContainer').innerHTML = '<p style="color: #c0392b; text-align: center;">Failed to load photos</p>';
            }
        }

        async function editPhoto(id) {
            try {
                const response = await fetch(`../backend/gallery_api.php?action=get_photo&id=${id}`);
                const result = await response.json();
                
                if (result.success) {
                    const photo = result.data;
                    document.getElementById('photoId').value = photo.id;
                    document.getElementById('photoCategory').value = photo.category_id;
                    document.getElementById('photoName').value = photo.name;
                    document.getElementById('photoImagePath').value = photo.image_path;
                    
                    imagePreview.src = '../' + photo.image_path;
                    imagePreviewContainer.style.display = 'flex';
                    photoImage.required = false;
                    
                    document.getElementById('photoModalTitle').textContent = 'Edit Photo';
                    document.getElementById('submitPhotoBtn').textContent = 'Update Photo';
                    photoModal.style.display = 'flex';
                } else {
                    Swal.fire('Error', result.message, 'error');
                }
            } catch (error) {
                Swal.fire('Error', 'Failed to load photo', 'error');
                console.error(error);
            }
        }

        async function deletePhoto(id) {
            const result = await Swal.fire({
                title: 'Delete Photo?',
                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/gallery_api.php?action=delete_photo', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ id: id })
                    });

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

        // Category filter
        categoryFilter.addEventListener('change', async (e) => {
            const categoryId = e.target.value;
            const container = document.getElementById('photosContainer');

            if (!categoryId) {
                loadPhotos();
                return;
            }

            try {
                const response = await fetch(`../backend/gallery_api.php?action=get_photos&category_id=${categoryId}`);
                const result = await response.json();
                
                if (result.success && result.data.length > 0) {
                    container.innerHTML = result.data.map(photo => `
                        <div class="photo-card">
                            <img src="../${photo.image_path}" alt="${photo.name}" class="photo-image">
                            <div class="photo-info">
                                <div class="photo-category">${photo.category_name || 'Uncategorized'}</div>
                                <div class="photo-name">${photo.name}</div>
                                <div class="photo-actions">
                                    <button class="btn-small" onclick="editPhoto(${photo.id})" style="flex: 1;">
                                        <i class="fas fa-edit"></i> Edit
                                    </button>
                                    <button class="btn-small delete" onclick="deletePhoto(${photo.id})" style="flex: 1;">
                                        <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 photos in this category</p>';
                }
            } catch (error) {
                container.innerHTML = '<p style="color: #c0392b; text-align: center;">Failed to filter photos</p>';
            }
        });

        function loadNotificationCounts() {
            ['bookings', 'orders', 'contacts', 'feedback', 'users'].forEach(type => {
                const apiEndpoints = {
                    'bookings': '../backend/admin_bookings_api.php?action=new_count',
                    'orders': '../backend/admin_orders_api.php?action=new_count',
                    'contacts': '../backend/admin_contacts_api.php?action=new_count',
                    'feedback': '../backend/admin_feedback_api.php?action=new_count',
                    'users': '../backend/admin_users_api.php?action=new_count'
                };
                fetch(apiEndpoints[type]).then(response => response.json()).then(data => {
                    updateBadge(type, data.count);
                }).catch(error => console.error('Error:', error));
            });
        }

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

</html>
