let weeklyProfitChartInstance = null;
let monthlyProductChartInstance = null;

function moneyFormat(value) {
    return Number(value || 0).toLocaleString(undefined, {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });
}

async function fetchJson(url) {
    const response = await fetch(url, { cache: 'no-store' });
    return await response.json();
}

async function loadDashboard() {
    const billCount = document.getElementById('billCount');
    if (!billCount) return;

    const data = await fetchJson('api/dashboard_data.php');

    document.getElementById('billCount').textContent = data.summary.bill_count ?? 0;
    document.getElementById('todaySale').textContent = moneyFormat(data.summary.sale);
    document.getElementById('todayIncome').textContent = moneyFormat(data.summary.income);
    document.getElementById('todayProfit').textContent = moneyFormat(data.summary.profit);

    const weeklyCtx = document.getElementById('weeklyProfitChart');
    if (weeklyCtx) {
        if (weeklyProfitChartInstance) {
            weeklyProfitChartInstance.destroy();
        }

        weeklyProfitChartInstance = new Chart(weeklyCtx, {
            type: 'line',
            data: {
                labels: data.weekly_profit.labels || [],
                datasets: [{
                    label: 'Profit',
                    data: data.weekly_profit.values || [],
                    borderColor: '#22c55e',
                    backgroundColor: 'rgba(34,197,94,0.15)',
                    fill: true,
                    tension: 0.35,
                    borderWidth: 3,
                    pointRadius: 4,
                    pointHoverRadius: 5
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                animation: false,
                plugins: {
                    legend: { display: false }
                },
                scales: {
                    x: {
                        ticks: {
                            color: '#334155',
                            maxRotation: 45,
                            minRotation: 0,
                            autoSkip: true
                        },
                        grid: {
                            display: false
                        }
                    },
                    y: {
                        beginAtZero: true,
                        ticks: {
                            color: '#334155'
                        }
                    }
                }
            }
        });
    }

    const donutCtx = document.getElementById('monthlyProductChart');
    if (donutCtx) {
        if (monthlyProductChartInstance) {
            monthlyProductChartInstance.destroy();
        }

        monthlyProductChartInstance = new Chart(donutCtx, {
            type: 'doughnut',
            data: {
                labels: data.monthly_products.labels || [],
                datasets: [{
                    data: data.monthly_products.values || [],
                    backgroundColor: [
                        '#2563eb',
                        '#22c55e',
                        '#f59e0b',
                        '#ef4444',
                        '#8b5cf6',
                        '#14b8a6',
                        '#f97316',
                        '#06b6d4',
                        '#84cc16',
                        '#e11d48'
                    ],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                animation: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            boxWidth: 12,
                            padding: 12
                        }
                    }
                }
            }
        });
    }
}

async function loadBills() {
    const list = document.getElementById('billList');
    if (!list) return;

    const date = document.getElementById('billDate').value;
    const billNumber = document.getElementById('billNumber').value;
    const data = await fetchJson(`api/bills.php?date=${encodeURIComponent(date)}&bill_number=${encodeURIComponent(billNumber)}`);

    if (!data.length) {
        list.innerHTML = '<div class="empty-state">No bill records found.</div>';
        return;
    }

    list.innerHTML = data.map(item => {
        const hasCreditor = item.customer_name && item.customer_name.trim() !== '';
        const negativeBalance = Number(item.balance_amount) < 0;
        const dangerClass = hasCreditor && negativeBalance ? ' danger-soft' : '';

        return `
            <div class="list-card${dangerClass}">
                <div class="card-row"><strong>Bill Number:</strong><span>${item.bill_number ?? ''}</span></div>
                <div class="card-row"><strong>Creditor Name:</strong><span>${item.customer_name ?? '-'}</span></div>
                <div class="card-row"><strong>Date:</strong><span>${item.entered_date ?? ''}</span></div>
                <div class="card-row"><strong>Total Amount:</strong><span>${moneyFormat(item.total_amount)}</span></div>
                <div class="card-row"><strong>Discount Amount:</strong><span>${moneyFormat(item.total_discount)}</span></div>
                <div class="card-row"><strong>Received Amount:</strong><span>${moneyFormat(item.received_amount)}</span></div>
                <div class="card-row"><strong>Balance Amount:</strong><span>${moneyFormat(item.balance_amount)}</span></div>
                <div class="card-row"><strong>Cashier:</strong><span>${item.entered_user ?? ''}</span></div>
            </div>
        `;
    }).join('');
}

async function loadStock() {
    const list = document.getElementById('stockList');
    if (!list) return;

    const search = document.getElementById('stockSearch').value;
    const data = await fetchJson(`api/stock.php?search=${encodeURIComponent(search)}`);

    if (!data.length) {
        list.innerHTML = '<div class="empty-state">No stock records found.</div>';
        return;
    }

    list.innerHTML = data.map(item => `
        <div class="list-card">
            <div class="card-row"><strong>Product:</strong><span>${item.product_name ?? ''}</span></div>
            <div class="card-row"><strong>Quantity:</strong><span>${item.purchased_qty ?? 0}</span></div>
            <div class="card-row"><strong>Unit:</strong><span>${item.unit ?? ''}</span></div>
        </div>
    `).join('');
}

async function loadPurchases() {
    const list = document.getElementById('purchaseList');
    if (!list) return;

    const date = document.getElementById('purchaseDate').value;
    const invoiceNumber = document.getElementById('invoiceNumber').value;
    const company = document.getElementById('companyName').value;
    const data = await fetchJson(`api/purchases.php?date=${encodeURIComponent(date)}&invoice_number=${encodeURIComponent(invoiceNumber)}&company=${encodeURIComponent(company)}`);

    if (!data.length) {
        list.innerHTML = '<div class="empty-state">No purchasing records found.</div>';
        return;
    }

    list.innerHTML = data.map(item => `
        <div class="list-card">
            <div class="card-row"><strong>Date:</strong><span>${item.purchase_date ?? ''}</span></div>
            <div class="card-row"><strong>Company:</strong><span>${item.supplier ?? ''}</span></div>
            <div class="card-row"><strong>Invoice Number:</strong><span>${item.invoice_number ?? ''}</span></div>
            <div class="card-row"><strong>Total Amount:</strong><span>${moneyFormat(item.total_amount)}</span></div>
            <div class="card-row"><strong>Paid Amount:</strong><span>${moneyFormat(item.paid_amount)}</span></div>
            <div class="card-row"><strong>Balance Amount:</strong><span>${moneyFormat(item.pending_amount)}</span></div>
        </div>
    `).join('');
}

document.addEventListener('DOMContentLoaded', () => {
    loadDashboard();
    loadBills();
    loadStock();
    loadPurchases();
});

window.addEventListener('resize', () => {
    if (weeklyProfitChartInstance) {
        weeklyProfitChartInstance.resize();
    }
    if (monthlyProductChartInstance) {
        monthlyProductChartInstance.resize();
    }
});