// API URL
const API_URL = 'http://localhost:5000/api';

// Global variables
let currentPage = window.location.pathname.split('/').pop() || 'index.html';
let currentData = [];
let reportData = {};

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    // Initialize based on current page
    initPage();
    
    // Setup theme toggle
    const themeToggle = document.getElementById('theme-toggle');
    if (themeToggle) {
        themeToggle.addEventListener('change', toggleTheme);
        // Set initial theme
        if (localStorage.getItem('theme') === 'dark') {
            document.body.classList.add('dark-theme');
            themeToggle.checked = true;
        }
    }
    
    // Setup logout button
    const logoutBtn = document.querySelector('.btn-logout');
    if (logoutBtn) {
        logoutBtn.addEventListener('click', function() {
            localStorage.removeItem('token');
            localStorage.removeItem('user');
            window.location.href = '../pages/login.html';
        });
    }
    
    // Billing page functions
async function loadBilling() {
    try {
        // For testing without backend
        const mockCustomers = [
            { _id: '1', name: 'John Doe', phone: '555-123-4567', email: 'john@example.com', address: '123 Main St, City' },
            { _id: '2', name: 'Jane Smith', phone: '555-987-6543', email: 'jane@example.com', address: '456 Oak Ave, Town' },
            { _id: '3', name: 'Robert Johnson', phone: '555-456-7890', email: 'robert@example.com', address: '789 Pine Rd, Village' }
        ];
        
        const mockProducts = [
            { _id: '1', name: 'Laptop', category: 'Electronics', price: 999.99, stock: 15 },
            { _id: '2', name: 'Smartphone', category: 'Electronics', price: 499.99, stock: 25 },
            { _id: '3', name: 'Desk Chair', category: 'Furniture', price: 149.99, stock: 8 }
        ];
        
        const mockBills = [
            { _id: 'B001', customerId: '1', customerName: 'John Doe', date: '2023-06-15', total: 1499.98, items: [
                { productId: '1', name: 'Laptop', price: 999.99, quantity: 1, total: 999.99 },
                { productId: '2', name: 'Smartphone', price: 499.99, quantity: 1, total: 499.99 }
            ]},
            { _id: 'B002', customerId: '2', customerName: 'Jane Smith', date: '2023-06-16', total: 649.98, items: [
                { productId: '2', name: 'Smartphone', price: 499.99, quantity: 1, total: 499.99 },
                { productId: '3', name: 'Desk Chair', price: 149.99, quantity: 1, total: 149.99 }
            ]}
        ];
        
        // Store data for use in billing functions
        window.billingData = {
            customers: mockCustomers,
            products: mockProducts,
            bills: mockBills,
            currentBillItems: []
        };
        
        // Load customers into select dropdown
        loadCustomersForBilling(mockCustomers);
        
        // Load recent bills
        renderBills(mockBills);
        
        // Setup event listeners
        setupBillingEventListeners();
        
    } catch (error) {
        console.error('Error loading billing data:', error);
    }
}

function loadCustomersForBilling(customers) {
    const customerSelect = document.getElementById('customer-select');
    if (!customerSelect) return;
    
    // Clear existing options except the first one
    while (customerSelect.options.length > 1) {
        customerSelect.remove(1);
    }
    
    // Add customer options
    customers.forEach(customer => {
        const option = document.createElement('option');
        option.value = customer._id;
        option.textContent = customer.name;
        customerSelect.appendChild(option);
    });
}

function setupBillingEventListeners() {
    // New bill button
    const newBillBtn = document.getElementById('new-bill-btn');
    if (newBillBtn) {
        newBillBtn.addEventListener('click', () => {
            resetBillingForm();
            document.querySelector('.bill-form-container').style.display = 'block';
        });
    }
    
    // Cancel bill button
    const cancelBillBtn = document.getElementById('cancel-bill');
    if (cancelBillBtn) {
        cancelBillBtn.addEventListener('click', () => {
            resetBillingForm();
            document.querySelector('.bill-form-container').style.display = 'none';
        });
    }
    
    // Add new customer button
    const addNewCustomerBtn = document.getElementById('add-new-customer-btn');
    if (addNewCustomerBtn) {
        addNewCustomerBtn.addEventListener('click', () => {
            const modal = document.getElementById('customer-modal');
            if (modal) modal.style.display = 'block';
        });
    }
    
    // Close customer modal
    const closeCustomerModal = document.querySelector('#customer-modal .close-modal');
    if (closeCustomerModal) {
        closeCustomerModal.addEventListener('click', () => {
            document.getElementById('customer-modal').style.display = 'none';
        });
    }
    
    // Customer form submit
    const customerForm = document.getElementById('customer-form');
    if (customerForm) {
        customerForm.addEventListener('submit', handleBillingCustomerSubmit);
    }
    
    // Product search
    const productSearch = document.getElementById('product-search-billing');
    if (productSearch) {
        productSearch.addEventListener('input', handleProductSearch);
    }
    
    // Tax and discount inputs
    const taxRate = document.getElementById('tax-rate');
    const discount = document.getElementById('discount');
    if (taxRate) taxRate.addEventListener('input', updateBillTotals);
    if (discount) discount.addEventListener('input', updateBillTotals);
    
    // Billing form submit
    const billingForm = document.getElementById('billing-form');
    if (billingForm) {
        billingForm.addEventListener('submit', handleBillingSubmit);
    }
    
    // Bill details modal close
    const closeBillDetailsBtn = document.getElementById('close-bill-details');
    if (closeBillDetailsBtn) {
        closeBillDetailsBtn.addEventListener('click', () => {
            document.getElementById('bill-details-modal').style.display = 'none';
        });
    }
    
    // Print bill button
    const printBillBtn = document.getElementById('print-bill');
    if (printBillBtn) {
        printBillBtn.addEventListener('click', () => {
            window.print();
        });
    }
}

function handleProductSearch(e) {
    const searchTerm = e.target.value.toLowerCase();
    const searchResults = document.getElementById('product-search-results');
    
    if (!searchTerm) {
        searchResults.innerHTML = '';
        searchResults.style.display = 'none';
        return;
    }
    
    const filteredProducts = window.billingData.products.filter(product => 
        product.name.toLowerCase().includes(searchTerm) && product.stock > 0
    );
    
    if (filteredProducts.length === 0) {
        searchResults.innerHTML = '<p>No products found</p>';
    } else {
        searchResults.innerHTML = '';
        filteredProducts.forEach(product => {
            const productItem = document.createElement('div');
            productItem.className = 'search-result-item';
            productItem.innerHTML = `
                <span>${product.name} - $${product.price.toFixed(2)}</span>
                <span>Stock: ${product.stock}</span>
            `;
            productItem.addEventListener('click', () => addProductToBill(product));
            searchResults.appendChild(productItem);
        });
    }
    
    searchResults.style.display = 'block';
}

function addProductToBill(product) {
    // Check if product already in bill
    const existingItem = window.billingData.currentBillItems.find(item => item.productId === product._id);
    
    if (existingItem) {
        // Increment quantity if already in bill
        existingItem.quantity += 1;
        existingItem.total = existingItem.price * existingItem.quantity;
    } else {
        // Add new item to bill
        window.billingData.currentBillItems.push({
            productId: product._id,
            name: product.name,
            price: product.price,
            quantity: 1,
            total: product.price
        });
    }
    
    // Update bill items table
    renderBillItems();
    
    // Update totals
    updateBillTotals();
    
    // Clear search
    document.getElementById('product-search-billing').value = '';
    document.getElementById('product-search-results').style.display = 'none';
}

function renderBillItems() {
    const billItemsTable = document.getElementById('bill-items-table');
    if (!billItemsTable) return;
    
    const tbody = billItemsTable.querySelector('tbody');
    tbody.innerHTML = '';
    
    if (window.billingData.currentBillItems.length === 0) {
        tbody.innerHTML = '<tr><td colspan="5" class="text-center">No items added</td></tr>';
        return;
    }
    
    window.billingData.currentBillItems.forEach((item, index) => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${item.name}</td>
            <td>$${item.price.toFixed(2)}</td>
            <td>
                <input type="number" min="1" value="${item.quantity}" class="quantity-input" data-index="${index}">
            </td>
            <td>$${item.total.toFixed(2)}</td>
            <td>
                <button class="btn-delete" data-index="${index}">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        `;
        tbody.appendChild(tr);
    });
    
    // Add event listeners to quantity inputs
    document.querySelectorAll('.quantity-input').forEach(input => {
        input.addEventListener('change', (e) => {
            const index = parseInt(e.target.dataset.index);
            const quantity = parseInt(e.target.value);
            
            if (quantity < 1) {
                e.target.value = 1;
                return;
            }
            
            window.billingData.currentBillItems[index].quantity = quantity;
            window.billingData.currentBillItems[index].total = 
                window.billingData.currentBillItems[index].price * quantity;
            
            renderBillItems();
            updateBillTotals();
        });
    });
    
    // Add event listeners to delete buttons
    document.querySelectorAll('.btn-delete').forEach(btn => {
        btn.addEventListener('click', () => {
            const index = parseInt(btn.dataset.index);
            window.billingData.currentBillItems.splice(index, 1);
            renderBillItems();
            updateBillTotals();
        });
    });
}

function updateBillTotals() {
    const subtotalElem = document.getElementById('subtotal');
    const taxAmountElem = document.getElementById('tax-amount');
    const totalAmountElem = document.getElementById('total-amount');
    const taxRateInput = document.getElementById('tax-rate');
    const discountInput = document.getElementById('discount');
    
    // Calculate subtotal
    const subtotal = window.billingData.currentBillItems.reduce((sum, item) => sum + item.total, 0);
    
    // Get tax rate and discount
    const taxRate = parseFloat(taxRateInput.value) || 0;
    const discount = parseFloat(discountInput.value) || 0;
    
    // Calculate tax amount
    const taxAmount = subtotal * (taxRate / 100);
    
    // Calculate total
    const total = subtotal + taxAmount - discount;
    
    // Update display
    subtotalElem.textContent = `$${subtotal.toFixed(2)}`;
    taxAmountElem.textContent = `$${taxAmount.toFixed(2)}`;
    totalAmountElem.textContent = `$${total.toFixed(2)}`;
}

function resetBillingForm() {
    // Reset form fields
    document.getElementById('customer-select').value = '';
    document.getElementById('tax-rate').value = '0';
    document.getElementById('discount').value = '0';
    
    // Clear bill items
    window.billingData.currentBillItems = [];
    renderBillItems();
    
    // Reset totals
    updateBillTotals();
}

async function handleBillingCustomerSubmit(e) {
    e.preventDefault();
    
    const customerData = {
        name: document.getElementById('customer-name').value,
        phone: document.getElementById('customer-phone').value,
        email: document.getElementById('customer-email').value,
        address: document.getElementById('customer-address').value
    };
    
    try {
        // For testing without backend
        const newCustomer = {
            _id: Date.now().toString(),
            ...customerData
        };
        
        // Add to customers list
        window.billingData.customers.push(newCustomer);
        
        // Add to customer select dropdown
        loadCustomersForBilling(window.billingData.customers);
        
        // Select the new customer
        document.getElementById('customer-select').value = newCustomer._id;
        
        // Close modal
        document.getElementById('customer-modal').style.display = 'none';
        
    } catch (error) {
        console.error('Error adding customer:', error);
    }
}

async function handleBillingSubmit(e) {
    e.preventDefault();
    
    const customerId = document.getElementById('customer-select').value;
    if (!customerId) {
        alert('Please select a customer');
        return;
    }
    
    if (window.billingData.currentBillItems.length === 0) {
        alert('Please add at least one product to the bill');
        return;
    }
    
    try {
        const customer = window.billingData.customers.find(c => c._id === customerId);
        const taxRate = parseFloat(document.getElementById('tax-rate').value) || 0;
        const discount = parseFloat(document.getElementById('discount').value) || 0;
        
        // Calculate totals
        const subtotal = window.billingData.currentBillItems.reduce((sum, item) => sum + item.total, 0);
        const taxAmount = subtotal * (taxRate / 100);
        const total = subtotal + taxAmount - discount;
        
        // Create bill object
        const newBill = {
            _id: `B${Date.now().toString().slice(-4)}`,
            customerId,
            customerName: customer.name,
            date: new Date().toISOString().split('T')[0],
            subtotal,
            taxRate,
            taxAmount,
            discount,
            total,
            items: [...window.billingData.currentBillItems]
        };
        
        // Add to bills list
        window.billingData.bills.unshift(newBill);
        
        // Render bills
        renderBills(window.billingData.bills);
        
        // Show bill details
        showBillDetails(newBill);
        
        // Reset form and hide it
        resetBillingForm();
        document.querySelector('.bill-form-container').style.display = 'none';
        
    } catch (error) {
        console.error('Error generating bill:', error);
    }
}

function renderBills(bills) {
    const billsTable = document.getElementById('bills-table');
    if (!billsTable) return;
    
    const tbody = billsTable.querySelector('tbody');
    tbody.innerHTML = '';
    
    if (bills.length === 0) {
        tbody.innerHTML = '<tr><td colspan="5" class="text-center">No bills found</td></tr>';
        return;
    }
    
    bills.forEach(bill => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${bill._id}</td>
            <td>${bill.customerName}</td>
            <td>${bill.date}</td>
            <td>$${bill.total.toFixed(2)}</td>
            <td>
                <button class="btn-view" data-id="${bill._id}">
                    <i class="fas fa-eye"></i>
                </button>
                <button class="btn-print" data-id="${bill._id}">
                    <i class="fas fa-print"></i>
                </button>
            </td>
        `;
        tbody.appendChild(tr);
    });
    
    // Add event listeners to view buttons
    document.querySelectorAll('.btn-view').forEach(btn => {
        btn.addEventListener('click', () => {
            const billId = btn.dataset.id;
            const bill = window.billingData.bills.find(b => b._id === billId);
            if (bill) {
                showBillDetails(bill);
            }
        });
    });
    
    // Add event listeners to print buttons
    document.querySelectorAll('.btn-print').forEach(btn => {
        btn.addEventListener('click', () => {
            const billId = btn.dataset.id;
            const bill = window.billingData.bills.find(b => b._id === billId);
            if (bill) {
                showBillDetails(bill);
                setTimeout(() => {
                    window.print();
                }, 500);
            }
        });
    });
}

function showBillDetails(bill) {
    const modal = document.getElementById('bill-details-modal');
    const content = document.getElementById('bill-details-content');
    
    content.innerHTML = `
        <div class="bill-header">
            <div class="bill-company">
                <h2>BillStock</h2>
                <p>123 Business Street</p>
                <p>City, State 12345</p>
                <p>Phone: (555) 123-4567</p>
            </div>
            <div class="bill-info">
                <h3>INVOICE</h3>
                <p><strong>Invoice #:</strong> ${bill._id}</p>
                <p><strong>Date:</strong> ${bill.date}</p>
            </div>
        </div>
        
        <div class="bill-customer">
            <h3>Bill To:</h3>
            <p><strong>${bill.customerName}</strong></p>
        </div>
        
        <table class="bill-items-table">
            <thead>
                <tr>
                    <th>Item</th>
                    <th>Price</th>
                    <th>Quantity</th>
                    <th>Total</th>
                </tr>
            </thead>
            <tbody>
                ${bill.items.map(item => `
                    <tr>
                        <td>${item.name}</td>
                        <td>$${item.price.toFixed(2)}</td>
                        <td>${item.quantity}</td>
                        <td>$${item.total.toFixed(2)}</td>
                    </tr>
                `).join('')}
            </tbody>
        </table>
        
        <div class="bill-summary">
            <div class="summary-row">
                <span>Subtotal:</span>
                <span>$${bill.subtotal.toFixed(2)}</span>
            </div>
            <div class="summary-row">
                <span>Tax (${bill.taxRate}%):</span>
                <span>$${bill.taxAmount.toFixed(2)}</span>
            </div>
            <div class="summary-row">
                <span>Discount:</span>
                <span>$${bill.discount.toFixed(2)}</span>
            </div>
            <div class="summary-row total">
                <span>Total:</span>
                <span>$${bill.total.toFixed(2)}</span>
            </div>
        </div>
        
        <div class="bill-footer">
            <p>Thank you for your business!</p>
        </div>
    `;
    
    modal.style.display = 'block';
}

// Setup search functionality
    setupSearch();
    
    // Setup theme toggle
    const themeToggle = document.getElementById('theme-toggle');
    if (themeToggle) {
        themeToggle.addEventListener('click', toggleTheme);
        
        // Set initial theme
        const currentTheme = localStorage.getItem('theme') || 'light';
        document.body.classList.add(currentTheme);
        themeToggle.innerHTML = currentTheme === 'light' 
            ? '<i class="fas fa-moon"></i>' 
            : '<i class="fas fa-sun"></i>';
    }
    
    // Setup logout button
    const logoutBtn = document.getElementById('logout-btn');
    if (logoutBtn) {
        logoutBtn.addEventListener('click', function() {
            localStorage.removeItem('token');
            localStorage.removeItem('user');
            window.location.href = 'pages/login.html';
        });
    }
});

// Initialize page based on current URL
function initPage() {
    switch(currentPage) {
        case 'index.html':
            loadDashboard();
            break;
        case 'products.html':
            loadProducts();
            setupProductModal();
            break;
        case 'customers.html':
            loadCustomers();
            break;
        case 'billing.html':
            loadBilling();
            break;
        case 'reports.html':
            loadReports();
            setupReportEventListeners();
            break;
    }
}

// Reports page functions
async function loadReports() {
    try {
        // For testing without backend
        // Generate mock data for reports
        const mockSalesData = {
            totalSales: 2149.96,
            totalBills: 2,
            avgBillValue: 1074.98,
            salesTrend: [
                { date: '2023-06-10', amount: 850.50 },
                { date: '2023-06-11', amount: 425.75 },
                { date: '2023-06-12', amount: 0 },
                { date: '2023-06-13', amount: 1250.25 },
                { date: '2023-06-14', amount: 750.80 },
                { date: '2023-06-15', amount: 1499.98 },
                { date: '2023-06-16', amount: 649.98 }
            ]
        };

        const mockProductData = {
            totalProducts: 5,
            lowStockCount: 1,
            outOfStock: 0,
            lowStockItems: [
                { _id: '3', name: 'Desk Chair', category: 'Furniture', stock: 8, status: 'Low Stock' }
            ],
            topSellingProducts: [
                { name: 'Laptop', sales: 1999.98, percentage: 45 },
                { name: 'Smartphone', sales: 999.98, percentage: 30 },
                { name: 'Desk Chair', sales: 149.99, percentage: 25 }
            ]
        };

        const mockCustomerData = {
            totalCustomers: 3,
            newCustomers: 1,
            repeatCustomers: 2,
            topCustomers: [
                { name: 'John Doe', purchases: 1, totalAmount: 1499.98, lastPurchase: '2023-06-15' },
                { name: 'Jane Smith', purchases: 1, totalAmount: 649.98, lastPurchase: '2023-06-16' }
            ]
        };

        // Store data for use in report functions
        reportData = {
            sales: mockSalesData,
            products: mockProductData,
            customers: mockCustomerData
        };

        // Update report UI with data
        updateReportUI(reportData);
        
    } catch (error) {
        console.error('Error loading report data:', error);
    }
}

function updateReportUI(data) {
    // Update Sales Summary section
    document.getElementById('total-sales').textContent = `$${data.sales.totalSales.toFixed(2)}`;
    document.getElementById('total-bills').textContent = data.sales.totalBills;
    document.getElementById('avg-bill-value').textContent = `$${data.sales.avgBillValue.toFixed(2)}`;
    
    // Update Product Analysis section
    document.getElementById('total-products').textContent = data.products.totalProducts;
    document.getElementById('low-stock-count').textContent = data.products.lowStockCount;
    document.getElementById('out-of-stock').textContent = data.products.outOfStock;
    
    // Update Customer Insights section
    document.getElementById('total-customers').textContent = data.customers.totalCustomers;
    document.getElementById('new-customers').textContent = data.customers.newCustomers;
    document.getElementById('repeat-customers').textContent = data.customers.repeatCustomers;
    
    // Render low stock table
    renderLowStockTable(data.products.lowStockItems);
    
    // Render top customers table
    renderTopCustomersTable(data.customers.topCustomers);
    
    // Render charts if Chart.js is available
    if (typeof Chart !== 'undefined') {
        renderSalesChart(data.sales.salesTrend);
        renderTopProductsChart(data.products.topSellingProducts);
    } else {
        console.log('Chart.js not available. Charts will not be rendered.');
    }
}

function renderLowStockTable(items) {
    const tableBody = document.querySelector('#low-stock-table tbody');
    if (!tableBody) return;
    
    tableBody.innerHTML = '';
    
    if (items.length === 0) {
        const row = document.createElement('tr');
        row.innerHTML = '<td colspan="5" class="text-center">No low stock items</td>';
        tableBody.appendChild(row);
        return;
    }
    
    items.forEach(item => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${item.name}</td>
            <td>${item.category}</td>
            <td>${item.stock}</td>
            <td><span class="status-badge low-stock">${item.status}</span></td>
            <td><button class="btn-small" onclick="reorderProduct('${item._id}')">Reorder</button></td>
        `;
        tableBody.appendChild(row);
    });
}

function renderTopCustomersTable(customers) {
    const tableBody = document.querySelector('#top-customers-table tbody');
    if (!tableBody) return;
    
    tableBody.innerHTML = '';
    
    if (customers.length === 0) {
        const row = document.createElement('tr');
        row.innerHTML = '<td colspan="4" class="text-center">No customer data available</td>';
        tableBody.appendChild(row);
        return;
    }
    
    customers.forEach(customer => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${customer.name}</td>
            <td>${customer.purchases}</td>
            <td>$${customer.totalAmount.toFixed(2)}</td>
            <td>${customer.lastPurchase}</td>
        `;
        tableBody.appendChild(row);
    });
}

function setupReportEventListeners() {
    // Date filter and generate report button
    const generateReportBtn = document.getElementById('generate-report-btn');
    if (generateReportBtn) {
        generateReportBtn.addEventListener('click', generateReport);
    }
    
    // Export buttons
    const exportSalesPdfBtn = document.getElementById('export-sales-pdf');
    const exportInventoryPdfBtn = document.getElementById('export-inventory-pdf');
    const exportCustomersPdfBtn = document.getElementById('export-customers-pdf');
    
    if (exportSalesPdfBtn) exportSalesPdfBtn.addEventListener('click', () => exportReportPdf('sales'));
    if (exportInventoryPdfBtn) exportInventoryPdfBtn.addEventListener('click', () => exportReportPdf('inventory'));
    if (exportCustomersPdfBtn) exportCustomersPdfBtn.addEventListener('click', () => exportReportPdf('customers'));
}

function generateReport() {
    const dateFrom = document.getElementById('date-from').value;
    const dateTo = document.getElementById('date-to').value;
    
    if (!dateFrom || !dateTo) {
        alert('Please select both start and end dates');
        return;
    }
    
    // In a real app, we would fetch data for the selected date range
    // For now, we'll just show a message and use our mock data
    alert(`Generating report for period: ${dateFrom} to ${dateTo}`);
    
    // Update UI with current mock data
    updateReportUI(reportData);
}

function exportReportPdf(reportType) {
    // In a real app, this would generate and download a PDF
    // For now, we'll just show a message
    alert(`Exporting ${reportType} report as PDF...`);
    
    // Simulate download delay
    setTimeout(() => {
        alert(`${reportType.charAt(0).toUpperCase() + reportType.slice(1)} report has been downloaded.`);
    }, 1500);
}

function renderSalesChart(salesData) {
    const ctx = document.getElementById('sales-chart');
    if (!ctx) return;
    
    // Clear placeholder if it exists
    const placeholder = ctx.querySelector('.chart-placeholder');
    if (placeholder) placeholder.remove();
    
    // Extract dates and amounts for the chart
    const dates = salesData.map(item => item.date);
    const amounts = salesData.map(item => item.amount);
    
    // Create chart
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: dates,
            datasets: [{
                label: 'Sales Amount',
                data: amounts,
                borderColor: '#4CAF50',
                backgroundColor: 'rgba(76, 175, 80, 0.1)',
                tension: 0.4,
                fill: true
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return '$' + value;
                        }
                    }
                }
            }
        }
    });
}

function renderTopProductsChart(productsData) {
    const ctx = document.getElementById('top-products-chart');
    if (!ctx) return;
    
    // Clear placeholder if it exists
    const placeholder = ctx.querySelector('.chart-placeholder');
    if (placeholder) placeholder.remove();
    
    // Extract product names and percentages for the chart
    const names = productsData.map(item => item.name);
    const percentages = productsData.map(item => item.percentage);
    
    // Create chart
    new Chart(ctx, {
        type: 'pie',
        data: {
            labels: names,
            datasets: [{
                data: percentages,
                backgroundColor: [
                    'rgba(255, 99, 132, 0.7)',
                    'rgba(54, 162, 235, 0.7)',
                    'rgba(255, 206, 86, 0.7)',
                    'rgba(75, 192, 192, 0.7)',
                    'rgba(153, 102, 255, 0.7)'
                ],
                borderColor: [
                    'rgba(255, 99, 132, 1)',
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 206, 86, 1)',
                    'rgba(75, 192, 192, 1)',
                    'rgba(153, 102, 255, 1)'
                ],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'right'
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return `${context.label}: ${context.raw}%`;
                        }
                    }
                }
            }
        }
    });
}

// Function to reorder a product (placeholder)
function reorderProduct(productId) {
    alert(`Reorder request sent for product ID: ${productId}`);
}

// Products page functions
async function loadProducts() {
    try {
        // For testing without backend
        const mockProducts = [
            { _id: '1', name: 'Laptop', category: 'Electronics', price: 999.99, stock: 15 },
            { _id: '2', name: 'Smartphone', category: 'Electronics', price: 499.99, stock: 25 },
            { _id: '3', name: 'Desk Chair', category: 'Furniture', price: 149.99, stock: 8 },
            { _id: '4', name: 'Coffee Maker', category: 'Appliances', price: 79.99, stock: 12 },
            { _id: '5', name: 'Headphones', category: 'Electronics', price: 129.99, stock: 20 }
        ];
        
        currentData = mockProducts;
        renderProducts(mockProducts);
        loadCategories(mockProducts);
        
        // Setup product form
        const productForm = document.getElementById('product-form');
        if (productForm) {
            productForm.addEventListener('submit', handleProductSubmit);
        }
        
        // Setup add product button
        const addProductBtn = document.getElementById('add-product-btn');
        if (addProductBtn) {
            addProductBtn.addEventListener('click', () => {
                openProductModal();
            });
        }
        
        // Setup filters
        setupProductFilters();
    } catch (error) {
        console.error('Error loading products:', error);
    }
}

function renderProducts(products) {
    const productsTable = document.getElementById('products-table');
    if (!productsTable) return;
    
    const tbody = productsTable.querySelector('tbody');
    tbody.innerHTML = '';
    
    if (products.length === 0) {
        tbody.innerHTML = '<tr><td colspan="5" class="text-center">No products found</td></tr>';
        return;
    }
    
    products.forEach(product => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${product.name}</td>
            <td>${product.category}</td>
            <td>$${product.price.toFixed(2)}</td>
            <td>${product.stock}</td>
            <td>
                <button class="btn-edit" data-id="${product._id}">
                    <i class="fas fa-edit"></i>
                </button>
                <button class="btn-delete" data-id="${product._id}">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        `;
        tbody.appendChild(tr);
    });
    
    // Add event listeners to edit and delete buttons
    document.querySelectorAll('.btn-edit').forEach(btn => {
        btn.addEventListener('click', () => editProduct(btn.dataset.id));
    });
    
    document.querySelectorAll('.btn-delete').forEach(btn => {
        btn.addEventListener('click', () => deleteProduct(btn.dataset.id));
    });
}

function loadCategories(products) {
    const categoryFilter = document.getElementById('category-filter');
    if (!categoryFilter) return;
    
    // Extract unique categories
    const categories = [...new Set(products.map(p => p.category))];
    
    // Clear existing options except the first one
    while (categoryFilter.options.length > 1) {
        categoryFilter.remove(1);
    }
    
    // Add category options
    categories.forEach(category => {
        const option = document.createElement('option');
        option.value = category;
        option.textContent = category;
        categoryFilter.appendChild(option);
    });
}

function setupProductFilters() {
    const categoryFilter = document.getElementById('category-filter');
    const stockFilter = document.getElementById('stock-filter');
    const searchInput = document.getElementById('product-search');
    
    if (categoryFilter) {
        categoryFilter.addEventListener('change', applyProductFilters);
    }
    
    if (stockFilter) {
        stockFilter.addEventListener('change', applyProductFilters);
    }
    
    if (searchInput) {
        searchInput.addEventListener('input', applyProductFilters);
    }
}

function applyProductFilters() {
    const categoryFilter = document.getElementById('category-filter');
    const stockFilter = document.getElementById('stock-filter');
    const searchInput = document.getElementById('product-search');
    
    let filteredProducts = [...currentData];
    
    // Apply category filter
    if (categoryFilter && categoryFilter.value) {
        filteredProducts = filteredProducts.filter(p => p.category === categoryFilter.value);
    }
    
    // Apply stock filter
    if (stockFilter && stockFilter.value) {
        if (stockFilter.value === 'low') {
            filteredProducts = filteredProducts.filter(p => p.stock > 0 && p.stock <= 5);
        } else if (stockFilter.value === 'out') {
            filteredProducts = filteredProducts.filter(p => p.stock === 0);
        }
    }
    
    // Apply search filter
    if (searchInput && searchInput.value) {
        const searchTerm = searchInput.value.toLowerCase();
        filteredProducts = filteredProducts.filter(p => 
            p.name.toLowerCase().includes(searchTerm) || 
            p.category.toLowerCase().includes(searchTerm)
        );
    }
    
    renderProducts(filteredProducts);
}

function setupProductModal() {
    const modal = document.getElementById('product-modal');
    const closeBtn = document.querySelector('.close-modal');
    
    if (closeBtn) {
        closeBtn.addEventListener('click', () => {
            modal.style.display = 'none';
        });
    }
    
    // Close modal when clicking outside
    window.addEventListener('click', (e) => {
        if (e.target === modal) {
            modal.style.display = 'none';
        }
    });
}

function openProductModal(product = null) {
    const modal = document.getElementById('product-modal');
    const modalTitle = document.getElementById('modal-title');
    const productForm = document.getElementById('product-form');
    const productId = document.getElementById('product-id');
    
    if (product) {
        modalTitle.textContent = 'Edit Product';
        productId.value = product._id;
        document.getElementById('product-name').value = product.name;
        document.getElementById('product-category').value = product.category;
        document.getElementById('product-price').value = product.price;
        document.getElementById('product-stock').value = product.stock;
    } else {
        modalTitle.textContent = 'Add Product';
        productForm.reset();
        productId.value = '';
    }
    
    modal.style.display = 'block';
}

function editProduct(id) {
    const product = currentData.find(p => p._id === id);
    if (product) {
        openProductModal(product);
    }
}

async function deleteProduct(id) {
    if (confirm('Are you sure you want to delete this product?')) {
        try {
            // For testing without backend
            currentData = currentData.filter(p => p._id !== id);
            renderProducts(currentData);
            loadCategories(currentData);
            
            // With backend:
            // await deleteData('products', id);
            // await loadProducts();
        } catch (error) {
            console.error('Error deleting product:', error);
        }
    }
}

async function handleProductSubmit(e) {
    e.preventDefault();
    
    const productId = document.getElementById('product-id').value;
    const productData = {
        name: document.getElementById('product-name').value,
        category: document.getElementById('product-category').value,
        price: parseFloat(document.getElementById('product-price').value),
        stock: parseInt(document.getElementById('product-stock').value)
    };
    
    try {
        // For testing without backend
        if (productId) {
            // Update existing product
            const index = currentData.findIndex(p => p._id === productId);
            if (index !== -1) {
                currentData[index] = { ...currentData[index], ...productData };
            }
        } else {
            // Create new product
            const newProduct = {
                _id: Date.now().toString(),
                ...productData
            };
            currentData.push(newProduct);
        }
        
        // With backend:
        // if (productId) {
        //     await updateData('products', productId, productData);
        // } else {
        //     await createData('products', productData);
        // }
        
        // Close modal and refresh products
        document.getElementById('product-modal').style.display = 'none';
        renderProducts(currentData);
        loadCategories(currentData);
    } catch (error) {
        console.error('Error saving product:', error);
    }
}

// Customers page functions
async function loadCustomers() {
    try {
        // For testing without backend
        const mockCustomers = [
            { _id: '1', name: 'John Doe', phone: '555-123-4567', email: 'john@example.com', address: '123 Main St, City' },
            { _id: '2', name: 'Jane Smith', phone: '555-987-6543', email: 'jane@example.com', address: '456 Oak Ave, Town' },
            { _id: '3', name: 'Robert Johnson', phone: '555-456-7890', email: 'robert@example.com', address: '789 Pine Rd, Village' },
            { _id: '4', name: 'Sarah Williams', phone: '555-789-0123', email: 'sarah@example.com', address: '321 Elm St, County' },
            { _id: '5', name: 'Michael Brown', phone: '555-234-5678', email: 'michael@example.com', address: '654 Maple Dr, State' }
        ];
        
        currentData = mockCustomers;
        renderCustomers(mockCustomers);
        
        // Setup customer form
        const customerForm = document.getElementById('customer-form');
        if (customerForm) {
            customerForm.addEventListener('submit', handleCustomerSubmit);
        }
        
        // Setup add customer button
        const addCustomerBtn = document.getElementById('add-customer-btn');
        if (addCustomerBtn) {
            addCustomerBtn.addEventListener('click', () => {
                openCustomerModal();
            });
        }
        
        // Setup cancel button
        const cancelBtn = document.getElementById('cancel-customer');
        if (cancelBtn) {
            cancelBtn.addEventListener('click', () => {
                document.getElementById('customer-modal').style.display = 'none';
            });
        }
        
        // Setup search
        const searchInput = document.getElementById('customer-search');
        if (searchInput) {
            searchInput.addEventListener('input', () => {
                const searchTerm = searchInput.value.toLowerCase();
                const filteredCustomers = currentData.filter(customer => 
                    customer.name.toLowerCase().includes(searchTerm) || 
                    customer.email.toLowerCase().includes(searchTerm) ||
                    customer.phone.includes(searchTerm)
                );
                renderCustomers(filteredCustomers);
            });
        }
        
        // Setup customer modal
        setupCustomerModal();
    } catch (error) {
        console.error('Error loading customers:', error);
    }
}

function renderCustomers(customers) {
    const customersTable = document.getElementById('customers-table');
    if (!customersTable) return;
    
    const tbody = customersTable.querySelector('tbody');
    tbody.innerHTML = '';
    
    if (customers.length === 0) {
        tbody.innerHTML = '<tr><td colspan="5" class="text-center">No customers found</td></tr>';
        return;
    }
    
    customers.forEach(customer => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${customer.name}</td>
            <td>${customer.phone}</td>
            <td>${customer.email}</td>
            <td>${customer.address}</td>
            <td>
                <button class="btn-edit" data-id="${customer._id}">
                    <i class="fas fa-edit"></i>
                </button>
                <button class="btn-delete" data-id="${customer._id}">
                    <i class="fas fa-trash"></i>
                </button>
            </td>
        `;
        tbody.appendChild(tr);
    });
    
    // Add event listeners to edit and delete buttons
    document.querySelectorAll('.btn-edit').forEach(btn => {
        btn.addEventListener('click', () => editCustomer(btn.dataset.id));
    });
    
    document.querySelectorAll('.btn-delete').forEach(btn => {
        btn.addEventListener('click', () => deleteCustomer(btn.dataset.id));
    });
}

function setupCustomerModal() {
    const modal = document.getElementById('customer-modal');
    const closeBtn = document.querySelector('.close-modal');
    
    if (closeBtn) {
        closeBtn.addEventListener('click', () => {
            modal.style.display = 'none';
        });
    }
    
    // Close modal when clicking outside
    window.addEventListener('click', (e) => {
        if (e.target === modal) {
            modal.style.display = 'none';
        }
    });
}

function openCustomerModal(customer = null) {
    const modal = document.getElementById('customer-modal');
    const modalTitle = document.getElementById('modal-title');
    const customerForm = document.getElementById('customer-form');
    const customerId = document.getElementById('customer-id');
    
    if (customer) {
        modalTitle.textContent = 'Edit Customer';
        customerId.value = customer._id;
        document.getElementById('customer-name').value = customer.name;
        document.getElementById('customer-phone').value = customer.phone;
        document.getElementById('customer-email').value = customer.email;
        document.getElementById('customer-address').value = customer.address;
    } else {
        modalTitle.textContent = 'Add Customer';
        customerForm.reset();
        customerId.value = '';
    }
    
    modal.style.display = 'block';
}

function editCustomer(id) {
    const customer = currentData.find(c => c._id === id);
    if (customer) {
        openCustomerModal(customer);
    }
}

async function deleteCustomer(id) {
    if (confirm('Are you sure you want to delete this customer?')) {
        try {
            // For testing without backend
            currentData = currentData.filter(c => c._id !== id);
            renderCustomers(currentData);
            
            // With backend:
            // await deleteData('customers', id);
            // await loadCustomers();
        } catch (error) {
            console.error('Error deleting customer:', error);
        }
    }
}

async function handleCustomerSubmit(e) {
    e.preventDefault();
    
    const customerId = document.getElementById('customer-id').value;
    const customerData = {
        name: document.getElementById('customer-name').value,
        phone: document.getElementById('customer-phone').value,
        email: document.getElementById('customer-email').value,
        address: document.getElementById('customer-address').value
    };
    
    try {
        // For testing without backend
        if (customerId) {
            // Update existing customer
            const index = currentData.findIndex(c => c._id === customerId);
            if (index !== -1) {
                currentData[index] = { ...currentData[index], ...customerData };
            }
        } else {
            // Create new customer
            const newCustomer = {
                _id: Date.now().toString(),
                ...customerData
            };
            currentData.push(newCustomer);
        }
        
        // With backend:
        // if (customerId) {
        //     await updateData('customers', customerId, customerData);
        // } else {
        //     await createData('customers', customerData);
        // }
        
        // Close modal and refresh customers
        document.getElementById('customer-modal').style.display = 'none';
        renderCustomers(currentData);
    } catch (error) {
        console.error('Error saving customer:', error);
    }
}

// Setup search functionality
function setupSearch() {
    const searchInput = document.getElementById('search-input');
    if (searchInput) {
        searchInput.addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase();
            filterData(searchTerm);
        });
    }
}

// Filter data based on search term
function filterData(searchTerm) {
    if (!currentData.length) return;
    
    let filteredData = currentData;
    
    if (searchTerm) {
        filteredData = currentData.filter(item => {
            return Object.values(item).some(value => 
                value && value.toString().toLowerCase().includes(searchTerm)
            );
        });
    }
    
    // Re-render based on current page
    switch(currentPage) {
        case 'products.html':
            renderProducts(filteredData);
            break;
        case 'customers.html':
            renderCustomers(filteredData);
            break;
        case 'billing.html':
            renderBills(filteredData);
            break;
        case 'reports.html':
            renderReports(filteredData);
            break;
    }
}

// Toggle theme between light and dark
function toggleTheme() {
    const currentTheme = localStorage.getItem('theme') || 'light';
    const newTheme = currentTheme === 'light' ? 'dark' : 'light';
    
    document.body.classList.remove(currentTheme);
    document.body.classList.add(newTheme);
    
    localStorage.setItem('theme', newTheme);
    
    // Update icon
    this.innerHTML = newTheme === 'light' 
        ? '<i class="fas fa-moon"></i>' 
        : '<i class="fas fa-sun"></i>';
}

// Authentication helper functions
function getToken() {
    return localStorage.getItem('token');
}

// Fetch with authentication
async function authFetch(url, options = {}) {
    const token = getToken();
    
    const headers = {
        'Content-Type': 'application/json',
        ...options.headers
    };
    
    if (token) {
        headers['Authorization'] = `Bearer ${token}`;
    }
    
    const response = await fetch(url, {
        ...options,
        headers
    });
    
    // If unauthorized, redirect to login
    if (response.status === 401) {
        localStorage.removeItem('token');
        localStorage.removeItem('user');
        window.location.href = 'pages/login.html';
        return;
    }
    
    return response;
}

// CRUD operations
async function fetchData(endpoint) {
    try {
        const response = await authFetch(`${API_URL}/${endpoint}`);
        const data = await response.json();
        return data;
    } catch (error) {
        console.error(`Error fetching ${endpoint}:`, error);
        return [];
    }
}

async function createData(endpoint, data) {
    try {
        const response = await authFetch(`${API_URL}/${endpoint}`, {
            method: 'POST',
            body: JSON.stringify(data)
        });
        return await response.json();
    } catch (error) {
        console.error(`Error creating ${endpoint}:`, error);
        throw error;
    }
}

async function updateData(endpoint, id, data) {
    try {
        const response = await authFetch(`${API_URL}/${endpoint}/${id}`, {
            method: 'PUT',
            body: JSON.stringify(data)
        });
        return await response.json();
    } catch (error) {
        console.error(`Error updating ${endpoint}:`, error);
        throw error;
    }
}

async function deleteData(endpoint, id) {
    try {
        const response = await authFetch(`${API_URL}/${endpoint}/${id}`, {
            method: 'DELETE'
        });
        return await response.json();
    } catch (error) {
        console.error(`Error deleting ${endpoint}:`, error);
        throw error;
    }
}