// Purchase Reports Dashboard JavaScript

// Wait for DOM to load
document.addEventListener('DOMContentLoaded', function() {
    // Load summary stats
    loadSummaryStats();
    
    // Initialize date range filter
    initializeDateRangeFilter();
    
    // Load charts
    loadCharts();
    
    // Setup reset button
    document.getElementById('resetFilters').addEventListener('click', resetFilters);
});

// Load summary statistics
function loadSummaryStats() {
    const dateRange = document.getElementById('filterDateRange').value;
    
    // Show loading spinners
    document.getElementById('totalPurchaseAmount').innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
    document.getElementById('totalInvoices').innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
    document.getElementById('totalItemsPurchased').innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
    document.getElementById('avgInvoiceValue').innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
    
    // Simulated data - Replace with actual API call
    setTimeout(() => {
        document.getElementById('totalPurchaseAmount').textContent = '₹7,500';
        document.getElementById('totalInvoices').textContent = '1';
        document.getElementById('totalItemsPurchased').textContent = '50';
        document.getElementById('avgInvoiceValue').textContent = '₹7,500';
    }, 500);
}

// Initialize date range filter
function initializeDateRangeFilter() {
    const dateRangeSelect = document.getElementById('filterDateRange');
    const customFromContainer = document.getElementById('customDateRangeContainer');
    const customToContainer = document.getElementById('customDateToContainer');
    
    dateRangeSelect.addEventListener('change', function() {
        if (this.value === 'custom') {
            customFromContainer.style.display = 'block';
            customToContainer.style.display = 'block';
        } else {
            customFromContainer.style.display = 'none';
            customToContainer.style.display = 'none';
            loadSummaryStats();
        }
    });
}

// Load charts
function loadCharts() {
    loadPurchaseTrendChart();
    loadPurchaseTypeChart();
}

// Load purchase trend chart
function loadPurchaseTrendChart() {
    const ctx = document.getElementById('purchaseTrendChart');
    if (!ctx) return;
    
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: ['Day 1', 'Day 5', 'Day 10', 'Day 15', 'Day 20', 'Day 25', 'Day 30'],
            datasets: [{
                label: 'Purchase Amount (₹)',
                data: [0, 0, 0, 0, 7500, 0, 0],
                borderColor: 'rgb(231, 74, 59)',
                backgroundColor: 'rgba(231, 74, 59, 0.1)',
                tension: 0.4,
                fill: true
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: true,
                    position: 'top'
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return '₹' + value.toLocaleString();
                        }
                    }
                }
            }
        }
    });
}

// Load purchase type chart
function loadPurchaseTypeChart() {
    const ctx = document.getElementById('purchaseTypeChart');
    if (!ctx) return;
    
    new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: ['GST', 'NON-GST', 'IMPORT'],
            datasets: [{
                data: [100, 0, 0],
                backgroundColor: [
                    'rgba(231, 74, 59, 0.8)',
                    'rgba(246, 194, 62, 0.8)',
                    'rgba(54, 185, 204, 0.8)'
                ],
                borderWidth: 2,
                borderColor: '#fff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });
}

// Reset filters
function resetFilters() {
    document.getElementById('filterDateRange').value = 'this_month';
    document.getElementById('filterPurchaseType').value = '';
    document.getElementById('filterSupplier').value = '';
    document.getElementById('customDateRangeContainer').style.display = 'none';
    document.getElementById('customDateToContainer').style.display = 'none';
    loadSummaryStats();
    loadCharts();
}

// Format currency
function formatCurrency(amount) {
    return '₹' + Number(amount).toLocaleString('en-IN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });
}
