<?php
session_start();

// Check if user is logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BeAccurate Admin</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="css/style.css">
    <!-- Replace QuaggaJS with ZXing -->
    <script src="https://unpkg.com/@zxing/library@latest"></script>
</head>
<body>

    <aside class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <h2><i class="fas fa-user-shield"></i> Admin</h2>
        </div>
        <nav>
            <ul>
                <li><a href="#" class="nav-link active" data-page="dashboard"><i class="fas fa-tachometer-alt"></i> Dashboard</a></li>
                <li><a href="#" class="nav-link" data-page="product-list"><i class="fas fa-box-open"></i> Products</a></li>
                <li><a href="#" class="nav-link" data-page="product-requests"><i class="fas fa-tasks"></i> Requests</a></li>
                <li><a href="#" class="nav-link" data-page="settings"><i class="fas fa-cog"></i> Settings</a></li>
                <li><a href="logout.php" class="logout-btn"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
            </ul>
        </nav>
    </aside>

    <div class="main-content" id="main-content">
        <header class="content-header">
            <div class="menu-toggle" id="menu-toggle">
                <i class="fas fa-bars"></i>
            </div>
            <h1 class="page-title" id="page-title-display">Dashboard</h1>
            <div class="header-actions">
                <button class="btn icon-only search-toggle-btn" id="search-toggle-mobile" aria-label="Toggle search">
                    <i class="fas fa-search"></i>
                </button>
                <div class="search-bar" id="search-bar-desktop">
                    <input type="text" placeholder="Search..." id="search-input">
                    <button id="search-button" aria-label="Search"><i class="fas fa-search"></i></button>
                </div>
            </div>
        </header>
        <div class="mobile-search-container" id="mobile-search-container">
            <input type="text" placeholder="Search..." id="mobile-search-input" aria-label="Mobile search input">
            <button id="mobile-search-execute-btn" aria-label="Execute mobile search"><i class="fas fa-search"></i></button>
            <button id="mobile-search-close-btn" aria-label="Close mobile search">×</button>
        </div>

        <main class="page-content-area">
            <!-- Dashboard Page -->
            <section id="dashboard-page" class="page active">
                <div class="dashboard-stats">
                    <div class="stat-card"><i class="fas fa-mobile-alt"></i><h3>App Opens</h3><p id="app-opens">Loading...</p></div>
                    <div class="stat-card"><i class="fas fa-ban"></i><h3>Boycotts</h3><p id="boycotts">Loading...</p></div>
                    <div class="stat-card"><i class="fas fa-users"></i><h3>Admin Username</h3><p id="admin-username">Loading...</p></div>
                    <div class="stat-card"><i class="fas fa-chart-line"></i><h3>LDUT</h3><p id="ldut">Loading...</p></div>
                </div>
            </section>

            <!-- Product List Page -->
            <section id="product-list-page" class="page">
                <h3>Manage Products</h3>
                <div class="action-bar">
                    <button class="btn btn-primary" id="add-new-product-btn"><i class="fas fa-plus"></i> Add New Product</button>
                </div>
                <div class="list-container" id="product-list-container">
                    <!-- Products will be loaded here dynamically -->
                </div>
            </section>

            <section id="product-requests-page" class="page">
                <h3>Pending Product Requests</h3>
                <div class="action-bar">
                    <button id="refresh-requests-btn" class="btn btn-primary">
                        <i class="fas fa-sync"></i> Refresh List
                    </button>
                </div>
                <div class="list-container" id="request-list-container">
                    <!-- Requests will be loaded here dynamically -->
                </div>
            </section>

            <section id="settings-page" class="page">
                <h3>General Settings</h3>
                <form class="settings-form form-group" id="general-settings-form">
                    <div class="form-group">
                        <label for="new-username">New Username</label>
                        <input type="text" id="new-username" name="new_username" placeholder="Enter new username">
                    </div>
                    <div class="form-group">
                        <label for="current-password">Current Password</label>
                        <input type="password" id="current-password" name="current_password" required>
                    </div>
                    <div class="form-group">
                        <label for="new-password">New Password</label>
                        <input type="password" id="new-password" name="new_password" placeholder="Enter new password">
                    </div>
                    <div class="form-group">
                        <label for="confirm-password">Confirm New Password</label>
                        <input type="password" id="confirm-password" name="confirm_password" placeholder="Confirm new password">
                    </div>
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save Changes</button>
                </form>

                <h3>System Maintenance</h3>
                <div class="maintenance-section">
                    <div class="maintenance-card">
                        <div class="maintenance-header">
                            <i class="fas fa-broom"></i>
                            <h4>Image Cleanup</h4>
                        </div>
                        <div class="maintenance-content">
                            <p class="maintenance-description">This will remove any unused images from both products and requests that are no longer being used in the database.</p>
                            <button type="button" id="cleanup-all-images-btn" class="btn btn-warning">
                                <i class="fas fa-broom"></i> Clean Up All Unused Images
                            </button>
                        </div>
                    </div>
                </div>
            </section>
        </main>
    </div>

    <div id="product-modal" class="modal">
        <div class="modal-content large">
            <div class="modal-header">
                <h3 id="modal-title">Add Product</h3>
                <span class="close-modal" id="close-product-modal">×</span>
            </div>
            <div class="modal-body">
                <form id="product-form" method="post" enctype="multipart/form-data">
                    <input type="hidden" id="product-id" name="product-id">
                    <h4>Main Info</h4>
                    <div class="form-grid">
                        <div class="form-group">
                            <label for="productImageFile">Product Image</label>
                            <input type="file" id="productImageFile" accept="image/*">
                        </div>
                        <div class="form-group">
                            <label for="productName">Name</label>
                            <input type="text" class="name-fix" id="productName" name="name" required>
                        </div>
                        <div class="form-group">
                            <label for="productBrand">Brand</label>
                            <input type="text" id="productBrand" name="brand" required>
                        </div>
                        <div class="form-group">
                            <label for="productCategory">Category</label>
                            <select id="productCategory" name="category" required>
                                <option value="">Select Category</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="productSubCategory">Sub Category</label>
                            <select id="productSubCategory" name="subcategory">
                                <option value="">Select Sub Category</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="productBarcode">Barcode (Optional)</label>
                            <div class="input-group">
                                <input type="text" id="productBarcode" name="barcode">
                                <button type="button" class="btn btn-secondary scan-barcode-btn">
                                    <i class="fas fa-barcode"></i> Scan
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="form-group form-group-full">
                        <label for="productMoreInfo">More Info</label>
                        <textarea id="productMoreInfo" name="moreinfo"></textarea>
                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" id="cancel-product-form">Cancel</button>
                <button type="button" class="btn btn-primary" id="save-product-btn">Save</button>
            </div>
        </div>
    </div>

    <!-- Add Image Viewer Modal -->
    <div id="image-viewer-modal" class="modal">
        <div class="modal-content image-viewer">
            <span class="close-modal" id="close-image-viewer">×</span>
            <img id="viewer-image" src="" alt="Product Image">
        </div>
    </div>

    <!-- Add Barcode Scanner Modal -->
    <div id="barcode-scanner-modal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Scan Barcode/QR Code</h3>
                <span class="close-modal" id="close-scanner-modal">×</span>
            </div>
            <div class="modal-body">
                <div id="interactive" class="viewport">
                    <video id="video"></video>
                </div>
                <div class="scanner-controls">
                    <button id="stop-scan" class="btn btn-danger">
                        <i class="fas fa-stop"></i> Stop Scanner
                    </button>
                </div>
            </div>
        </div>
    </div>

<script src="js/script.js"></script>
    <script>
// Function to update dashboard data
function updateDashboardData() {
    fetch('src/get_dashboard_data.php')
        .then(response => response.json())
        .then(data => {
            document.getElementById('app-opens').textContent = data.app_opens;
            document.getElementById('boycotts').textContent = data.boycotts;
            document.getElementById('admin-username').textContent = data.admin_username;
            document.getElementById('ldut').textContent = data.ldut;
        })
        .catch(error => console.error('Error fetching dashboard data:', error));
}

// Update dashboard data when page loads
document.addEventListener('DOMContentLoaded', updateDashboardData);

// Update dashboard data every 30 seconds
setInterval(updateDashboardData, 30000);

// Function to load products
function loadProducts(searchTerm = '') {
    fetch('src/get_products.php')
        .then(response => response.json())
        .then(products => {
            if (searchTerm) {
                products = products.filter(product =>
                    product.ProductName.toLowerCase().includes(searchTerm.toLowerCase()) ||
                    product.ProductBrand.toLowerCase().includes(searchTerm.toLowerCase()) ||
                    (product.Barcode && product.Barcode.toLowerCase().includes(searchTerm.toLowerCase())) ||
                    (product.ProductCategory && product.ProductCategory.toLowerCase().includes(searchTerm.toLowerCase()))
                );
            }
            const container = document.getElementById('product-list-container');
            container.innerHTML = '';
            if (products.length === 0) {
                container.innerHTML = '<div class="no-products">No products found</div>';
                return;
            }
            products.forEach(product => {
                const productHtml = `
                    <div class="list-item">
                        <div class="list-item-image">
                            ${product.ProductImage ? 
                                `<img src="uploads/products/${product.ProductImage}" alt="${product.ProductName}" class="product-image" onclick="showImageViewer('uploads/products/${product.ProductImage}', '${product.ProductName}')">` : 
                                `<i class="fas fa-image"></i>`}
                        </div>
                        <div class="list-item-details">
                            <h4>${product.ProductName} ${product.Barcode ? `(${product.Barcode})` : ''}</h4>
                            <p><strong>Brand:</strong> ${product.ProductBrand}</p>
                            <p><strong>Category:</strong> ${product.ProductCategory}</p>
                            <p><strong>Boycott Count:</strong> ${product.BoycottCount}</p>
                            <p><strong>Report:</strong> ${product.Report || 'N/A'}</p>
                        </div>
                        <div class="list-item-actions">
                            <button class="btn btn-info edit-product-btn" data-id="${product.ID || ''}">
                                <i class="fas fa-edit"></i> Edit
                            </button>
                            <button class="btn btn-danger delete-item-btn" data-id="${product.ID || ''}">
                                <i class="fas fa-trash"></i> Delete
                            </button>
                        </div>
                    </div>
                `;
                container.innerHTML += productHtml;
            });
        })
        .catch(error => {
            console.error('Error loading products:', error);
            const container = document.getElementById('product-list-container');
            container.innerHTML = '<div class="error-message">Error loading products</div>';
        });
}

// Function to load categories and subcategories
function loadCategories() {
    return fetch('src/get_categories.php')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const categorySelect = document.getElementById('productCategory');
                const subcategorySelect = document.getElementById('productSubCategory');
                
                // Clear existing options
                categorySelect.innerHTML = '<option value="">Select Category</option>';
                subcategorySelect.innerHTML = '<option value="">Select Sub Category</option>';
                
                // Add categories
                data.categories.forEach(category => {
                    const option = document.createElement('option');
                    option.value = category;
                    option.textContent = category;
                    categorySelect.appendChild(option);
                });

                // Store subcategories data
                window.subcategoriesData = data.subcategories;
            }
        })
        .catch(error => {
            console.error('Error loading categories:', error);
            showToast('Error loading categories', 'error');
        });
}

// Function to update subcategories based on selected category
function updateSubcategories(category) {
    const subcategorySelect = document.getElementById('productSubCategory');
    subcategorySelect.innerHTML = '<option value="">Select Sub Category</option>';
    
    if (category && window.subcategoriesData && window.subcategoriesData[category]) {
        window.subcategoriesData[category].forEach(subcategory => {
            const option = document.createElement('option');
            option.value = subcategory;
            option.textContent = subcategory;
            subcategorySelect.appendChild(option);
        });
    }
}

// Function to reset form and show modal for new product
function showAddProductModal() {
    const form = document.getElementById('product-form');
    form.reset();
    form.dataset.action = 'add';
    
    // Clear product ID
    document.getElementById('product-id').value = '';
    
    // Update modal title
    document.getElementById('modal-title').textContent = 'Add New Product';
    
    // Reset validation states
    document.querySelectorAll('.barcode-input, .product-name-input').forEach(container => {
        container.classList.remove('valid', 'invalid');
        const feedback = container.querySelector('.barcode-feedback, .product-name-feedback');
        if (feedback) feedback.remove();
    });
    
    // Enable save button
    const saveButton = document.getElementById('save-product-btn');
    if (saveButton) {
        saveButton.disabled = false;
        saveButton.classList.remove('btn-disabled');
    }
    
    // Show modal
    document.getElementById('product-modal').style.display = 'block';
}

// Function to load product data for editing
function loadProductForEdit(id) {
    const formData = new FormData();
    formData.append('action', 'get');
    formData.append('id', id);

    fetch('src/product_operations.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(product => {
        if (!product) {
            throw new Error('No product data received');
        }

        const form = document.getElementById('product-form');
        form.dataset.action = 'edit';
        form.dataset.originalId = product.ID;
        
        // Fill form fields
        document.getElementById('product-id').value = product.ID;
        document.getElementById('productName').value = product.ProductName;
        document.getElementById('productBrand').value = product.ProductBrand;
        
        // Store the existing image
        const imageFileInput = document.getElementById('productImageFile');
        if (product.ProductImage) {
            imageFileInput.dataset.existingImage = product.ProductImage;
        }
        
        // Load categories first, then set the selected category and subcategory
        return loadCategories().then(() => {
            document.getElementById('productCategory').value = product.ProductCategory;
            updateSubcategories(product.ProductCategory);
            setTimeout(() => {
                document.getElementById('productSubCategory').value = product.SubCategory;
            }, 100);
            
            document.getElementById('productBarcode').value = product.Barcode;
            document.getElementById('productMoreInfo').value = product.MoreInfo;

            // Fill alternative products
            for (let i = 1; i <= 3; i++) {
                // Check if any alternative product data exists (name, brand, barcode, or image)
                const hasAltData = product[`AlternativeName${i}`] || 
                                 product[`AlternativeBrand${i}`] || 
                                 product[`AlternativeBarcode${i}`] || 
                                 product[`AlternativeImage${i}`];
                
                if (hasAltData) {
                    // Set existing image if available
                    if (product[`AlternativeImage${i}`]) {
                        const altImageInput = document.getElementById(`altIF${i}`);
                        if (altImageInput) {
                            altImageInput.dataset.existingImage = product[`AlternativeImage${i}`];
                        }
                    }
                    
                    // Fill all alternative product fields
                    const altNameField = document.getElementById(`altN${i}`);
                    const altBrandField = document.getElementById(`altB${i}`);
                    const altBarcodeField = document.getElementById(`altBC${i}`);
                    
                    if (altNameField) altNameField.value = product[`AlternativeName${i}`] || '';
                    if (altBrandField) altBrandField.value = product[`AlternativeBrand${i}`] || '';
                    if (altBarcodeField) altBarcodeField.value = product[`AlternativeBarcode${i}`] || '';
                }
            }

            // Update modal title
            document.getElementById('modal-title').textContent = 'Edit Product';
            document.getElementById('product-modal').style.display = 'block';
        });
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('An error occurred while loading the product data', 'error');
    });
}

// Product name validation function
function checkProductName(productName, inputElement, originalBarcode = '') {
    if (!productName) {
        updateSaveButtonState();
        return;
    }

    const formData = new FormData();
    formData.append('product_name', productName);
    formData.append('original_barcode', originalBarcode);

    fetch('src/check_product_name.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        const container = inputElement.closest('.product-name-input');
        if (!container) return;

        if (data.exists) {
            container.classList.remove('valid');
            container.classList.add('invalid');
            const feedback = container.querySelector('.product-name-feedback') || document.createElement('div');
            feedback.className = 'product-name-feedback';
            feedback.textContent = 'Product name already exists';
            if (!container.querySelector('.product-name-feedback')) {
                container.appendChild(feedback);
            }
        } else {
            container.classList.remove('invalid');
            container.classList.add('valid');
            const feedback = container.querySelector('.product-name-feedback') || document.createElement('div');
            feedback.className = 'product-name-feedback';
            feedback.textContent = 'Product name available';
            if (!container.querySelector('.product-name-feedback')) {
                container.appendChild(feedback);
            }
        }
        updateSaveButtonState();
    })
    .catch(error => {
        console.error('Error checking product name:', error);
        updateSaveButtonState();
    });
}

// Function to update save button state
function updateSaveButtonState() {
    const saveButton = document.getElementById('save-product-btn');
    if (!saveButton) return;
    
    // Always enable the save button
    saveButton.disabled = false;
    saveButton.classList.remove('btn-disabled');
    saveButton.title = '';
}

// Add styles for disabled button
const style = document.createElement('style');
style.textContent = `
    .btn-disabled {
        opacity: 1;
        cursor: pointer;
    }
    
    .btn-disabled:hover {
        background-color: #007bff;
        border-color: #007bff;
    }
`;
document.head.appendChild(style);

// Update setupBarcodeValidation to remove button state updates
function setupBarcodeValidation() {
    // Main product barcode
    const mainBarcodeInput = document.getElementById('productBarcode');
    if (mainBarcodeInput) {
        const container = mainBarcodeInput.closest('.input-group');
        container.classList.add('barcode-input');
        
        let timeout;
        mainBarcodeInput.addEventListener('input', (e) => {
            clearTimeout(timeout);
            timeout = setTimeout(() => {
                const originalBarcode = document.getElementById('product-id').value;
                checkBarcode(e.target.value, mainBarcodeInput, originalBarcode);
            }, 500);
        });
    }

    // Alternative product barcodes
    for (let i = 1; i <= 3; i++) {
        const altBarcodeInput = document.getElementById(`altBC${i}`);
        if (altBarcodeInput) {
            const container = altBarcodeInput.closest('.input-group');
            container.classList.add('barcode-input');
            
            let timeout;
            altBarcodeInput.addEventListener('input', (e) => {
                clearTimeout(timeout);
                timeout = setTimeout(() => {
                    checkBarcode(e.target.value, altBarcodeInput);
                }, 500);
            });
        }
    }
}

// Update setupProductNameValidation to remove button state updates
function setupProductNameValidation() {
    const productNameInput = document.getElementById('productName');
    if (productNameInput) {
        const container = productNameInput.closest('.form-group');
        container.classList.add('product-name-input');
        
        let timeout;
        productNameInput.addEventListener('input', (e) => {
            clearTimeout(timeout);
            timeout = setTimeout(() => {
                const originalBarcode = document.getElementById('product-id').value;
                checkProductName(e.target.value, productNameInput, originalBarcode);
            }, 500);
        });
    }
}

// Toast notification function
function showToast(message, type = 'success') {
    const container = document.getElementById('toast-container');
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    
    const messageDiv = document.createElement('div');
    messageDiv.className = 'toast-message';
    messageDiv.textContent = message;
    
    const closeButton = document.createElement('button');
    closeButton.className = 'toast-close';
    closeButton.innerHTML = '×';
    closeButton.onclick = () => {
        toast.style.animation = 'fadeOut 0.3s ease-in-out forwards';
        setTimeout(() => toast.remove(), 300);
    };
    
    toast.appendChild(messageDiv);
    toast.appendChild(closeButton);
    container.appendChild(toast);
    
    // Auto remove after 3 seconds
    setTimeout(() => {
        if (toast.parentElement) {
            toast.style.animation = 'fadeOut 0.3s ease-in-out forwards';
            setTimeout(() => toast.remove(), 300);
        }
    }, 3000);
}

// Update handleProductFormSubmit to properly handle all action cases
function handleProductFormSubmit() {
    const form = document.getElementById('product-form');
    const productName = document.getElementById('productName').value;
    const barcode = document.getElementById('productBarcode').value.trim();
    const originalId = document.getElementById('product-id').value;
    const modal = document.getElementById('product-modal');
    const action = form.dataset.action || 'add';

    // First check if product name is filled
    if (!productName) {
        showToast('Please fill in the product name', 'error');
        return false;
    }

    // Create FormData objects for both checks
    const barcodeFormData = new FormData();
    barcodeFormData.append('barcode', barcode);
    barcodeFormData.append('original_id', originalId);

    const nameFormData = new FormData();
    nameFormData.append('product_name', productName);
    nameFormData.append('original_id', originalId);

    // Only perform validation if we're adding a new product
    if (action === 'add') {
        // Check both barcode and product name before submission
        Promise.all([
            barcode ? fetch('src/check_barcode.php', {
                method: 'POST',
                body: barcodeFormData
            }).then(response => response.json()) : Promise.resolve({ exists: false }),
            
            fetch('src/check_product_name.php', {
                method: 'POST',
                body: nameFormData
            }).then(response => response.json())
        ])
        .then(([barcodeResult, nameResult]) => {
            let errorMessage = '';
            
            if (barcode && barcodeResult.exists) {
                errorMessage += 'Barcode already exists.\n';
            }
            if (nameResult.exists) {
                errorMessage += 'Product name already exists.\n';
            }

            if (errorMessage) {
                showToast(errorMessage, 'error');
                return;
            }

            // If both are unique, proceed with form submission
            submitForm();
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('An error occurred while processing your request', 'error');
        });
    } else {
        // For edit action, submit the form directly
        submitForm();
    }

    function submitForm() {
        const formData = new FormData();
        formData.append('action', action);

        // Add request_id for review action
        if (action === 'review' && form.dataset.requestId) {
            formData.append('request_id', form.dataset.requestId);
        }

        if (action === 'edit') {
            formData.append('original_id', form.dataset.originalId);
        }

        // Get image file
        const imageFile = document.getElementById('productImageFile').files[0];
        if (imageFile) {
            formData.append('productImageFile', imageFile);
        } else {
            // If no new image is selected, use the existing image
            const existingImage = document.getElementById('productImageFile').dataset.existingImage;
            if (existingImage) {
                formData.append('existing_image', existingImage);
            }
        }

        // Add main product data
        formData.append('name', document.getElementById('productName').value);
        formData.append('brand', document.getElementById('productBrand').value);
        formData.append('category', document.getElementById('productCategory').value);
        formData.append('subcategory', document.getElementById('productSubCategory').value);
        formData.append('barcode', document.getElementById('productBarcode').value.trim());
        formData.append('moreinfo', document.getElementById('productMoreInfo').value);

        // Add alternative products data
        for (let i = 1; i <= 3; i++) {
            const altImage = document.getElementById(`altIF${i}`);
            const altName = document.getElementById(`altN${i}`);
            const altBrand = document.getElementById(`altB${i}`);
            const altBarcode = document.getElementById(`altBC${i}`);

            if (altImage && altName && altBrand && altBarcode) {
                const altImageFile = altImage.files[0];
                if (altImageFile) {
                    formData.append(`altimg${i}`, altImageFile);
                } else {
                    // If no new image is selected, use the existing image
                    const existingAltImage = altImage.dataset.existingImage;
                    if (existingAltImage) {
                        formData.append(`existing_altimg${i}`, existingAltImage);
                    }
                }
                
                formData.append(`altname${i}`, altName.value || '');
                formData.append(`altbrand${i}`, altBrand.value || '');
                formData.append(`altbarcode${i}`, altBarcode.value.trim() || '');
            } else {
                // Always add the alternative product data, even if some fields don't exist
                // This ensures that any available data is sent to the backend
                if (altImage) {
                    const altImageFile = altImage.files[0];
                    if (altImageFile) {
                        formData.append(`altimg${i}`, altImageFile);
                    } else {
                        // If no new image is selected, use the existing image
                        const existingAltImage = altImage.dataset.existingImage;
                        if (existingAltImage) {
                            formData.append(`existing_altimg${i}`, existingAltImage);
                        }
                    }
                }
                
                formData.append(`altname${i}`, altName ? (altName.value || '') : '');
                formData.append(`altbrand${i}`, altBrand ? (altBrand.value || '') : '');
                formData.append(`altbarcode${i}`, altBarcode ? (altBarcode.value.trim() || '') : '');
            }
        }

        // Determine which endpoint to use based on action
        const endpoint = action === 'review' ? 'src/approve_product_request.php' : 'src/product_operations.php';

        // Send the request
        fetch(endpoint, {
            method: 'POST',
            body: formData
        })
        .then(response => {
            return response.json().then(data => {
                if (!response.ok || !data.success) {
                    showToast('Error: ' + (data?.message || 'Unknown error occurred'), 'error');
                    return Promise.reject('_handled'); // Pass a special value for handled errors
                }
                return data;
            });
        })
        .then(data => {
            if (!data) return;
            showToast(data.message, 'success');
            document.getElementById('product-modal').style.display = 'none';
            if (action === 'review') {
                loadProductRequests();
            } else {
                loadProducts();
            }
        })
        .catch(error => {
            if (error === '_handled') return; // Don't show another toast for handled errors
            console.error('Error:', error);
            showToast('An error occurred while processing your request', 'error');
        });
    }

    return false; // Prevent form submission
}

// Update handleDelete to use toast
function handleDelete(id) {
    if (!id) {
        showToast('Invalid product ID', 'error');
        return;
    }

    if (confirm('Are you sure you want to delete this product?')) {
        const formData = new FormData();
        formData.append('action', 'delete');
        formData.append('id', id);

        fetch('src/product_operations.php', {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                showToast(data.message, 'success');
                loadProducts();
            } else {
                showToast(data.message || 'Error deleting product', 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('An error occurred while deleting the product', 'error');
        });
    }
}

// Function to show image viewer
function showImageViewer(imageUrl, productName) {
    const modal = document.getElementById('image-viewer-modal');
    const image = document.getElementById('viewer-image');
    image.src = imageUrl;
    image.alt = productName;
    modal.style.display = 'block';
}

// Barcode Scanner Functions
let scannerRunning = false;
let codeReader = null;
window.currentBarcodeInputId = null; // Track which input to fill

function startScanner() {
    if (scannerRunning) return;
    
    const video = document.getElementById('video');
    codeReader = new ZXing.BrowserMultiFormatReader();
    
    codeReader.getVideoInputDevices()
        .then((videoInputDevices) => {
            let selectedDeviceId;
            // রিয়ার ক্যামেরা খুঁজে বের করার চেষ্টা করুন
            const rearCamera = videoInputDevices.find(device => 
                device.label.toLowerCase().includes('back') || 
                device.label.toLowerCase().includes('rear')
            );

            if (rearCamera) {
                selectedDeviceId = rearCamera.deviceId;
            } else if (videoInputDevices.length > 0) {
                // যদি রিয়ার ক্যামেরা না পাওয়া যায়, প্রথম উপলব্ধ ক্যামেরা ব্যবহার করুন
                selectedDeviceId = videoInputDevices[0].deviceId;
                console.warn('Rear camera not found, using default camera (which might be front camera).');
            } else {
                console.error('No video input devices found.');
                showToast('No camera found. Please ensure camera access is allowed.', 'error');
                return;
            }

            // ZXing লাইব্রেরিতে constraints সরাসরি পাঠানো যায় না, কিন্তু deviceId দিয়ে রিয়ার ক্যামেরা সিলেক্ট করা যায়
            codeReader.decodeFromVideoDevice(selectedDeviceId, video, (result, err) => {
                if (result) {
                    const code = result.getText();
                    // Fill the correct input field
                    const inputId = window.currentBarcodeInputId || 'productBarcode';
                    const barcodeInput = document.getElementById(inputId);
                    if (barcodeInput) {
                        barcodeInput.value = code;
                        // Validate the scanned barcode
                        const originalBarcode = document.getElementById('product-id').value;
                        checkBarcode(code, barcodeInput, originalBarcode);
                    }
                    stopScanner();
                    document.getElementById('barcode-scanner-modal').style.display = 'none';
                    window.currentBarcodeInputId = null; // Reset after scan
                }
                if (err && !(err instanceof ZXing.NotFoundException)) {
                    console.error(err);
                }
            });
            
            scannerRunning = true;
        })
        .catch((err) => {
            console.error('Error getting video input devices or starting scanner:', err);
            showToast('Failed to start camera. Please check camera permissions.', 'error');
        });
}

function stopScanner() {
    if (!scannerRunning || !codeReader) return;
    
    codeReader.reset();
    scannerRunning = false;
}

// Barcode validation function
function checkBarcode(barcode, inputElement, originalBarcode = '') {
    if (!barcode) {
        const container = inputElement.closest('.barcode-input');
        if (container) {
            container.classList.remove('valid', 'invalid');
            const feedback = container.querySelector('.barcode-feedback');
            if (feedback) feedback.remove();
        }
        updateSaveButtonState();
        return;
    }

    const formData = new FormData();
    formData.append('barcode', barcode);
    formData.append('original_barcode', originalBarcode);

    fetch('src/check_barcode.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        const container = inputElement.closest('.barcode-input');
        if (!container) return;

        if (data.exists) {
            container.classList.remove('valid');
            container.classList.add('invalid');
            const feedback = container.querySelector('.barcode-feedback') || document.createElement('div');
            feedback.className = 'barcode-feedback';
            feedback.textContent = 'Barcode already exists';
            if (!container.querySelector('.barcode-feedback')) {
                container.appendChild(feedback);
            }
        } else {
            container.classList.remove('invalid');
            container.classList.add('valid');
            const feedback = container.querySelector('.barcode-feedback') || document.createElement('div');
            feedback.className = 'barcode-feedback';
            feedback.textContent = 'Barcode available';
            if (!container.querySelector('.barcode-feedback')) {
                container.appendChild(feedback);
            }
        }
        updateSaveButtonState();
    })
    .catch(error => {
        console.error('Error checking barcode:', error);
        updateSaveButtonState();
    });
}

// Event Listeners
document.addEventListener('DOMContentLoaded', () => {
    // Save Product button
    const saveProductBtn = document.getElementById('save-product-btn');
    if (saveProductBtn) {
        saveProductBtn.addEventListener('click', (e) => {
            e.preventDefault();
            const form = document.getElementById('product-form');
            if (form.dataset.action === 'review') {
                handleReviewApprove(e);
            } else {
                handleProductFormSubmit();
            }
        });
    }

    // Cancel button
    const cancelBtn = document.getElementById('cancel-product-form');
    if (cancelBtn) {
        cancelBtn.addEventListener('click', () => {
            document.getElementById('product-modal').style.display = 'none';
        });
    }

    // Add New Product button
    const addNewProductBtn = document.getElementById('add-new-product-btn');
    if (addNewProductBtn) {
        addNewProductBtn.addEventListener('click', () => {
            showAddProductModal();
            loadCategories();
        });
    }

    // Edit buttons
    document.addEventListener('click', (e) => {
        if (e.target.closest('.edit-product-btn')) {
            const barcode = e.target.closest('.edit-product-btn').dataset.id;
            loadProductForEdit(barcode);
        }
    });

    // Delete buttons
    document.addEventListener('click', (e) => {
        if (e.target.closest('.delete-item-btn')) {
            const id = e.target.closest('.delete-item-btn').dataset.id;
            const isRequest = e.target.closest('.list-item').closest('#request-list-container') !== null;
            
            if (confirm('Are you sure you want to delete this item?')) {
                const formData = new FormData();
                formData.append('action', 'delete');
                formData.append('id', id);

                // Use different endpoints for products and requests
                const endpoint = isRequest ? 'src/delete_product_request.php' : 'src/product_operations.php';

                fetch(endpoint, {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        showToast(data.message, 'success');
                        if (isRequest) {
                            loadProductRequests();
                        } else {
                            loadProducts();
                        }
                    } else {
                        showToast(data.message || 'Error deleting item', 'error');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showToast('An error occurred while deleting the item', 'error');
                });
            }
        }
    });

    // Close modal
    const closeModalBtn = document.getElementById('close-product-modal');
    if (closeModalBtn) {
        closeModalBtn.addEventListener('click', () => {
            document.getElementById('product-modal').style.display = 'none';
        });
    }

    // Image type toggle
    document.querySelectorAll('input[name="productImageType"]').forEach(radio => {
        radio.addEventListener('change', (e) => {
            const isUrl = e.target.value === 'url';
            document.getElementById('productImageFile').style.display = isUrl ? 'none' : 'block';
            document.getElementById('productImageUrl').style.display = isUrl ? 'block' : 'none';
        });
    });

    // Load products when product list page is shown
    const productListLink = document.querySelector('[data-page="product-list"]');
    if (productListLink) {
        productListLink.addEventListener('click', (e) => {
            e.preventDefault();
            loadProducts();
        });
    }

    // Initial load if on product list page
    if (document.getElementById('product-list-page')?.classList.contains('active')) {
        loadProducts();
    }

    // Add click event listener for navigation
    document.querySelectorAll('.nav-link').forEach(link => {
        link.addEventListener('click', (e) => {
            e.preventDefault();
            const page = e.target.dataset.page;
            if (page === 'product-list') {
                loadProducts();
            }
        });
    });

    // Close image viewer
    const closeImageViewer = document.getElementById('close-image-viewer');
    if (closeImageViewer) {
        closeImageViewer.addEventListener('click', () => {
            document.getElementById('image-viewer-modal').style.display = 'none';
        });
    }

    // Close image viewer when clicking outside the image
    window.addEventListener('click', (e) => {
        const modal = document.getElementById('image-viewer-modal');
        if (e.target === modal) {
            modal.style.display = 'none';
        }
    });

    // Load categories when the page loads
    loadCategories();

    // Update subcategories when category changes
    const categorySelect = document.getElementById('productCategory');
    if (categorySelect) {
        categorySelect.addEventListener('change', (e) => {
            updateSubcategories(e.target.value);
        });
    }

    // Barcode Scanner Modal
    document.addEventListener('click', function(e) {
        const scanBtn = e.target.closest('.scan-barcode-btn');
        if (scanBtn) {
            // Find the nearest input[type=text] before the button
            let input = scanBtn.closest('.input-group')?.querySelector('input[type="text"]');
            if (!input) {
                // fallback: try previousElementSibling
                input = scanBtn.previousElementSibling;
            }
            if (input && input.id) {
                window.currentBarcodeInputId = input.id;
            } else {
                window.currentBarcodeInputId = 'productBarcode';
            }
            document.getElementById('barcode-scanner-modal').style.display = 'block';
            setTimeout(startScanner, 500);
        }
    });

    // Close Scanner Modal
    const closeScannerModal = document.getElementById('close-scanner-modal');
    if (closeScannerModal) {
        closeScannerModal.addEventListener('click', () => {
            stopScanner();
            document.getElementById('barcode-scanner-modal').style.display = 'none';
        });
    }

    // Stop Scanner Button
    const stopScanBtn = document.getElementById('stop-scan');
    if (stopScanBtn) {
        stopScanBtn.addEventListener('click', () => {
            stopScanner();
        });
    }

    // Close scanner when clicking outside
    window.addEventListener('click', (e) => {
        const modal = document.getElementById('barcode-scanner-modal');
        if (e.target === modal) {
            stopScanner();
            modal.style.display = 'none';
        }
    });

    // Setup barcode validation
    setupBarcodeValidation();

    // Setup product name validation
    setupProductNameValidation();

    // Settings form submission
    const settingsForm = document.getElementById('general-settings-form');
    if (settingsForm) {
        settingsForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            // Get form values
            const formData = new FormData();
            formData.append('new_username', document.getElementById('new-username').value);
            formData.append('current_password', document.getElementById('current-password').value);
            formData.append('new_password', document.getElementById('new-password').value);
            formData.append('confirm_password', document.getElementById('confirm-password').value);
            
            try {
                const response = await fetch('src/update_settings.php', {
                    method: 'POST',
                    body: formData
                });
                
                const data = await response.json();
                console.log('Response:', data); // Add this for debugging
                
                if (data.success) {
                    showToast(data.message, 'success');
                    // Clear password fields
                    document.getElementById('current-password').value = '';
                    document.getElementById('new-password').value = '';
                    document.getElementById('confirm-password').value = '';
                    document.getElementById('new-username').value = '';
                } else {
                    showToast(data.message || 'Failed to update settings', 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                showToast('An error occurred while updating settings', 'error');
            }
        });
    }

    // Image cleanup button handler
    const cleanupAllImagesBtn = document.getElementById('cleanup-all-images-btn');
    if (cleanupAllImagesBtn) {
        cleanupAllImagesBtn.addEventListener('click', async function() {
            if (!confirm('Are you sure you want to clean up all unused images? This action cannot be undone.')) {
                return;
            }

            try {
                // First clean up product images
                const productResponse = await fetch('src/cleanup_images.php');
                const productData = await productResponse.json();
                
                // Then clean up request images
                const requestResponse = await fetch('src/cleanup_request_images.php');
                const requestData = await requestResponse.json();
                
                // Show combined results
                const totalDeleted = (productData.deleted_count || 0) + (requestData.deleted_count || 0);
                const allErrors = [
                    ...(productData.errors || []),
                    ...(requestData.errors || [])
                ];
                
                if (productData.success && requestData.success) {
                    showToast(`Cleanup completed. Deleted ${totalDeleted} unused images in total.`, 'success');
                    if (allErrors.length > 0) {
                        console.warn('Some errors occurred during cleanup:', allErrors);
                    }
                    // Reload both lists to reflect changes
                    loadProducts();
                    loadProductRequests();
                } else {
                    const errorMessage = [
                        productData.message || 'Failed to clean up product images',
                        requestData.message || 'Failed to clean up request images'
                    ].filter(Boolean).join('. ');
                    showToast(errorMessage, 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                showToast('An error occurred during cleanup', 'error');
            }
        });
    }

    // Add this near your DOMContentLoaded or main script section
    const searchInput = document.getElementById('search-input');
    const searchButton = document.getElementById('search-button');
    const mobileSearchInput = document.getElementById('mobile-search-input');
    const mobileSearchButton = document.getElementById('mobile-search-execute-btn');

    function handleGlobalSearch(term) {
        if (document.getElementById('product-list-page')?.classList.contains('active')) {
            loadProducts(term);
        } else if (document.getElementById('product-requests-page')?.classList.contains('active')) {
            loadProductRequests(term);
        } else {
            showToast('Search is only available on Products and Requests pages.', 'warning');
        }
    }

    if (searchButton && searchInput) {
        searchButton.addEventListener('click', () => {
            handleGlobalSearch(searchInput.value.trim());
        });
        searchInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                handleGlobalSearch(searchInput.value.trim());
            }
        });
    }
    if (mobileSearchButton && mobileSearchInput) {
        mobileSearchButton.addEventListener('click', () => {
            handleGlobalSearch(mobileSearchInput.value.trim());
        });
        mobileSearchInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                handleGlobalSearch(mobileSearchInput.value.trim());
            }
        });
    }

    if (searchInput) {
        searchInput.addEventListener('input', () => {
            handleGlobalSearch(searchInput.value.trim());
        });
    }
    if (mobileSearchInput) {
        mobileSearchInput.addEventListener('input', () => {
            handleGlobalSearch(mobileSearchInput.value.trim());
        });
    }
});

// Add this to your existing JavaScript code
function loadProductRequests(searchTerm = '') {
    fetch('src/get_product_requests.php')
        .then(response => response.json())
        .then(data => {
            let requests = data.requests || [];
            if (searchTerm) {
                requests = requests.filter(request =>
                    (request.product_name || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
                    (request.product_brand || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
                    (request.barcode || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
                    (request.product_category || '').toLowerCase().includes(searchTerm.toLowerCase())
                );
            }
            const container = document.getElementById('request-list-container');
            container.innerHTML = '';
            if (requests.length === 0) {
                container.innerHTML = '<div class="no-requests">No pending requests</div>';
                return;
            }
            requests.forEach(request => {
                const requestHtml = `
                    <div class="list-item">
                        <div class="list-item-image">
                            ${request.product_image_url ? 
                                `<img src="uploads/requests/${request.product_image_url.startsWith('http') ? request.product_image_url : request.product_image_url}" alt="${request.product_name}" class="product-image" onclick="showImageViewer('${request.product_image_url.startsWith('http') ? request.product_image_url : 'uploads/requests/' + request.product_image_url}', '${request.product_name}')">` : 
                                `<i class="fas fa-image"></i>`}
                        </div>
                        <div class="list-item-details">
                            <h4>${request.product_name} (${request.barcode})</h4>
                            <p><strong>Brand:</strong> ${request.product_brand}</p>
                            <p><strong>Category:</strong> ${request.product_category}</p>
                            <p><strong>Sub Category:</strong> ${request.sub_category}</p>
                        </div>
                        <div class="list-item-actions">
                            <button class="btn btn-success review-request-btn" data-id="${request.id}">
                                <i class="fas fa-search-plus"></i> Review
                            </button>
                            <button class="btn btn-danger delete-item-btn" data-id="${request.id}">
                                <i class="fas fa-trash"></i> Delete
                            </button>
                        </div>
                    </div>
                `;
                container.innerHTML += requestHtml;
            });
        })
        .catch(error => {
            console.error('Error loading requests:', error);
            const container = document.getElementById('request-list-container');
            container.innerHTML = '<div class="error-message">Error loading requests</div>';
        });
}

function handleReviewApprove(e) {
    e.preventDefault();
    const form = document.getElementById('product-form');
    const requestId = form.dataset.requestId;
    
    if (!requestId) {
        showToast('Invalid request ID', 'error');
        return;
    }

    const formData = new FormData();
    formData.append('action', 'approve');
    formData.append('request_id', requestId);

    // Add main product data
    const imageFile = document.getElementById('productImageFile').files[0];
    if (imageFile) {
        formData.append('productImageFile', imageFile);
    } else {
        // If no new image is selected, use the existing image from the request
        const existingImage = document.getElementById('productImageFile').dataset.existingImage;
        if (existingImage) {
            formData.append('existing_image', existingImage);
        }
    }

    formData.append('name', document.getElementById('productName').value);
    formData.append('brand', document.getElementById('productBrand').value);
    formData.append('category', document.getElementById('productCategory').value);
    formData.append('subcategory', document.getElementById('productSubCategory').value);
    formData.append('barcode', document.getElementById('productBarcode').value.trim());
    formData.append('moreinfo', document.getElementById('productMoreInfo').value);

    // Add alternative products data
    for (let i = 1; i <= 3; i++) {
        const altImage = document.getElementById(`altIF${i}`);
        const altName = document.getElementById(`altN${i}`);
        const altBrand = document.getElementById(`altB${i}`);
        const altBarcode = document.getElementById(`altBC${i}`);

        if (altImage && altName && altBrand && altBarcode) {
            const altImageFile = altImage.files[0];
            if (altImageFile) {
                formData.append(`altimg${i}`, altImageFile);
            } else {
                // If no new image is selected, use the existing image
                const existingAltImage = altImage.dataset.existingImage;
                if (existingAltImage) {
                    formData.append(`existing_altimg${i}`, existingAltImage);
                }
            }
            
            formData.append(`altname${i}`, altName.value || '');
            formData.append(`altbrand${i}`, altBrand.value || '');
            formData.append(`altbarcode${i}`, altBarcode.value.trim() || '');
        } else {
            // Always add the alternative product data, even if some fields don't exist
            // This ensures that any available data is sent to the backend
            if (altImage) {
                const altImageFile = altImage.files[0];
                if (altImageFile) {
                    formData.append(`altimg${i}`, altImageFile);
                } else {
                    // If no new image is selected, use the existing image
                    const existingAltImage = altImage.dataset.existingImage;
                    if (existingAltImage) {
                        formData.append(`existing_altimg${i}`, existingAltImage);
                    }
                }
            }
            
            formData.append(`altname${i}`, altName ? (altName.value || '') : '');
            formData.append(`altbrand${i}`, altBrand ? (altBrand.value || '') : '');
            formData.append(`altbarcode${i}`, altBarcode ? (altBarcode.value.trim() || '') : '');
        }
    }

    fetch('src/approve_product_request.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast(data.message, 'success');
            document.getElementById('product-modal').style.display = 'none';
            loadProductRequests();
        } else {
            showToast('Error: ' + (data.message || 'Unknown error occurred'), 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('An error occurred while processing your request', 'error');
    });
}

function loadRequestForReview(requestId) {
    const form = document.getElementById('product-form');
    if (!form) {
        console.error('Product form not found');
        showToast('Error: Product form not found', 'error');
        return;
    }

    form.dataset.action = 'review';
    form.dataset.requestId = requestId;

    fetch('src/get_product_requests.php')
        .then(response => response.json())
        .then(data => {
            if (!data || !data.requests) {
                throw new Error('Invalid response data');
            }

            const request = data.requests.find(r => parseInt(r.id) === parseInt(requestId));
            if (!request) {
                throw new Error('Request not found');
            }

            // Get all required elements
            const elements = {
                productName: document.getElementById('productName'),
                productBrand: document.getElementById('productBrand'),
                productBarcode: document.getElementById('productBarcode'),
                productMoreInfo: document.getElementById('productMoreInfo'),
                productImageFile: document.getElementById('productImageFile'),
                productCategory: document.getElementById('productCategory'),
                productSubCategory: document.getElementById('productSubCategory'),
                modalTitle: document.getElementById('modal-title'),
                saveButton: document.getElementById('save-product-btn')
            };

            // Check if all required elements exist
            const missingElements = Object.entries(elements)
                .filter(([key, element]) => !element)
                .map(([key]) => key);

            if (missingElements.length > 0) {
                throw new Error(`Missing required elements: ${missingElements.join(', ')}`);
            }

            // Set form values
            elements.productName.value = request.product_name || '';
            elements.productBrand.value = request.product_brand || '';
            elements.productBarcode.value = request.barcode || '';
            elements.productMoreInfo.value = request.more_info || '';

            // Handle categories
            const categories = request.categories ? request.categories.split(',') : [];
            elements.productCategory.value = categories[0] || '';
            elements.productSubCategory.value = categories[1] || '';

            // Update modal title and save button
            elements.modalTitle.textContent = 'Review Product Request';
            elements.saveButton.textContent = 'Approve';
            elements.saveButton.classList.add('approve-button');
            elements.saveButton.classList.remove('save-button');

            // Show modal
            const modal = document.getElementById('product-modal');
            if (modal) {
                modal.style.display = 'block';
            } else {
                throw new Error('Product modal not found');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast(`Error loading product request: ${error.message}`, 'error');
        });
}

// Add event listener for product requests page
document.addEventListener('DOMContentLoaded', () => {
    // ... existing event listeners ...

    // Load requests when product requests page is shown
    const productRequestsLink = document.querySelector('[data-page="product-requests"]');
    if (productRequestsLink) {
        productRequestsLink.addEventListener('click', (e) => {
            e.preventDefault();
            loadProductRequests();
        });
    }

    // Initial load if on product requests page
    if (document.getElementById('product-requests-page')?.classList.contains('active')) {
        loadProductRequests();
    }

    // Refresh List button click handler
    const refreshRequestsBtn = document.getElementById('refresh-requests-btn');
    if (refreshRequestsBtn) {
        refreshRequestsBtn.addEventListener('click', () => {
            loadProductRequests();
            showToast('Requests list refreshed', 'success');
        });
    }

    // Review request button click handler
    document.addEventListener('click', (e) => {
        const reviewBtn = e.target.closest('.review-request-btn');
        if (reviewBtn) {
            const requestId = reviewBtn.dataset.id;
            loadRequestForReview(requestId);
        }
    });
});
    </script>
    <style>
        /* Add these styles to your existing CSS */
        .product-image {
            cursor: pointer;
            transition: transform 0.2s;
            max-width: 100%;
            height: auto;
        }

        .product-image:hover {
            transform: scale(1.05);
        }

        .image-viewer {
            max-width: 90%;
            max-height: 90vh;
            margin: auto;
            padding: 0;
            background: transparent;
            box-shadow: none;
        }

        .image-viewer img {
            max-width: 100%;
            max-height: 90vh;
            object-fit: contain;
            display: block;
            margin: auto;
        }

        .image-viewer .close-modal {
            position: absolute;
            right: 15px;
            top: 10px;
            color: white;
            font-size: 30px;
            font-weight: bold;
            cursor: pointer;
            text-shadow: 0 0 3px rgba(0,0,0,0.5);
        }

        #image-viewer-modal {
            background-color: rgba(0, 0, 0, 0.9);
        }

        #image-viewer-modal .modal-content {
            background: transparent;
            border: none;
            box-shadow: none;
        }

        /* Scanner Styles */
        #interactive.viewport {
            position: relative;
            width: 100%;
            height: 300px;
            background-color: #000;
            overflow: hidden;
        }

        #interactive.viewport video {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .scanner-controls {
            margin-top: 1rem;
            text-align: center;
        }

        #barcode-scanner-modal .modal-content {
            max-width: 600px;
        }

        #barcode-scanner-modal .modal-body {
            padding: 1rem;
        }

        /* Add validation styles */
        .barcode-input {
            position: relative;
        }

        .barcode-input.valid input {
            border-color: #28a745;
        }

        .barcode-input.invalid input {
            border-color: #dc3545;
        }

        .barcode-feedback {
            position: absolute;
            top: 100%;
            font-size: 14px;
        }

        .barcode-input.valid .barcode-feedback {
            color: #28a745;
        }

        .barcode-input.invalid .barcode-feedback {
            color: #dc3545;
        }

        /* Add product name validation styles */
        .product-name-input {
            position: relative;
        }

        .product-name-input.valid input {
            border-color: #28a745;
        }

        .product-name-input.invalid input {
            border-color: #dc3545;
        }

        .product-name-feedback {
            position: absolute;
            right: 10px;
            top: 100%;
            font-size: 14px;
        }

        .product-name-input.valid .product-name-feedback {
            color: #28a745;
        }

        .product-name-input.invalid .product-name-feedback {
            color: #dc3545;
        }

        /* Toast Notification Styles */
        .toast-container {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 9999;
        }

        .toast {
            background: #333;
            color: white;
            padding: 12px 24px;
            border-radius: 4px;
            margin-bottom: 10px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            display: flex;
            align-items: center;
            justify-content: space-between;
            min-width: 250px;
            max-width: 350px;
            animation: slideIn 0.3s ease-in-out;
        }

        .toast.success {
            background: #28a745;
        }

        .toast.error {
            background: #dc3545;
        }

        .toast.warning {
            background: #ffc107;
            color: #000;
        }

        .toast-message {
            margin-right: 10px;
        }

        .toast-close {
            background: none;
            border: none;
            color: inherit;
            cursor: pointer;
            font-size: 20px;
            padding: 0;
            opacity: 0.7;
        }

        .toast-close:hover {
            opacity: 1;
        }

        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

        @keyframes fadeOut {
            from {
                transform: translateX(0);
                opacity: 1;
            }
            to {
                transform: translateX(100%);
                opacity: 0;
            }
        }
    </style>

    <!-- Add Toast Container -->
    <div class="toast-container" id="toast-container"></div>

</body>
</html>