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

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

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

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

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

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

        /* Chef Cards Grid */
        .chefs-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 25px;
            margin-top: 20px;
        }

        .chef-card {
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
        }

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

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

        .chef-info {
            padding: 20px;
        }

        .chef-name {
            font-size: 18px;
            color: #2c3e50;
            font-weight: 700;
            margin-bottom: 5px;
        }

        .chef-position {
            font-size: 12px;
            color: #d4a574;
            font-weight: 600;
            text-transform: uppercase;
            margin-bottom: 10px;
            letter-spacing: 1px;
        }

        .chef-actions {
            display: flex;
            gap: 8px;
            margin-top: 15px;
        }

        .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;
            flex: 1;
            text-align: center;
        }

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

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

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

        /* Modals */
        .modal {
            display: none;
            position: fixed;
            z-index: 950;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            overflow-y: auto;
            padding: 20px;
        }

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

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

        /* Tab Navigation */
        .form-tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 30px;
            border-bottom: 2px solid #e0e0e0;
        }

        .tab-button {
            padding: 12px 20px;
            background: none;
            border: none;
            border-bottom: 3px solid transparent;
            cursor: pointer;
            font-weight: 600;
            color: #999;
            font-size: 14px;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .tab-button:hover {
            color: #666;
        }

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

        .tab-content {
            display: none;
            animation: fadeIn 0.3s ease;
        }

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

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

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

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

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

        /* Tabs */
        .tabs-container {
            display: flex;
            gap: 10px;
            margin-bottom: 25px;
            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;
        }

        /* Skills list */
        .skills-list {
            margin-top: 15px;
        }

        .skill-item {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 10px;
            background: #f5f5f5;
            border-radius: 6px;
            margin-bottom: 8px;
        }

        .skill-item span {
            flex: 1;
            font-size: 14px;
            color: #333;
        }

        .btn-skill-delete {
            padding: 4px 8px;
            background: #e74c3c;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            font-size: 11px;
            font-weight: 600;
        }

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

        /* Social media list */
        .social-list {
            margin-top: 15px;
        }

        .social-item {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 10px;
            background: #f5f5f5;
            border-radius: 6px;
            margin-bottom: 8px;
        }

        .social-item span {
            flex: 1;
            font-size: 14px;
            color: #333;
        }

        .btn-social-delete {
            padding: 4px 8px;
            background: #e74c3c;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            font-size: 11px;
            font-weight: 600;
        }

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

        /* Ensure SweetAlert2 and other modals stay on top */
        .swal2-container,
        .swal2-popup {
            z-index: 2000 !important;
        }

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

            .topbar {
                left: 250px;
            }

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

            .chefs-grid {
                grid-template-columns: repeat(auto-fill, minmax(200px, 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;
            }

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

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

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

            .chef-image {
                height: 200px;
            }
        }
    </style>
</head>

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

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

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

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

    <!-- 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">Chef 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">
        <div class="content-section">
            <div class="section-title">
                <i class="fas fa-user-tie"></i>
                Manage Chefs
            </div>
            <p style="color: #999; margin-bottom: 20px;">Add, edit, or delete chef profiles with their skills and social media</p>
            <div class="btn-group">
                <button class="btn-action" id="addChefBtn">
                    <i class="fas fa-plus"></i> Add Chef
                </button>
            </div>

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

    <!-- Add/Edit Chef Modal -->
    <div id="chefModal" class="modal" style="display: none;">
        <div class="modal-content">
            <span class="close-modal" id="closeChefModal">&times;</span>
            <h2 id="chefModalTitle">Add New Chef</h2>
            
            <!-- Tab Navigation -->
            <div class="form-tabs">
                <button type="button" class="tab-button active" data-tab="basic-info">
                    <i class="fas fa-user"></i> Basic Information
                </button>
                <button type="button" class="tab-button" data-tab="additional-details">
                    <i class="fas fa-info-circle"></i> Additional Details
                </button>
            </div>
            
            <form id="chefForm">
                <input type="hidden" id="chefId">

                <!-- Tab 1: Basic Information -->
                <div class="tab-content active" data-tab="basic-info">
                    <div class="form-group">
                        <label for="chefName">Chef Name *</label>
                        <input type="text" id="chefName" placeholder="e.g., Todd Stephen" required>
                    </div>

                    <div class="form-group">
                        <label for="chefPosition">Position *</label>
                        <input type="text" id="chefPosition" placeholder="e.g., Master Chef" required>
                    </div>

                    <!-- Kitchen Staff Authentication Section -->
                    <div style="margin-top: 25px; padding: 20px; background: #f0f7ff; border-left: 4px solid #667eea; border-radius: 6px;">
                        <h4 style="margin-bottom: 15px; color: #667eea; display: flex; align-items: center; gap: 10px;">
                            <i class="fas fa-key"></i> Kitchen Staff Login (Optional)
                        </h4>
                        <p style="font-size: 12px; color: #666; margin: 0 0 15px 0;">
                            Leave blank if this chef won't have kitchen dashboard access
                        </p>

                        <div class="form-group">
                            <label for="chefEmail">Email</label>
                            <input type="email" id="chefEmail" placeholder="e.g., chef@granny.local">
                        </div>

                        <div class="form-group">
                            <label for="chefEmployeeId">Employee ID</label>
                            <input type="text" id="chefEmployeeId" placeholder="e.g., CHEF001">
                        </div>

                        <div class="form-group">
                            <label for="chefPassword">Password</label>
                            <input type="password" id="chefPassword" placeholder="Leave empty to keep existing">
                            <small style="color: #999;">Only required when creating new staff for kitchen login. Leave empty when editing to keep current password.</small>
                        </div>

                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                            <div class="form-group">
                                <label for="chefRole">Role</label>
                                <select id="chefRole" style="padding: 12px; border: 1px solid #e0e0e0; border-radius: 6px; width: 100%; font-family: inherit;">
                                    <option value="">Select Role</option>
                                    <option value="Chef">Chef</option>
                                    <option value="Kitchen Manager">Kitchen Manager</option>
                                    <option value="Staff">Staff</option>
                                </select>
                            </div>

                            <div class="form-group">
                                <label for="chefAuthStatus">Status</label>
                                <select id="chefAuthStatus" style="padding: 12px; border: 1px solid #e0e0e0; border-radius: 6px; width: 100%; font-family: inherit;">
                                    <option value="active">Active</option>
                                    <option value="inactive">Inactive</option>
                                </select>
                            </div>
                        </div>
                    </div>

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

                <!-- Tab 2: Additional Details -->
                <div class="tab-content" data-tab="additional-details">
                    <div class="form-group">
                        <label for="chefDescription">Description/Bio</label>
                        <textarea id="chefDescription" placeholder="Chef's background and experience" rows="5"></textarea>
                    </div>

                    <!-- Skills Section -->
                    <div style="margin-top: 25px; padding-top: 20px;">
                        <h4 style="margin-bottom: 15px; color: #2c3e50;">Skills</h4>
                        <div class="form-group">
                            <label for="skillInput">Add Skill</label>
                            <div style="display: flex; gap: 10px;">
                                <input type="text" id="skillInput" placeholder="e.g., Pastry Making" style="flex: 1;">
                                <button type="button" class="btn-action" id="addSkillBtn" style="margin: 0; padding: 12px 20px;">Add</button>
                            </div>
                        </div>
                        <div class="skills-list" id="skillsList"></div>
                    </div>

                    <!-- Social Media Section -->
                    <div style="margin-top: 25px; padding-top: 20px;">
                        <h4 style="margin-bottom: 15px; color: #2c3e50;">Social Media</h4>
                        <div class="form-group">
                            <label for="socialPlatform">Platform</label>
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 10px;">
                                <select id="socialPlatform" style="padding: 12px; border: 1px solid #e0e0e0; border-radius: 6px;">
                                    <option value="facebook">Facebook</option>
                                    <option value="instagram">Instagram</option>
                                    <option value="twitter">Twitter</option>
                                    <option value="linkedin">LinkedIn</option>
                                </select>
                                <input type="text" id="socialUrl" placeholder="Profile URL">
                            </div>
                            <button type="button" class="btn-action" id="addSocialBtn" style="width: 100%;">Add Social Media</button>
                        </div>
                        <div class="social-list" id="socialList"></div>
                    </div>
                </div>

                <div class="form-actions">
                    <button type="submit" class="btn-action" id="submitChefBtn">Add Chef</button>
                    <button type="button" class="btn-action-secondary" id="cancelChefBtn">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>

    <!-- Chef Management Script -->
    <script>
        let currentChef = null;
        let currentSkills = [];
        let currentSocial = [];

        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
            loadChefs();

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

        // ========== CHEF MANAGEMENT ==========
        const chefModal = document.getElementById('chefModal');
        const addChefBtn = document.getElementById('addChefBtn');
        const closeChefModal = document.getElementById('closeChefModal');
        const chefForm = document.getElementById('chefForm');
        const cancelChefBtn = document.getElementById('cancelChefBtn');
        const chefImage = document.getElementById('chefImage');
        const imagePreview = document.getElementById('imagePreview');
        const imagePreviewContainer = document.getElementById('imagePreviewContainer');
        const removeImageBtn = document.getElementById('removeImageBtn');
        const chefImagePath = document.getElementById('chefImagePath');

        addChefBtn.addEventListener('click', () => {
            resetChefForm();
            document.getElementById('chefModalTitle').textContent = 'Add New Chef';
            document.getElementById('submitChefBtn').textContent = 'Add Chef';
            // Reset to first tab
            document.querySelectorAll('.tab-button').forEach((btn, i) => {
                if (i === 0) {
                    btn.classList.add('active');
                } else {
                    btn.classList.remove('active');
                }
            });
            document.querySelectorAll('.tab-content').forEach((content, i) => {
                if (i === 0) {
                    content.classList.add('active');
                } else {
                    content.classList.remove('active');
                }
            });
            chefModal.style.display = 'block';
        });

        // Tab switching
        document.querySelectorAll('.tab-button').forEach(button => {
            button.addEventListener('click', (e) => {
                e.preventDefault();
                const tabName = button.getAttribute('data-tab');
                
                // Remove active from all tabs and contents
                document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
                document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
                
                // Add active to clicked tab and corresponding content
                button.classList.add('active');
                document.querySelector(`.tab-content[data-tab="${tabName}"]`).classList.add('active');
            });
        });

        closeChefModal.addEventListener('click', () => {
            chefModal.style.display = 'none';
        });

        cancelChefBtn.addEventListener('click', () => {
            chefModal.style.display = 'none';
        });

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

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

        // Add skill
        document.getElementById('addSkillBtn').addEventListener('click', (e) => {
            e.preventDefault();
            const skillInput = document.getElementById('skillInput');
            if (skillInput.value.trim()) {
                const skill = {
                    id: 'new_' + Date.now(),
                    skill_name: skillInput.value.trim(),
                    is_new: true
                };
                currentSkills.push(skill);
                skillInput.value = '';
                renderSkills();
            }
        });

        // Add social media
        document.getElementById('addSocialBtn').addEventListener('click', (e) => {
            e.preventDefault();
            const platform = document.getElementById('socialPlatform').value;
            const url = document.getElementById('socialUrl').value.trim();
            
            if (url) {
                const social = {
                    id: 'new_' + Date.now(),
                    platform: platform,
                    url: url,
                    icon_class: 'fab fa-' + platform,
                    is_new: true
                };
                currentSocial.push(social);
                document.getElementById('socialUrl').value = '';
                renderSocial();
            }
        });

        // Submit chef form
        chefForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            const chefId = document.getElementById('chefId').value;
            const isEditing = !!chefId;

            let imagePath = chefImagePath.value;
            if (chefImage.files.length > 0) {
                const formData = new FormData();
                formData.append('image', chefImage.files[0]);
                
                try {
                    const response = await fetch('../backend/chefs_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;
                }
            }

            // Only require image when creating new chef, not when editing
            if (!imagePath && !isEditing) {
                Swal.fire('Error', 'Please select an image', 'error');
                return;
            }

            const chefData = {
                name: document.getElementById('chefName').value,
                position: document.getElementById('chefPosition').value,
                description: document.getElementById('chefDescription').value,
                image_path: imagePath,
                display_order: 0,
                // Kitchen staff authentication fields
                email: document.getElementById('chefEmail').value || null,
                employee_id: document.getElementById('chefEmployeeId').value || null,
                password: document.getElementById('chefPassword').value || null,
                role: document.getElementById('chefRole').value || null,
                status: document.getElementById('chefAuthStatus').value || 'active'
            };

            if (isEditing) {
                chefData.id = chefId;
            }

            const url = isEditing ? '../backend/chefs_api.php?action=update_chef' : '../backend/chefs_api.php?action=create_chef';

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

                const raw = await response.text();
                let result;
                try {
                    result = JSON.parse(raw);
                } catch (parseError) {
                    throw new Error(`Invalid server response (${response.status}): ${raw || 'empty body'}`);
                }

                if (result.success) {
                    const newChefId = isEditing ? chefId : result.data.id;
                    
                    // Add skills
                    for (let skill of currentSkills) {
                        if (skill.is_new) {
                            await fetch('../backend/chefs_api.php?action=add_skill', {
                                method: 'POST',
                                headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify({
                                    chef_id: newChefId,
                                    skill_name: skill.skill_name
                                })
                            });
                        }
                    }

                    // Add social media
                    for (let social of currentSocial) {
                        if (social.is_new) {
                            await fetch('../backend/chefs_api.php?action=add_social', {
                                method: 'POST',
                                headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify({
                                    chef_id: newChefId,
                                    platform: social.platform,
                                    url: social.url,
                                    icon_class: social.icon_class
                                })
                            });
                        }
                    }

                    Swal.fire('Success', isEditing ? 'Chef updated successfully' : 'Chef added successfully', 'success');
                    chefModal.style.display = 'none';
                    loadChefs();
                } else {
                    Swal.fire('Error', result.message, 'error');
                }
            } catch (error) {
                Swal.fire('Error', 'Failed to save chef', 'error');
                console.error(error);
            }
        });

        function resetChefForm() {
            chefForm.reset();
            document.getElementById('chefId').value = '';
            chefImagePath.value = '';
            imagePreviewContainer.style.display = 'none';
            chefImage.required = true;
            
            // Reset authentication fields if they exist
            if (document.getElementById('chefEmail')) {
                document.getElementById('chefEmail').value = '';
                document.getElementById('chefEmployeeId').value = '';
                document.getElementById('chefPassword').value = '';
                document.getElementById('chefRole').value = 'Chef';
                document.getElementById('chefAuthStatus').value = 'active';
            }
            
            currentSkills = [];
            currentSocial = [];
            renderSkills();
            renderSocial();
        }

        function renderSkills() {
            const container = document.getElementById('skillsList');
            container.innerHTML = currentSkills.map(skill => `
                <div class="skill-item">
                    <span>${skill.skill_name}</span>
                    <button type="button" class="btn-skill-delete" onclick="removeSkill('${skill.id}')">Remove</button>
                </div>
            `).join('');
        }

        function renderSocial() {
            const container = document.getElementById('socialList');
            container.innerHTML = currentSocial.map(social => `
                <div class="social-item">
                    <span>${social.platform.toUpperCase()}: ${social.url}</span>
                    <button type="button" class="btn-social-delete" onclick="removeSocial('${social.id}')">Remove</button>
                </div>
            `).join('');
        }

        window.removeSkill = function(id) {
            currentSkills = currentSkills.filter(s => s.id !== id);
            renderSkills();
        };

        window.removeSocial = function(id) {
            currentSocial = currentSocial.filter(s => s.id !== id);
            renderSocial();
        };

        async function loadChefs() {
            try {
                const response = await fetch('../backend/chefs_api.php?action=get_chefs');
                const result = await response.json();
                
                const container = document.getElementById('chefsContainer');

                if (result.success && result.data.length > 0) {
                    container.innerHTML = result.data.map(chef => `
                        <div class="chef-card">
                            <img src="../${chef.image_path}" alt="${chef.name}" class="chef-image">
                            <div class="chef-info">
                                <div class="chef-name">${chef.name}</div>
                                <div class="chef-position">${chef.position}</div>
                                ${chef.email ? `<div class="auth-badge" style="color: #27ae60; font-size: 12px; margin: 5px 0;"><i class="fas fa-key"></i> Kitchen Access</div>` : ''}
                                <div class="chef-actions">
                                    <button class="btn-small" onclick="editChef(${chef.id})">
                                        <i class="fas fa-edit"></i> Edit
                                    </button>
                                    <button class="btn-small delete" onclick="deleteChef(${chef.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 chefs found. Add one to get started!</p>';
                }
            } catch (error) {
                console.error('Error loading chefs:', error);
                document.getElementById('chefsContainer').innerHTML = '<p style="color: #c0392b; text-align: center;">Failed to load chefs</p>';
            }
        }

        window.editChef = async function(id) {
            try {
                const response = await fetch(`../backend/chefs_api.php?action=get_chef&id=${id}`);
                const result = await response.json();
                
                if (result.success) {
                    const chef = result.data;
                    document.getElementById('chefId').value = chef.id;
                    document.getElementById('chefName').value = chef.name;
                    document.getElementById('chefPosition').value = chef.position;
                    document.getElementById('chefDescription').value = chef.description || '';
                    document.getElementById('chefImagePath').value = chef.image_path;
                    
                    imagePreview.src = '../' + chef.image_path;
                    imagePreviewContainer.style.display = 'flex';
                    chefImage.required = false;
                    
                    // Populate authentication fields (if they exist)
                    if (document.getElementById('chefEmail')) {
                        document.getElementById('chefEmail').value = chef.email || '';
                        document.getElementById('chefEmployeeId').value = chef.employee_id || '';
                        document.getElementById('chefPassword').value = ''; // Don't populate password on edit
                        document.getElementById('chefRole').value = chef.role || 'Chef';
                        document.getElementById('chefAuthStatus').value = chef.status || 'active';
                    }
                    
                    currentSkills = (chef.skills || []).map(s => ({
                        id: s.id,
                        skill_name: s.skill_name,
                        is_new: false
                    }));
                    currentSocial = (chef.social_media || []).map(s => ({
                        id: s.id,
                        platform: s.platform,
                        url: s.url,
                        icon_class: s.icon_class,
                        is_new: false
                    }));
                    
                    renderSkills();
                    renderSocial();
                    
                    document.getElementById('chefModalTitle').textContent = 'Edit Chef';
                    document.getElementById('submitChefBtn').textContent = 'Update Chef';
                    chefModal.style.display = 'block';
                } else {
                    Swal.fire('Error', result.message, 'error');
                }
            } catch (error) {
                Swal.fire('Error', 'Failed to load chef', 'error');
                console.error(error);
            }
        };

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

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

        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>
