<?php
require_once 'partials/guard.php';
require_once '../includes/config.php';

// Fetch quick stats
$totalUsers    = $pdo->query("SELECT COUNT(*) FROM users WHERE role = 'customer'")->fetchColumn();
$totalProducts = $pdo->query("SELECT COUNT(*) FROM products")->fetchColumn();
$totalCartItems = $pdo->query("SELECT COUNT(*) FROM cart_items")->fetchColumn();
$totalCategories = $pdo->query("SELECT COUNT(DISTINCT category) FROM products")->fetchColumn();

$adminName = $_SESSION['admin_name'] ?? 'Admin';
$adminEmail = $_SESSION['admin_email'] ?? '';
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard — GP Crackers</title>
    <meta name="description" content="GP Crackers Admin Panel — Manage users, products and more.">
    <link rel="icon" type="image/png" href="../assets/images/favicon_gp.png">

    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">
    <!-- Admin CSS -->
    <link rel="stylesheet" href="admin.css">
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>

<body>

<!-- Sidebar Overlay (mobile) -->
<div class="sidebar-overlay" id="sidebarOverlay"></div>

<div class="admin-shell">

    <!-- ═══════════════════════ SIDEBAR ═══════════════════════ -->
    <aside class="sidebar" id="adminSidebar">

        <!-- Brand -->
        <a href="index.php" class="sidebar-brand">
            <div class="brand-logo-box"><i class="bi bi-fire"></i></div>
            <div class="brand-text">
                <div class="brand-name">GP Crackers</div>
                <div class="brand-tag">Admin Panel</div>
            </div>
        </a>

        <!-- Navigation -->
        <nav class="sidebar-nav">
            <span class="nav-section-label">Main Menu</span>

            <button class="nav-item active" data-panel="dashboard" onclick="switchPanel('dashboard', this)">
                <i class="bi bi-grid-1x2-fill"></i>
                <span>Dashboard</span>
            </button>

            <button class="nav-item" data-panel="users" onclick="switchPanel('users', this)">
                <i class="bi bi-people-fill"></i>
                <span>Users</span>
                <span class="nav-badge" id="user-count-badge"><?= $totalUsers ?></span>
            </button>

            <!-- Catalog Dropdown -->
            <div class="nav-dropdown-group">
                <button class="nav-dropdown-toggle" id="catalogDropdownBtn">
                    <div>
                        <i class="bi bi-box-seam-fill"></i>
                        <span>Catalog</span>
                    </div>
                    <i class="bi bi-chevron-down nav-dropdown-icon"></i>
                </button>
                <div class="nav-submenu" id="catalogSubmenu">
                    <button class="nav-item" data-panel="products" onclick="switchPanel('products', this, true)">
                        <i class="bi bi-list-ul"></i>
                        <span>All Products</span>
                        <span class="nav-badge" id="product-count-badge"><?= $totalProducts ?></span>
                    </button>
                    <button class="nav-item" data-panel="categories" onclick="switchPanel('categories', this, true)">
                        <i class="bi bi-tags-fill"></i>
                        <span>Categories</span>
                    </button>
                </div>
            </div>

            <button class="nav-item" data-panel="trash" onclick="switchPanel('trash', this)">
                <i class="bi bi-trash3-fill"></i>
                <span>Trash</span>
            </button>
        </nav>

        <!-- Admin Profile & Logout -->
        <div class="sidebar-footer">
            <div class="admin-profile">
                <div class="admin-avatar"><i class="bi bi-person-fill"></i></div>
                <div class="admin-info">
                    <div class="admin-name"><?= htmlspecialchars($adminName) ?></div>
                    <div class="admin-role">Administrator</div>
                </div>
            </div>
            <a href="logout.php" class="btn-logout" onclick="return confirm('Logout from Admin Panel?')">
                <i class="bi bi-box-arrow-left"></i> <span class="logout-text">Logout</span>
            </a>
        </div>
    </aside>

    <!-- ═══════════════════════ MAIN AREA ═══════════════════════ -->
    <div class="main-area">

        <!-- Topbar -->
        <header class="topbar">
            <button class="hamburger-btn" id="hamburgerBtn">
                <i class="bi bi-list"></i>
            </button>
            <button class="topbar-icon-btn d-none-mobile" id="sidebarToggleBtn" title="Toggle Sidebar">
                <i class="bi bi-layout-sidebar"></i>
            </button>

            <div class="topbar-title">
                <h1 id="topbar-heading">Dashboard</h1>
                <p id="topbar-desc">Overview of GP Crackers store</p>
            </div>

            <div class="topbar-actions">
                <a href="../index.html" class="topbar-icon-btn" title="View Store">
                    <i class="bi bi-shop"></i>
                </a>
                <a href="logout.php" class="topbar-icon-btn" title="Logout" onclick="return confirm('Logout from Admin Panel?')">
                    <i class="bi bi-power"></i>
                </a>
            </div>
        </header>

        <!-- Content Area -->
        <main class="content-area">

            <!-- ════════ DASHBOARD PANEL ════════ -->
            <section class="panel active" id="panel-dashboard">

                <!-- Stats Row -->
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-icon navy">
                            <i class="bi bi-people-fill"></i>
                        </div>
                        <div>
                            <div class="stat-value"><?= $totalUsers ?></div>
                            <div class="stat-label">Registered Customers</div>
                        </div>
                    </div>

                    <div class="stat-card">
                        <div class="stat-icon gold">
                            <i class="bi bi-box-seam-fill"></i>
                        </div>
                        <div>
                            <div class="stat-value"><?= $totalProducts ?></div>
                            <div class="stat-label">Total Products</div>
                        </div>
                    </div>

                    <div class="stat-card">
                        <div class="stat-icon green">
                            <i class="bi bi-cart-fill"></i>
                        </div>
                        <div>
                            <div class="stat-value"><?= $totalCartItems ?></div>
                            <div class="stat-label">Active Cart Items</div>
                        </div>
                    </div>

                    <div class="stat-card">
                        <div class="stat-icon purple">
                            <i class="bi bi-tags-fill"></i>
                        </div>
                        <div>
                            <div class="stat-value"><?= $totalCategories ?></div>
                            <div class="stat-label">Product Categories</div>
                        </div>
                    </div>
                </div>

                <!-- Empty State Placeholder -->
                <div class="dashboard-empty">
                    <i class="bi bi-bar-chart-line"></i>
                    <h3>Dashboard content coming soon</h3>
                    <p style="color:#94a3b8; margin-top:8px; font-size:0.85rem;">
                        Charts, reports, and analytics will appear here.
                    </p>
                </div>
            </section>

            <!-- ════════ USERS PANEL ════════ -->
            <section class="panel" id="panel-users">

                <div class="section-header">
                    <div>
                        <h2>All Customers</h2>
                        <p>Registered users of GP Crackers</p>
                    </div>
                </div>

                <div class="toolbar">
                    <div class="search-box">
                        <i class="bi bi-search"></i>
                        <input type="text" id="user-search" placeholder="Search by name, email or phone...">
                    </div>
                    <select class="filter-select" id="role-filter">
                        <option value="">All Roles</option>
                        <option value="customer">Customer</option>
                        <option value="admin">Admin</option>
                    </select>
                </div>

                <div class="data-card">
                    <div class="data-table-wrap">
                        <table class="data-table" id="users-table">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>User</th>
                                    <th>Mobile</th>
                                    <th>Role</th>
                                    <th>Status</th>
                                    <th>Joined</th>
                                </tr>
                            </thead>
                            <tbody id="users-tbody">
                                <tr>
                                    <td colspan="6">
                                        <div class="table-loading">
                                            <div class="spinner"></div>
                                            <p>Loading users...</p>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </section>

            <!-- ════════ CATEGORIES PANEL ════════ -->
            <section class="panel" id="panel-categories">
                <div class="header-with-action">
                    <div class="section-header">
                        <div>
                            <h2>Category Management</h2>
                            <p>Manage product categories dynamically</p>
                        </div>
                    </div>
                </div>

                <div class="toolbar">
                    <form id="add-category-form" class="search-box" style="display:flex; gap:10px; flex:1;">
                        <input type="text" id="new-category-name" placeholder="Enter new category name (e.g. Gift Boxes)" required style="padding-left:14px;">
                        <button type="submit" class="stat-icon navy" style="width:auto; padding:0 20px; border-radius:10px; border:none; color:white; font-size:0.85rem; cursor:pointer; font-family:inherit; font-weight:600;">
                            <i class="bi bi-plus-lg" style="margin-right:5px;"></i> Add Category
                        </button>
                    </form>
                </div>

                <div class="data-card">
                    <div class="data-table-wrap">
                        <table class="data-table" id="categories-table">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Category Name</th>
                                    <th>Slug (ID)</th>
                                    <th>Created On</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="categories-tbody">
                                <!-- Dynamic -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </section>

            <!-- ════════ PRODUCTS PANEL ════════ -->
            <section class="panel" id="panel-products">

                <div class="section-header">
                    <div>
                        <h2>Product Catalogue</h2>
                        <p>All products available in the store</p>
                    </div>
                </div>

                <div class="toolbar">
                    <div class="search-box">
                        <i class="bi bi-search"></i>
                        <input type="text" id="product-search" placeholder="Search products...">
                    </div>
                    <select class="filter-select category-filter-sync" id="category-filter">
                        <option value="">All Categories</option>
                        <!-- Dynamic -->
                    </select>
                </div>

                <div class="data-card">
                    <div class="data-table-wrap">
                        <table class="data-table" id="products-table">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Product</th>
                                    <th>Category</th>
                                    <th>Price</th>
                                    <th>Added On</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="products-tbody">
                                <tr>
                                    <td colspan="6">
                                        <div class="table-loading">
                                            <div class="spinner"></div>
                                            <p>Loading products...</p>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </section>

            <!-- ════════ TRASH PANEL ════════ -->
            <section class="panel" id="panel-trash">
                <div class="section-header">
                    <div>
                        <h2>Trash Bin</h2>
                        <p>Inactive products that can be restored or deleted</p>
                    </div>
                </div>

                <div class="data-card">
                    <div class="data-table-wrap">
                        <table class="data-table" id="trash-table">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Product</th>
                                    <th>Category</th>
                                    <th>Price</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="trash-tbody">
                                <tr>
                                    <td colspan="5">
                                        <div class="table-loading">
                                            <div class="spinner"></div>
                                            <p>Loading trash...</p>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </section>

        </main>
    </div><!-- /main-area -->
</div><!-- /admin-shell -->

<script>
    /* ═══════ Panel Switcher ═══════ */
    const topbarMeta = {
        dashboard:  { heading: 'Dashboard',  desc: 'Overview of GP Crackers store' },
        users:      { heading: 'Users',      desc: 'All registered customers' },
        categories: { heading: 'Categories', desc: 'Dynamic product categories' },
        products:   { heading: 'Products',   desc: 'Full product catalogue' },
        trash:      { heading: 'Trash Bin',  desc: 'Manage deleted products' },
    };

    function switchPanel(panelId, btn, isSubmenu = false) {
        // Hide all panels
        document.querySelectorAll('.panel').forEach(p => p.classList.remove('active'));
        // Deactivate all nav items
        document.querySelectorAll('.nav-item').forEach(n => n.classList.remove('active'));

        // If not a submenu item, maybe close submenus
        if (!isSubmenu) {
            $('.nav-submenu').removeClass('open');
            $('.nav-dropdown-toggle').removeClass('dropdown-active');
        }

        // Activate selected
        document.getElementById('panel-' + panelId).classList.add('active');
        btn.classList.add('active');

        // Update topbar
        const meta = topbarMeta[panelId] || {};
        document.getElementById('topbar-heading').textContent = meta.heading || panelId;
        document.getElementById('topbar-desc').textContent    = meta.desc    || '';

        // Load data on demand
        if (panelId === 'users')      loadUsers();
        if (panelId === 'categories') loadCategories();
        if (panelId === 'products')   loadProducts();
        if (panelId === 'trash')      loadTrash();

        // Close sidebar on mobile
        document.getElementById('adminSidebar').classList.remove('open');
        document.getElementById('sidebarOverlay').classList.remove('show');
    }

    /* ═══════ Sidebar Dropdown Logic ═══════ */
    $('#catalogDropdownBtn').on('click', function() {
        $(this).toggleClass('dropdown-active');
        $('#catalogSubmenu').toggleClass('open');
        
        // If sidebar is collapsed and they click this, uncollapse it
        const sidebar = document.getElementById('adminSidebar');
        if (sidebar.classList.contains('collapsed')) {
            sidebar.classList.remove('collapsed');
        }
    });

    /* ═══════ Sidebar Toggle (mobile) ═══════ */
    document.getElementById('hamburgerBtn').addEventListener('click', () => {
        document.getElementById('adminSidebar').classList.toggle('open');
        document.getElementById('sidebarOverlay').classList.toggle('show');
    });

    document.getElementById('sidebarOverlay').addEventListener('click', () => {
        document.getElementById('adminSidebar').classList.remove('open');
        document.getElementById('sidebarOverlay').classList.remove('show');
    });

    /* ═══════ Sidebar Toggle (Desktop) ═══════ */
    const sidebarToggleBtn = document.getElementById('sidebarToggleBtn');
    if (sidebarToggleBtn) {
        sidebarToggleBtn.addEventListener('click', () => {
            document.getElementById('adminSidebar').classList.toggle('collapsed');
        });
    }

    /* ═══════ Load Users ═══════ */
    let usersData = [];

    function loadUsers() {
        $.getJSON('data/get_users.php', function (res) {
            usersData = res.data || [];
            renderUsers(usersData);
        }).fail(function () {
            $('#users-tbody').html('<tr><td colspan="5"><div class="empty-state"><i class="bi bi-exclamation-triangle"></i><p>Failed to load users.</p></div></td></tr>');
        });
    }

    function renderUsers(data) {
        if (!data.length) {
            $('#users-tbody').html('<tr><td colspan="5"><div class="empty-state"><i class="bi bi-people"></i><p>No users found.</p></div></td></tr>');
            return;
        }

        let html = '';
        data.forEach((u, i) => {
            const initials = u.full_name.split(' ').map(w => w[0]).join('').toUpperCase().slice(0, 2);
            const roleClass = u.role === 'admin' ? 'admin' : 'customer';
            const roleLabel = u.role === 'admin' ? 'Admin' : 'Customer';
            const joined = new Date(u.created_at).toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric' });
            const isActive = (u.is_active != 0);
            const statusLabel = isActive ? 'Active' : 'Inactive';
            const statusClass = isActive ? 'active' : 'inactive';

            html += `
                <tr data-role="${u.role}" data-name="${u.full_name.toLowerCase()}" data-email="${u.email.toLowerCase()}" data-phone="${u.phone_number}">
                    <td style="color:var(--text-muted); font-weight:600;">${i + 1}</td>
                    <td>
                        <div class="user-cell">
                            <div class="user-avatar-sm">${initials}</div>
                            <div class="user-cell-info">
                                <div class="name">${htmlEscape(u.full_name)}</div>
                                <div class="email">${htmlEscape(u.email)}</div>
                            </div>
                        </div>
                    </td>
                    <td style="font-size:0.85rem;">${htmlEscape(u.phone_number)}</td>
                    <td><span class="badge-pill ${roleClass}">${roleLabel}</span></td>
                    <td>
                        <label class="status-toggle">
                            <input type="checkbox" ${isActive ? 'checked' : ''} onchange="toggleUserStatus(${u.id}, this)">
                            <span class="toggle-slider"></span>
                        </label>
                        <span class="status-text ${statusClass}">${statusLabel}</span>
                    </td>
                    <td style="color:var(--text-muted); font-size:0.82rem;">${joined}</td>
                </tr>
            `;
        });

        $('#users-tbody').html(html);
    }

    /* ═══════ Toggle User Status ═══════ */
    function toggleUserStatus(userId, checkbox) {
        const newStatus = checkbox.checked ? 1 : 0;
        const statusText = $(checkbox).closest('td').find('.status-text');

        // Disable checkbox while processing
        checkbox.disabled = true;

        $.ajax({
            url: 'api/update_user_status.php',
            type: 'POST',
            data: { userId: userId, status: newStatus },
            success: function(res) {
                checkbox.disabled = false;
                if (res.status === 'success') {
                    // Update UI
                    if (newStatus === 1) {
                        statusText.text('Active').removeClass('inactive').addClass('active');
                    } else {
                        statusText.text('Inactive').removeClass('active').addClass('inactive');
                    }
                    // Optional: show small toast
                } else {
                    // Revert UI on failure
                    checkbox.checked = !checkbox.checked;
                    alert(res.message || 'Failed to update user status.');
                }
            },
            error: function() {
                checkbox.disabled = false;
                checkbox.checked = !checkbox.checked;
                alert('Connection error. Could not update status.');
            }
        });
    }

    // Live search for users
    $('#user-search').on('input', filterUsers);
    $('#role-filter').on('change', filterUsers);

    function filterUsers() {
        const q      = $('#user-search').val().toLowerCase();
        const role   = $('#role-filter').val();
        const filtered = usersData.filter(u => {
            const matchQ    = !q || u.full_name.toLowerCase().includes(q) || u.email.toLowerCase().includes(q) || u.phone_number.includes(q);
            const matchRole = !role || u.role === role;
            return matchQ && matchRole;
        });
        renderUsers(filtered);
    }

    /* ═══════ Product & Category Shared Data ═══════ */
    let productsData = [];
    let categoriesList = [];

    // Global category map for quick label lookup
    let catMap = {};

    function loadCategories(callback) {
        $.getJSON('data/get_categories.php', function(res) {
            categoriesList = res.data || [];
            catMap = {};
            let optionsHtml = '<option value="">All Categories</option>';
            
            categoriesList.forEach(c => {
                catMap[c.slug] = c.name;
                optionsHtml += `<option value="${c.slug}">${c.name}</option>`;
            });

            // Update all category filter selects across the UI
            $('.category-filter-sync').html(optionsHtml);
            
            renderCategories(categoriesList);
            if(callback) callback();
        });
    }

    function renderCategories(data) {
        let html = '';
        if(!data.length) {
            html = '<tr><td colspan="5"><div class="empty-state"><i class="bi bi-tag"></i><p>No categories found.</p></div></td></tr>';
        } else {
            data.forEach((c, i) => {
                const date = new Date(c.created_at).toLocaleDateString();
                html += `
                    <tr>
                        <td style="color:var(--text-muted); font-weight:600;">${i+1}</td>
                        <td style="font-weight:600;">${htmlEscape(c.name)}</td>
                        <td><code style="background:#f1f5f9; padding:2px 6px; border-radius:4px;">${c.slug}</code></td>
                        <td style="color:var(--text-muted);">${date}</td>
                        <td>
                            <div style="display:flex; gap:8px;">
                                <button class="action-btn restore" onclick="editCategory(${c.id}, '${htmlEscape(c.name)}')" title="Edit Category">
                                    <i class="bi bi-pencil-square"></i>
                                </button>
                                <button class="action-btn delete" onclick="deleteCategory(${c.id})" title="Delete Category">
                                    <i class="bi bi-x-lg"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                `;
            });
        }
        $('#categories-tbody').html(html);
    }

    // Add Category Form
    $('#add-category-form').on('submit', function(e) {
        e.preventDefault();
        const name = $('#new-category-name').val();
        $.post('api/add_category.php', { name: name }, function(res) {
            if(res.status === 'success') {
                $('#new-category-name').val('');
                loadCategories();
            } else {
                alert(res.message);
            }
        });
    });

    function deleteCategory(id) {
        if(!confirm('Delete this category?')) return;
        $.post('api/delete_category.php', { id: id }, function(res) {
            if(res.status === 'success') loadCategories();
            else alert(res.message);
        });
    }

    // Edit Category Prompt
    function editCategory(id, currentName) {
        const newName = prompt('Enter new category name:', currentName);
        if (newName !== null && newName.trim() !== '' && newName.trim() !== currentName) {
            $.post('api/edit_category.php', { id: id, name: newName.trim() }, function(res) {
                if (res.status === 'success') {
                    loadCategories();
                } else {
                    alert(res.message);
                }
            });
        }
    }

    /* ═══════ Load Products ═══════ */
    function loadProducts() {
        // Always ensure categories are loaded for label mapping
        loadCategories(() => {
            $.getJSON('data/get_products.php', function (res) {
                productsData = res.data || [];
                renderProducts(productsData);
            }).fail(function () {
                $('#products-tbody').html('<tr><td colspan="6"><div class="empty-state"><i class="bi bi-exclamation-triangle"></i><p>Failed to load products.</p></div></td></tr>');
            });
        });
    }

    function renderProducts(data) {
        if (!data.length) {
            $('#products-tbody').html('<tr><td colspan="6"><div class="empty-state"><i class="bi bi-box-seam"></i><p>No products found.</p></div></td></tr>');
            return;
        }

        let html = '';
        data.forEach((p, i) => {
            const catLabel = catMap[p.category] || p.category;
            const added    = new Date(p.created_at).toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric' });
            const imgSrc   = '../' + p.image_url.replace(/^\.\//, '');

            html += `
                <tr data-category="${p.category}" data-name="${p.name.toLowerCase()}">
                    <td style="color:var(--text-muted); font-weight:600;">${i + 1}</td>
                    <td>
                        <div class="product-cell">
                            <img src="${imgSrc}" alt="${htmlEscape(p.name)}" class="product-thumb"
                                 onerror="this.src='../assets/images/favicon_gp.png'">
                            <div class="product-cell-info">
                                <div class="pname">${htmlEscape(p.name)}</div>
                                <div class="pcategory">${htmlEscape(catLabel)}</div>
                            </div>
                        </div>
                    </td>
                    <td><span class="cat-tag">${htmlEscape(catLabel)}</span></td>
                    <td class="price-cell">₹${parseFloat(p.price).toFixed(2)}</td>
                    <td style="color:var(--text-muted); font-size:0.82rem;">${added}</td>
                    <td>
                        <button class="action-btn trash" onclick="trashProduct(${p.id})" title="Move to Trash">
                            <i class="bi bi-trash"></i>
                        </button>
                    </td>
                </tr>
            `;
        });

        $('#products-tbody').html(html);
    }

    /* ═══════ Trash Product ═══════ */
    function trashProduct(id) {
        if (!confirm('Move this product to trash?')) return;
        $.post('api/trash_product.php', { productId: id }, function(res) {
            if (res.status === 'success') {
                loadProducts();
                // Update badge if possible or just refresh
                location.reload(); 
            } else {
                alert(res.message);
            }
        });
    }

    /* ═══════ Load Trash ═══════ */
    function loadTrash() {
        loadCategories(() => {
            $.getJSON('data/get_trash_products.php', function (res) {
                renderTrash(res.data || []);
            }).fail(function () {
                $('#trash-tbody').html('<tr><td colspan="5"><div class="empty-state"><i class="bi bi-exclamation-triangle"></i><p>Failed to load trash.</p></div></td></tr>');
            });
        });
    }

    function renderTrash(data) {
        if (!data.length) {
            $('#trash-tbody').html('<tr><td colspan="5"><div class="empty-state"><i class="bi bi-trash3"></i><p>Trash is empty.</p></div></td></tr>');
            return;
        }

        let html = '';
        data.forEach((p, i) => {
            const catLabel = catMap[p.category] || p.category;
            const imgSrc   = '../' + p.image_url.replace(/^\.\//, '');

            html += `
                <tr>
                    <td style="color:var(--text-muted); font-weight:600;">${i + 1}</td>
                    <td>
                        <div class="product-cell">
                            <img src="${imgSrc}" alt="${htmlEscape(p.name)}" class="product-thumb" onerror="this.src='../assets/images/favicon_gp.png'">
                            <div class="product-cell-info">
                                <div class="pname">${htmlEscape(p.name)}</div>
                                <div class="pcategory">${htmlEscape(catLabel)}</div>
                            </div>
                        </div>
                    </td>
                    <td><span class="cat-tag">${htmlEscape(catLabel)}</span></td>
                    <td class="price-cell">₹${parseFloat(p.price).toFixed(2)}</td>
                    <td>
                        <div style="display:flex; gap:8px;">
                            <button class="action-btn restore" onclick="restoreProduct(${p.id})" title="Restore Product">
                                <i class="bi bi-arrow-counterclockwise"></i>
                            </button>
                            <button class="action-btn delete" onclick="deleteProduct(${p.id})" title="Delete Permanently">
                                <i class="bi bi-x-lg"></i>
                            </button>
                        </div>
                    </td>
                </tr>
            `;
        });
        $('#trash-tbody').html(html);
    }

    function restoreProduct(id) {
        $.post('api/restore_product.php', { productId: id }, function(res) {
            if (res.status === 'success') loadTrash();
            else alert(res.message);
        });
    }

    function deleteProduct(id) {
        if (!confirm('PERMANENTLY delete this product? This cannot be undone.')) return;
        $.post('api/delete_product.php', { productId: id }, function(res) {
            if (res.status === 'success') loadTrash();
            else alert(res.message);
        });
    }

    // Live search for products
    $('#product-search').on('input', filterProducts);
    $('#category-filter').on('change', filterProducts);

    function filterProducts() {
        const q   = $('#product-search').val().toLowerCase();
        const cat = $('#category-filter').val();
        const filtered = productsData.filter(p => {
            const matchQ   = !q   || p.name.toLowerCase().includes(q);
            const matchCat = !cat || p.category === cat;
            return matchQ && matchCat;
        });
        renderProducts(filtered);
    }

    /* Helper */
    function htmlEscape(str) {
        return String(str)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;');
    }
</script>
</body>
</html>
