<!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="Orders 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>Orders Management - Granny Restaurant</title>

    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Raleway', sans-serif;
            background: #f5f5f5;
            color: #333;
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            .topbar {
                left: 250px;
            }

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

        @media (max-width: 768px) {
            .sidebar {
                position: fixed;
                left: 0;
                top: 0;
                width: 280px;
                height: 100vh;
                transform: translateX(-100%);
                transition: transform 0.3s ease;
                z-index: 1000;
            }

            .topbar {
                left: 0;
            }

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

            .menu-toggle {
                display: block;
            }

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

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

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

        /* Order Details Modal Styles */
        #orderDetailsOverlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: none;
            z-index: 1998;
        }

        #orderDetailsModal {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            border-radius: 10px;
            box-shadow: 0 5px 30px rgba(0, 0, 0, 0.3);
            width: 90%;
            max-width: 900px;
            max-height: 90vh;
            overflow-y: auto;
            display: none;
            z-index: 1999;
            flex-direction: column;
        }

        #orderDetailsModal.show {
            display: flex !important;
        }

        #orderDetailsOverlay.show {
            display: block !important;
        }

        .order-details-header {
            padding: 25px;
            background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            color: white;
            border-radius: 10px 10px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .order-details-header h2 {
            margin: 0;
            font-size: 24px;
        }

        .order-details-close {
            background: none;
            border: none;
            color: white;
            font-size: 28px;
            cursor: pointer;
            padding: 0;
            width: 30px;
            height: 30px;
        }

        .order-details-close:hover {
            background-color: rgba(255, 255, 255, 0.2);
            border-radius: 50%;
        }

        .order-details-actions {
            display: flex;
            gap: 10px;
            padding: 20px 0;
            border-top: 1px solid #e0e0e0;
            margin-top: 20px;
        }

        .btn-accept {
            flex: 1;
            padding: 12px 24px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        .btn-accept:hover {
            background-color: #45a049;
        }

        .btn-accept:active {
            transform: scale(0.98);
        }

        .order-details-body {
            padding: 25px;
            flex: 1;
            overflow-y: auto;
        }

        .order-info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .order-info-card {
            background: #f9f9f9;
            padding: 15px;
            border-radius: 8px;
            border-left: 4px solid #d4a574;
        }

        .order-info-label {
            font-size: 12px;
            color: #999;
            text-transform: uppercase;
            font-weight: 600;
            margin-bottom: 8px;
        }

        .order-info-value {
            font-size: 16px;
            color: #333;
            font-weight: 600;
        }

        .order-items-section {
            margin-top: 30px;
            padding-top: 30px;
            border-top: 1px solid #e0e0e0;
        }

        .order-items-title {
            font-size: 18px;
            font-weight: 700;
            color: #2c3e50;
            margin-bottom: 15px;
        }

        .order-items-container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }

        .order-item {
            background: white;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            overflow: hidden;
            transition: all 0.3s ease;
        }

        .order-item:hover {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .order-item-image {
            width: 100%;
            height: 180px;
            overflow: hidden;
            background: #f5f5f5;
        }

        .order-item-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .order-item-details {
            padding: 15px;
        }

        .order-item-name {
            font-size: 16px;
            font-weight: 700;
            color: #2c3e50;
            margin-bottom: 10px;
        }

        .order-item-info {
            display: flex;
            justify-content: space-between;
            font-size: 13px;
            color: #666;
            margin-bottom: 8px;
        }

        .order-item-total {
            font-size: 14px;
            font-weight: 700;
            color: #d4a574;
        }

        .order-totals {
            background: #f9f9f9;
            padding: 20px;
            border-radius: 8px;
            margin-top: 20px;
        }

        .order-total-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 12px;
            font-size: 15px;
        }

        .order-total-row strong {
            font-weight: 600;
        }

        .order-total-row.final {
            border-top: 2px solid #d4a574;
            padding-top: 12px;
            margin-top: 12px;
            font-size: 18px;
            color: #2c3e50;
        }

        @media (max-width: 768px) {
            #orderDetailsModal {
                width: 95%;
                max-height: 95vh;
            }

            .order-details-header {
                flex-direction: column;
                gap: 15px;
                align-items: flex-start;
            }

            .order-details-close {
                align-self: flex-end;
            }

            .order-info-grid {
                grid-template-columns: 1fr;
            }

            .order-items-container {
                grid-template-columns: 1fr;
            }
        }

        /* Force SweetAlert to appear above your custom modal (which is 1999) */
        /* div.swal2-container {
            z-index: 20000 !important;
        } */
    </style>

</head>

<body>
    <div id="menuOverlay" class="overlay"></div>

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

        <ul class="sidebar-menu">
            <li><a href="dashboard.php"><i class="fas fa-chart-line"></i> <span>Dashboard</span></a></li>
            <li><a href="carousel.php"><i class="fas fa-images"></i> <span>Carousel</span></a></li>
            <li><a href="gallery.php"><i class="fas fa-th-large"></i> <span>Gallery</span></a></li>
            <li><a href="chefs.php"><i class="fas fa-user-tie"></i> <span>Chefs</span></a></li>
            <li><a href="menu.php"><i class="fas fa-utensils"></i> <span>Menu</span></a></li>
            <li><a href="bookings.php"><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" class="active"><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>

    <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">Orders</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>

    <div class="main-content">
        <div class="content-section">
            <div class="section-title">
                <i class="fas fa-shopping-cart"></i>
                Manage Orders
            </div>
            <!-- <div class="btn-group">
                <button class="btn-action">
                    <i class="fas fa-plus"></i> New Order
                </button>
                <button class="btn-action">
                    <i class="fas fa-download"></i> Export
                </button>
            </div> -->
            <div class="table-responsive">
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th>Order ID</th>
                            <th>Customer Name</th>
                            <th>Email</th>
                            <th>Phone</th>
                            <th>Address</th>
                            <th>Payment Method</th>
                            <th>Subtotal</th>
                            <th>Tax</th>
                            <th>Total</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="ordersTable">
                        <tr>
                            <td colspan="11" style="text-align: center; color: #999;">Loading orders...</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Order Details Modal -->
    <div id="orderDetailsOverlay"></div>
    <div id="orderDetailsModal">
        <div class="order-details-header">
            <h2>Order <span id="orderDetailsOrderNumber">#12345</span></h2>
            <button class="order-details-close" onclick="closeOrderDetailsModal()">×</button>
        </div>

        <div class="order-details-body">
            <!-- Order Status and Date -->
            <div class="order-info-grid">
                <div class="order-info-card">
                    <div class="order-info-label">Order Status</div>
                    <div class="order-info-value">
                        <span class="status-badge" id="orderDetailsStatus">pending</span>
                    </div>
                </div>
                <div class="order-info-card">
                    <div class="order-info-label">Order Date</div>
                    <div class="order-info-value" id="orderDetailsDate">-</div>
                </div>
            </div>

            <!-- Customer Information -->
            <div class="order-info-grid">
                <div class="order-info-card">
                    <div class="order-info-label">Customer Name</div>
                    <div class="order-info-value" id="orderDetailsCustomerName">-</div>
                </div>
                <div class="order-info-card">
                    <div class="order-info-label">Email</div>
                    <div class="order-info-value" id="orderDetailsEmail">-</div>
                </div>
                <div class="order-info-card">
                    <div class="order-info-label">Phone</div>
                    <div class="order-info-value" id="orderDetailsPhone">-</div>
                </div>
                <div class="order-info-card">
                    <div class="order-info-label">Payment Method</div>
                    <div class="order-info-value" id="orderDetailsPaymentMethod">-</div>
                </div>
            </div>

            <!-- Delivery Address -->
            <div class="order-info-grid">
                <div class="order-info-card" style="grid-column: 1 / -1;">
                    <div class="order-info-label">Delivery Address</div>
                    <div class="order-info-value" id="orderDetailsAddress">-</div>
                </div>
            </div>

            <!-- Order Items -->
            <div class="order-items-section">
                <div class="order-items-title">
                    <i class="fas fa-shopping-bag"></i> Order Items
                </div>
                <div class="order-items-container" id="orderItemsContainer">
                    <div style="text-align: center; color: #999; padding: 20px; grid-column: 1 / -1;">Loading items...</div>
                </div>
            </div>

            <!-- Order Totals -->
            <div class="order-totals">
                <div class="order-total-row">
                    <span>Subtotal</span>
                    <span id="orderDetailsSubtotal">$0.00</span>
                </div>
                <div class="order-total-row">
                    <span>Tax</span>
                    <span id="orderDetailsTax">$0.00</span>
                </div>
                <div class="order-total-row final">
                    <span>Total</span>
                    <span id="orderDetailsTotal">$0.00</span>
                </div>
            </div>

            <!-- Action Buttons -->
            <div class="order-details-actions">
                <button class="btn-accept" id="acceptOrderBtn" onclick="acceptOrder()">Accept Order</button>
            </div>
        </div>
    </div>

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

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            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();

            loadOrders();

            // Close order details modal when clicking overlay
            document.getElementById('orderDetailsOverlay').addEventListener('click', closeOrderDetailsModal);

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

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

        function loadOrders() {
            const tableBody = document.getElementById('ordersTable');
            tableBody.innerHTML = '<tr><td colspan="11" style="text-align: center; color: #999;">Loading orders...</td></tr>';

            fetch('../backend/admin_orders_api.php')
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.data && data.data.length > 0) {
                        tableBody.innerHTML = data.data.map(order => `
                            <tr>
                                <td>#${order.order_number || order.id}</td>
                                <td>${order.full_name}</td>
                                <td>${order.email}</td>
                                <td>${order.phone}</td>
                                <td>${order.address}</td>
                                <td>${order.payment_method}</td>
                                <td>$${parseFloat(order.subtotal).toFixed(2)}</td>
                                <td>$${parseFloat(order.tax).toFixed(2)}</td>
                                <td>$${parseFloat(order.total).toFixed(2)}</td>
                                <td><span class="status-badge ${order.status}">${order.status}</span></td>
                                <td>
                                    <button class="btn-view" onclick="viewOrder(${order.id})">
                                        <i class="fas fa-eye"></i> View
                                    </button>
                                </td>
                            </tr>
                        `).join('');
                    } else {
                        const message = data.success === false ?
                            `<tr><td colspan="11" style="text-align: center; color: #c0392b;">Error: ${data.message}</td></tr>` :
                            '<tr><td colspan="11" style="text-align: center; color: #999;">No orders found</td></tr>';
                        tableBody.innerHTML = message;
                    }
                })
                .catch(error => {
                    console.error('Error loading orders:', error);
                    tableBody.innerHTML = '<tr><td colspan="11" style="text-align: center; color: #c0392b;">Error: ' + error.message + '</td></tr>';
                });
        }

        function viewOrder(id) {
            // Fetch order details with items
            fetch(`../backend/admin_orders_api.php?action=get_details&order_id=${id}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.order) {
                        showOrderDetailsModal(data.order, data.items);
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: data.message || 'Failed to load order details'
                        });
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to load order details'
                    });
                });
        }

        function showOrderDetailsModal(order, items) {
            const modal = document.getElementById('orderDetailsModal');
            if (!modal) {
                console.error('Modal not found');
                return;
            }

            // Format date
            const orderDate = new Date(order.created_at).toLocaleDateString('en-US', {
                year: 'numeric',
                month: 'long',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            });

            // Build items HTML
            let itemsHtml = '';
            if (items && items.length > 0) {
                itemsHtml = items.map(item => {
                    const imagePath = item.image_path ? `../assets/uploads/${item.image_path}` : '../assets/images/default-food.png';
                    const itemTotal = (parseFloat(item.quantity) * parseFloat(item.price)).toFixed(2);
                    return `
                        <div class="order-item">
                            <div class="order-item-image">
                                <img src="${imagePath}" alt="${item.item_name}">
                            </div>
                            <div class="order-item-details">
                                <div class="order-item-name">${item.item_name}</div>
                                <div class="order-item-info">
                                    <span>Qty: <strong>${item.quantity}</strong></span>
                                    <span>Price: <strong>$${parseFloat(item.price).toFixed(2)}</strong></span>
                                </div>
                                <div class="order-item-total">Total: $${itemTotal}</div>
                            </div>
                        </div>
                    `;
                }).join('');
            } else {
                itemsHtml = '<div style="text-align: center; color: #999; padding: 20px;">No items found</div>';
            }

            // Update modal content
            document.getElementById('orderDetailsOrderNumber').textContent = `#${order.order_number || order.id}`;
            document.getElementById('orderDetailsDate').textContent = orderDate;
            document.getElementById('orderDetailsStatus').textContent = order.status;
            document.getElementById('orderDetailsStatus').className = `status-badge ${order.status}`;

            // Store order ID for later use
            modal.dataset.orderId = order.id;

            document.getElementById('orderDetailsCustomerName').textContent = order.full_name;
            document.getElementById('orderDetailsEmail').textContent = order.email;
            document.getElementById('orderDetailsPhone').textContent = order.phone;
            document.getElementById('orderDetailsAddress').textContent = order.address;
            document.getElementById('orderDetailsPaymentMethod').textContent = order.payment_method;

            document.getElementById('orderDetailsSubtotal').textContent = `$${parseFloat(order.subtotal).toFixed(2)}`;
            document.getElementById('orderDetailsTax').textContent = `$${parseFloat(order.tax).toFixed(2)}`;
            document.getElementById('orderDetailsTotal').textContent = `$${parseFloat(order.total).toFixed(2)}`;

            document.getElementById('orderItemsContainer').innerHTML = itemsHtml;

            // Show modal using class and clear inline styles
            modal.classList.add('show');
            modal.style.display = ''; // Clear inline style to use CSS
            const overlay = document.getElementById('orderDetailsOverlay');
            if (overlay) {
                overlay.classList.add('show');
                overlay.style.display = ''; // Clear inline style to use CSS
            }
        }

        function closeOrderDetailsModal() {
            const modal = document.getElementById('orderDetailsModal');
            const overlay = document.getElementById('orderDetailsOverlay');

            console.log('closeOrderDetailsModal called');

            if (modal) {
                modal.classList.remove('show');
                // Explicitly set display to none as fallback
                modal.style.display = 'none';
                console.log('Modal closed, show class removed, display set to none');
            }
            if (overlay) {
                overlay.classList.remove('show');
                // Explicitly set display to none as fallback
                overlay.style.display = 'none';
            }
        }

        function acceptOrder() {
            const modal = document.getElementById('orderDetailsModal');

            // Safety check: ensure modal exists
            if (!modal) return;

            // 1. FORCE CLOSE THE MODAL FIRST (before any validation alerts)
            closeOrderDetailsModal();

            let orderId = modal.dataset.orderId;
            const orderNumberElement = document.getElementById('orderDetailsOrderNumber');
            const orderNumber = orderNumberElement ? orderNumberElement.textContent.replace('#', '') : 'Unknown';

            const statusElement = document.getElementById('orderDetailsStatus');
            const currentStatus = statusElement ? statusElement.textContent : '';

            if (!orderId) {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Could not retrieve order ID'
                });
                return;
            }

            if (currentStatus === 'accepted') {
                Swal.fire({
                    icon: 'info',
                    title: 'Already Accepted',
                    text: 'This order has already been accepted.'
                });
                return;
            }

            // 2. WAIT 100ms BEFORE SHOWING SWEETALERT
            // This allows the browser to finish hiding the modal before creating the alert
            setTimeout(() => {
                Swal.fire({
                    title: 'Accept Order?',
                    text: `Are you sure you want to accept order ${orderNumber}?`,
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonColor: '#4CAF50',
                    cancelButtonColor: '#f44336',
                    confirmButtonText: 'Yes, Accept it!',
                    cancelButtonText: 'Cancel'
                }).then((result) => {
                    if (result.isConfirmed) {
                        // User clicked YES
                        fetch('../backend/admin_orders_api.php?action=update_status', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify({
                                    order_id: parseInt(orderId),
                                    status: 'accepted'
                                })
                            })
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    Swal.fire({
                                        icon: 'success',
                                        title: 'Accepted',
                                        text: 'Order has been accepted successfully!',
                                        timer: 1500
                                    }).then(() => {
                                        loadOrders();
                                    });
                                } else {
                                    Swal.fire({
                                        icon: 'error',
                                        title: 'Error',
                                        text: data.message || 'Failed to accept order'
                                    });
                                    // Optional: Re-open modal if error
                                    // viewOrder(orderId);
                                }
                            })
                            .catch(error => {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Error',
                                    text: 'Failed to accept order'
                                });
                            });
                    } else {
                        // User clicked Cancel - Re-open the modal so they can continue viewing
                        viewOrder(orderId);
                    }
                });
            }, 100); // End of setTimeout
        }

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

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

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

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

            fetch('../backend/admin_users_api.php?action=new_count')
                .then(response => response.json())
                .then(data => {
                    updateBadge('users', 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>