<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Elfit Arabia - Admin Panel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <link rel="stylesheet" href="/style.css">
    <style>
        /* Admin-specific overrides using the design system */
        body {
            background: linear-gradient(135deg, var(--surface-dark) 0%, var(--primary-800) 50%, var(--surface-dark) 100%);
            background-attachment: fixed;
            color: var(--text-primary);
            font-family: 'Inter', 'Segoe UI', -apple-system, BlinkMacSystemFont, sans-serif;
        }

        .sidebar {
            height: 100vh;
            width: 280px;
            position: fixed;
            top: 0;
            left: -280px;
            background: linear-gradient(180deg, var(--primary-800) 0%, var(--surface-dark) 100%);
            transition: left 0.3s ease;
            padding-top: 100px;
            z-index: 1000;
            border-right: 1px solid var(--surface-border);
        }

        .sidebar.active {
            left: 0;
        }

        .sidebar-toggle {
            position: fixed;
            top: 80px;
            left: 10px;
            z-index: 1100;
            background: linear-gradient(135deg, var(--accent-600) 0%, var(--accent-500) 100%);
            border: none;
            color: var(--text-primary);
            padding: 10px 14px;
            border-radius: var(--radius-md);
        }

        .sidebar-toggle:hover {
            background: linear-gradient(135deg, var(--accent-500) 0%, var(--accent-400) 100%);
        }

        .content {
            margin-left: 10px;
            margin-top: 100px;
            padding: 20px;
        }

        .section {
            background: linear-gradient(145deg, var(--surface-card) 0%, var(--primary-800) 100%);
            border: 1px solid var(--surface-border);
            border-radius: var(--radius-lg);
            padding: 28px;
            margin-bottom: 24px;
            box-shadow: var(--shadow-md);
        }

        .section h2 {
            color: var(--text-primary);
            font-weight: 700;
        }

        .sidebar a {
            font-size: 1.1rem;
            font-weight: 500;
            color: var(--text-secondary);
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 16px 28px;
            text-decoration: none;
            transition: all 0.2s ease;
            border-left: 3px solid transparent;
        }

        .sidebar a:hover {
            color: var(--text-primary);
            background: linear-gradient(90deg, rgba(59, 130, 246, 0.15) 0%, transparent 100%);
            border-left-color: var(--accent-500);
            padding-left: 36px;
        }

        .metric-card {
            background: linear-gradient(145deg, var(--surface-card) 0%, var(--surface-elevated) 100%);
            border: 1px solid var(--surface-border);
            border-radius: var(--radius-lg);
            padding: 30px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .metric-card:hover {
            transform: translateY(-5px);
            border-color: var(--accent-500);
            box-shadow: var(--shadow-lg), var(--shadow-glow);
        }

        .metric-card i {
            color: var(--accent-400) !important;
        }

        .metric-card h5 {
            color: var(--text-secondary);
            font-weight: 500;
            margin-bottom: 12px;
        }

        .metric-card h2,
        .metric-card h3 {
            color: var(--accent-400) !important;
            font-weight: 700;
        }

        .metric-card .text-warning-value {
            color: var(--warning) !important;
        }

        .modal-content {
            background: linear-gradient(180deg, var(--surface-card) 0%, var(--primary-800) 100%);
            color: var(--text-primary);
            border: 1px solid var(--surface-border);
            border-radius: var(--radius-lg);
        }

        .modal-header {
            border-bottom: 1px solid var(--surface-border);
        }

        .table-dark {
            background-color: var(--surface-card);
        }

        .table-dark th,
        .table-dark td {
            border-color: var(--surface-border);
            color: var(--text-primary);
        }

        .table-dark th {
            background-color: var(--surface-elevated);
            color: var(--text-secondary);
            font-weight: 600;
            text-transform: uppercase;
            font-size: 0.85rem;
        }

        .navbar {
            background: linear-gradient(180deg, var(--primary-800) 0%, var(--surface-dark) 100%);
            border-bottom: 1px solid var(--surface-border);
        }

        .navbar-brand {
            background: linear-gradient(135deg, var(--accent-400) 0%, var(--accent-300) 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            font-weight: 700;
        }
    </style>
</head>

<body>
    <!-- Header -->
    <nav class="navbar navbar-expand-lg fixed-top">
        <div class="container-fluid">
            <a class="navbar-brand text-white" href="/admin">Elfit Arabia Admin</a>
            <div class="collapse navbar-collapse">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item"><a class="nav-link <%= section === 'manage-clients' ? 'active' : '' %>"
                            href="/admin/manage-clients">Manage Clients</a></li>
                    <li class="nav-item"><a class="nav-link <%= section === 'client-orders' ? 'active' : '' %>"
                            href="/admin/client-orders">Client Orders</a></li>
                    <li class="nav-item"><a class="nav-link <%= section === 'manage-products' ? 'active' : '' %>"
                            href="/admin/manage-products">Manage Products</a></li>
                    <li class="nav-item"><a class="nav-link" href="/logout">Logout</a></li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- Sidebar -->
    <div class="sidebar" id="sidebar">
        <a href="/dashboard"><i class="fas fa-user-tie"></i> Client Mode</a>
        <a href="/admin_list"><i class="fas fa-users-cog"></i> Admin List</a>
    </div>
    <button class="btn sidebar-toggle" onclick="toggleSidebar()">☰</button>

    <!-- Main Content -->
    <div class="content container-fluid">
        <% const messages=getFlashedMessages(); %>
            <% if (messages && messages.length> 0) { %>
                <% messages.forEach(function(message) { %>
                    <div class="alert alert-warning alert-dismissible fade show" role="alert">
                        <%= message %>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <% }); %>
                        <% } %>

                            <% if (section==='manage-clients' ) { %>
                                <%- include('partials/admin_clients', { clients, edit_client }) %>
                                    <% } else if (section==='client-orders' ) { %>
                                        <%- include('partials/admin_orders', { orders }) %>
                                            <% } else if (section==='manage-products' ) { %>
                                                <%- include('partials/admin_products', { all_categories,
                                                    products_by_category }) %>
                                                    <% } else if (section==='edit-product' ) { %>
                                                        <%- include('partials/admin_edit_product', { edit_product,
                                                            edit_options }) %>
                                                            <% } else { %>
                                                                <!-- Dashboard -->
                                                                <div class="section">
                                                                    <h2 style="padding-bottom: 20px;">
                                                                        <strong>Admin Dashboard Overview</strong>
                                                                    </h2>
                                                                    <div class="row g-4">
                                                                        <div class="col-md-3 col-sm-6">
                                                                            <div class="metric-card"
                                                                                onclick="openOrdersModal('unplaced')">
                                                                                <i
                                                                                    class="fas fa-hourglass-half fa-2x mb-3"></i>
                                                                                <h5>Total Remaining Inquiries</h5>
                                                                                <h2 class="text-warning-value">
                                                                                    <%= unplaced_orders %>
                                                                                </h2>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-md-3 col-sm-6">
                                                                            <div class="metric-card"
                                                                                onclick="openOrdersModal('delivered')">
                                                                                <i class="fas fa-truck fa-2x mb-3"></i>
                                                                                <h5>Orders Delivered</h5>
                                                                                <h2>
                                                                                    <%= delivered_count %>
                                                                                </h2>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-md-3 col-sm-6">
                                                                            <a href="/admin/manage-products"
                                                                                class="text-decoration-none">
                                                                                <div class="metric-card">
                                                                                    <i
                                                                                        class="fas fa-box-open fa-2x mb-3"></i>
                                                                                    <h5>Product Catalog</h5>
                                                                                    <h2>
                                                                                        <%= in_stock_products %>
                                                                                    </h2>
                                                                                </div>
                                                                            </a>
                                                                        </div>
                                                                        <div class="col-md-3 col-sm-6">
                                                                            <a href="/admin/manage-clients"
                                                                                class="text-decoration-none">
                                                                                <div class="metric-card">
                                                                                    <i
                                                                                        class="fas fa-users fa-2x mb-3"></i>
                                                                                    <h5>Registered Clients</h5>
                                                                                    <h2>
                                                                                        <%= total_clients %>
                                                                                    </h2>
                                                                                </div>
                                                                            </a>
                                                                        </div>
                                                                        <div class="col-md-4 col-sm-6">
                                                                            <div class="metric-card"
                                                                                onclick="openOrdersModal('pending')">
                                                                                <i class="fas fa-clock fa-2x mb-3"></i>
                                                                                <h5>Pending Orders</h5>
                                                                                <h2 class="text-warning-value">
                                                                                    <%= pending_orders %>
                                                                                </h2>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-md-4 col-sm-6">
                                                                            <div class="metric-card"
                                                                                onclick="openOrdersModal('clients')">
                                                                                <i
                                                                                    class="fas fa-user-tie fa-2x mb-3"></i>
                                                                                <h5>Most Active Client</h5>
                                                                                <h3>
                                                                                    <%= most_active_client %>
                                                                                </h3>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-md-4 col-sm-6">
                                                                            <div class="metric-card"
                                                                                onclick="openOrdersModal('inquired')">
                                                                                <i
                                                                                    class="fas fa-question-circle fa-2x mb-3"></i>
                                                                                <h5>Most Inquired Item(s)</h5>
                                                                                <h3>
                                                                                    <%= most_inquired_item %>
                                                                                </h3>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </div>

                                                                <!-- Orders Modal -->
                                                                <div class="modal fade" id="ordersModal" tabindex="-1"
                                                                    aria-labelledby="ordersModalLabel"
                                                                    aria-hidden="true">
                                                                    <div
                                                                        class="modal-dialog modal-xl modal-dialog-scrollable">
                                                                        <div class="modal-content">
                                                                            <div class="modal-header">
                                                                                <h5 class="modal-title"
                                                                                    id="ordersModalLabel">Orders</h5>
                                                                                <button type="button"
                                                                                    class="btn-close btn-close-white"
                                                                                    data-bs-dismiss="modal"
                                                                                    aria-label="Close"></button>
                                                                            </div>
                                                                            <div class="modal-body">
                                                                                <div id="ordersTableContainer">
                                                                                    <p class="text-center text-muted">
                                                                                        Loading orders...</p>
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                                <% } %>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function toggleSidebar() {
            document.getElementById('sidebar').classList.toggle('active');
        }

        // Helper function to get badge color based on status
        function getStatusBadgeClass(status) {
            const statusMap = {
                'delivered': 'bg-success',
                'dispatched': 'bg-info',
                'pending': 'bg-warning',
                'inquiry received': 'bg-secondary',
                'quote sent': 'bg-primary',
                'order placed': 'bg-info',
                'cancelled': 'bg-danger'
            };
            return statusMap[status?.toLowerCase()] || 'bg-secondary';
        }

        async function openOrdersModal(type) {
            console.log('Opening modal for type:', type);

            const titles = {
                'week': 'Orders This Week',
                'delivered': 'Delivered Orders',
                'pending': 'Pending Orders',
                'dispatched': 'Dispatched Orders',
                'unplaced': 'Remaining Inquiries',
                'inquired': 'Most Inquired Items',
                'clients': 'Client Order Statistics'
            };

            document.getElementById('ordersModalLabel').textContent = titles[type] || 'Orders';
            document.getElementById('ordersTableContainer').innerHTML =
                '<p class="text-center text-muted">Loading...</p>';

            const modalEl = document.getElementById('ordersModal');
            const modal = bootstrap.Modal.getOrCreateInstance(modalEl);
            modal.show();

            try {
                const response = await fetch(`/api/orders/${type}`);

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const data = await response.json();
                console.log('Received data:', data);

                if (type === 'inquired') {
                    displayInquiredItems(data);
                } else if (type === 'clients') {
                    displayClientOrders(data);
                } else {
                    displayOrders(data);
                }

            } catch (error) {
                console.error('Error fetching data:', error);
                document.getElementById('ordersTableContainer').innerHTML =
                    `<div class="alert alert-danger">Failed to load data: ${error.message}</div>`;
            }
        }

        // Display regular orders in a table
        function displayOrders(orders) {
            const container = document.getElementById('ordersTableContainer');

            if (!orders || orders.length === 0) {
                container.innerHTML = '<p class="text-center text-muted">No orders found.</p>';
                return;
            }

            let html = `
                <div class="table-responsive">
                    <table class="table table-dark table-striped table-hover">
                        <thead>
                            <tr>
                                <th>Order ID</th>
                                <th>Product Name</th>
                                <th>Client Email</th>
                                <th>Quantity</th>
                                <th>Status</th>
                                <th>Last Updated</th>
                                <th>Comments</th>
                            </tr>
                        </thead>
                        <tbody>
            `;

            orders.forEach(order => {
                html += `
                    <tr>
                        <td>#${order.id}</td>
                        <td>${order.product_name || 'N/A'}</td>
                        <td>${order.client_email || 'N/A'}</td>
                        <td>${order.quantity || 'N/A'}</td>
                        <td>
                            <span class="badge ${getStatusBadgeClass(order.order_status)}">
                                ${order.order_status || 'Unknown'}
                            </span>
                        </td>
                        <td>${order.last_updated || 'N/A'}</td>
                        <td>${order.comments || '-'}</td>
                    </tr>
                `;
            });

            html += `
                        </tbody>
                    </table>
                </div>
            `;

            container.innerHTML = html;
        }

        // Display inquired items with ranking
        function displayInquiredItems(items) {
            const container = document.getElementById('ordersTableContainer');

            if (!items || items.length === 0) {
                container.innerHTML = '<p class="text-center text-muted">No orders found in the system.</p>';
                return;
            }

            let html = `
                <div class="table-responsive">
                    <table class="table table-dark table-hover">
                        <thead>
                            <tr>
                                <th style="width: 80px;">#</th>
                                <th>Product Name</th>
                                <th style="text-align: center; width: 200px;">Total Orders</th>
                            </tr>
                        </thead>
                        <tbody>
            `;

            items.forEach((item, index) => {
                let rankBadge = '';
                let badgeColor = 'var(--accent-500)';

                if (index === 0) {
                    rankBadge = '<span style="font-size: 1.2rem; margin-right: 8px;">👑</span>';
                    badgeColor = '#ffd700';
                } else if (index === 1) {
                    rankBadge = '<span style="font-size: 1.1rem; margin-right: 8px;">🥈</span>';
                    badgeColor = '#c0c0c0';
                } else if (index === 2) {
                    rankBadge = '<span style="font-size: 1.1rem; margin-right: 8px;">🥉</span>';
                    badgeColor = '#cd7f32';
                }

                html += `
                    <tr>
                        <td style="font-weight: bold; font-size: 1.1rem;">
                            ${rankBadge}${index + 1}
                        </td>
                        <td style="font-size: 1rem;">
                            ${item.product_name}
                        </td>
                        <td style="text-align: center;">
                            <span class="badge" style="background-color: ${badgeColor}; color: #1a2b1f; font-size: 0.9rem; padding: 8px 16px; border-radius: 20px;">
                                ${item.order_count} ${item.order_count === 1 ? 'order' : 'orders'}
                            </span>
                        </td>
                    </tr>
                `;
            });

            html += `
                        </tbody>
                    </table>
                </div>
                <div class="mt-3 text-center" style="padding: 15px; background: var(--surface-elevated); border-radius: 8px;">
                    <i class="fas fa-info-circle me-2"></i>
                    <strong>Total unique products ordered:</strong> ${items.length} |
                    <strong>Total orders:</strong> ${items.reduce((sum, item) => sum + item.order_count, 0)}
                </div>
            `;

            container.innerHTML = html;
        }

        // Display client order statistics with product breakdown accordion
        function displayClientOrders(clients) {
            const container = document.getElementById('ordersTableContainer');

            if (!clients || clients.length === 0) {
                container.innerHTML = '<p class="text-center text-muted">No client orders found.</p>';
                return;
            }

            let html = `<div class="accordion" id="clientAccordion">`;

            clients.forEach((client, index) => {
                let rankBadge = '';
                if (index === 0) {
                    rankBadge = '<span style="color: #ffd700; font-size: 1.2rem; margin-right: 8px;">👑</span>';
                } else if (index === 1) {
                    rankBadge = '<span style="color: #c0c0c0; font-size: 1.1rem; margin-right: 8px;">🥈</span>';
                } else if (index === 2) {
                    rankBadge = '<span style="color: #cd7f32; font-size: 1.1rem; margin-right: 8px;">🥉</span>';
                }

                html += `
                    <div class="accordion-item" style="background: var(--surface-elevated); border: 1px solid var(--surface-border); margin-bottom: 10px; border-radius: 8px;">
                        <h2 class="accordion-header" id="heading${index}">
                            <button class="accordion-button collapsed" type="button"
                                    data-bs-toggle="collapse" data-bs-target="#collapse${index}"
                                    aria-expanded="false" aria-controls="collapse${index}"
                                    style="background: var(--surface-elevated); color: var(--text-primary); border: none; font-size: 1.1rem; padding: 15px 20px;">
                                ${rankBadge}
                                <strong style="color: var(--accent-400); margin-right: 15px;">#${index + 1}</strong>
                                <span style="flex-grow: 1;">${client.email}</span>
                                <span class="badge" style="background: var(--accent-500); color: white; font-size: 0.9rem; padding: 6px 12px; border-radius: 15px; margin-left: 15px;">
                                    ${client.total_orders} ${client.total_orders === 1 ? 'order' : 'orders'}
                                </span>
                            </button>
                        </h2>
                        <div id="collapse${index}" class="accordion-collapse collapse"
                             aria-labelledby="heading${index}" data-bs-parent="#clientAccordion">
                            <div class="accordion-body" style="background: var(--surface-card); padding: 20px;">
                                <h6 style="color: var(--accent-400); margin-bottom: 15px;">
                                    <i class="fas fa-box me-2"></i>Product Breakdown:
                                </h6>
                                <table class="table table-dark table-sm" style="background: var(--surface-elevated);">
                                    <thead>
                                        <tr>
                                            <th style="width: 70%;">Product Name</th>
                                            <th style="text-align: center;">Quantity Ordered</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                `;

                if (client.products && client.products.length > 0) {
                    client.products.forEach(product => {
                        html += `
                            <tr style="border-bottom: 1px solid var(--surface-border);">
                                <td style="padding: 10px;">${product.product_name}</td>
                                <td style="text-align: center; padding: 10px;">
                                    <span class="badge bg-primary" style="font-size: 0.9rem; padding: 5px 10px;">
                                        ${product.count}
                                    </span>
                                </td>
                            </tr>
                        `;
                    });
                } else {
                    html += `<tr><td colspan="2" class="text-center text-muted">No product data available</td></tr>`;
                }

                html += `
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                `;
            });

            html += `
                </div>
                <div class="mt-3 text-center" style="padding: 15px; background: var(--surface-elevated); border-radius: 8px;">
                    <i class="fas fa-users me-2"></i>
                    <strong>Total active clients:</strong> ${clients.length} |
                    <strong>Total orders:</strong> ${clients.reduce((sum, client) => sum + client.total_orders, 0)}
                </div>
            `;

            container.innerHTML = html;
        }
    </script>
</body>

</html>