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

// Format number
function formatNumber(num) {
    return parseFloat(num || 0).toLocaleString('en-IN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });
}

// Format date
function formatDate(dateStr) {
    if (!dateStr) return '-';
    const date = new Date(dateStr);
    const day = String(date.getDate()).padStart(2, '0');
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const year = date.getFullYear();
    return `${day}/${month}/${year}`;
}

// Format date for input (YYYY-MM-DD)
function formatDateForInput(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

// Set quick filter dates
function setQuickFilter(filter) {
    const today = new Date();
    let startDate, endDate;
    
    // Remove active class from all buttons
    document.querySelectorAll('.quick-filter-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    
    // Add active class to clicked button
    event.target.classList.add('active');
    
    const customDatesRow = document.getElementById('customDatesRow');
    
    if (filter === 'custom') {
        customDatesRow.classList.add('show');
        return;
    } else {
        customDatesRow.classList.remove('show');
    }
    
    switch(filter) {
        case 'today':
            startDate = new Date(today);
            endDate = new Date(today);
            break;
        case 'yesterday':
            startDate = new Date(today);
            startDate.setDate(today.getDate() - 1);
            endDate = new Date(startDate);
            break;
        case 'thisWeek':
            startDate = new Date(today);
            startDate.setDate(today.getDate() - today.getDay());
            endDate = new Date(today);
            break;
        case 'lastWeek':
            startDate = new Date(today);
            startDate.setDate(today.getDate() - today.getDay() - 7);
            endDate = new Date(startDate);
            endDate.setDate(startDate.getDate() + 6);
            break;
        case 'thisMonth':
            startDate = new Date(today.getFullYear(), today.getMonth(), 1);
            endDate = new Date(today.getFullYear(), today.getMonth() + 1, 0);
            break;
        case 'lastMonth':
            startDate = new Date(today.getFullYear(), today.getMonth() - 1, 1);
            endDate = new Date(today.getFullYear(), today.getMonth(), 0);
            break;
        case 'thisYear':
            startDate = new Date(today.getFullYear(), 0, 1);
            endDate = new Date(today.getFullYear(), 11, 31);
            break;
        default:
            startDate = new Date(today.getFullYear(), today.getMonth(), 1);
            endDate = new Date(today.getFullYear(), today.getMonth() + 1, 0);
    }
    
    document.getElementById('startDate').value = formatDateForInput(startDate);
    document.getElementById('endDate').value = formatDateForInput(endDate);
    
    loadReport();
}

// Load report data
async function loadReport() {
    const startDate = document.getElementById('startDate').value;
    const endDate = document.getElementById('endDate').value;
    const customerId = document.getElementById('customerFilter').value;
    const salesType = document.getElementById('salesTypeFilter').value;
    const hsnCode = document.getElementById('hsnFilter').value;
    
    if (!startDate || !endDate) {
        alert('Please select start and end dates');
        return;
    }
    
    // Show loading state
    document.getElementById('loadingState').style.display = 'block';
    document.getElementById('reportContent').style.display = 'none';
    
    try {
        let apiUrl = `api/get-hsn-wise-sales.php?startDate=${startDate}&endDate=${endDate}`;
        
        if (customerId) {
            apiUrl += `&customerId=${encodeURIComponent(customerId)}`;
        }
        
        if (salesType) {
            apiUrl += `&salesType=${encodeURIComponent(salesType)}`;
        }
        
        if (hsnCode) {
            apiUrl += `&hsnCode=${encodeURIComponent(hsnCode)}`;
        }
        
        const response = await fetch(apiUrl);
        const data = await response.json();
        
        if (data.success) {
            renderReport(data);
        } else {
            alert('Error loading report: ' + (data.message || 'Unknown error'));
        }
    } catch (error) {
        console.error('Error:', error);
        alert('Failed to load report. Please try again.');
    } finally {
        document.getElementById('loadingState').style.display = 'none';
    }
}

// Render report data
function renderReport(data) {
    const { summary, hsnData, startDate, endDate, customerInfo, salesTypeInfo } = data;
    
    // Update report period
    const periodText = `${formatDate(startDate)} to ${formatDate(endDate)}`;
    document.getElementById('reportPeriod').textContent = periodText;
    
    // Update summary cards
    document.getElementById('totalSales').textContent = formatCurrency(summary.totalSales);
    document.getElementById('taxableAmount').textContent = formatCurrency(summary.taxableAmount);
    document.getElementById('cgstAmount').textContent = formatCurrency(summary.cgstAmount);
    document.getElementById('sgstAmount').textContent = formatCurrency(summary.sgstAmount);
    document.getElementById('igstAmount').textContent = formatCurrency(summary.igstAmount);
    document.getElementById('totalTax').textContent = formatCurrency(summary.totalTax);
    document.getElementById('totalQuantity').textContent = formatNumber(summary.totalQuantity);
    document.getElementById('hsnCount').textContent = summary.hsnCount;
    
    // Update count display
    document.getElementById('hsnCodeCount').textContent = `(${summary.hsnCount} codes)`;
    
    // Render table
    renderHSNTable(hsnData, summary);
    
    // Show report content
    document.getElementById('reportContent').style.display = 'block';
}

// Render HSN table
function renderHSNTable(hsnData, summary) {
    const tbody = document.getElementById('hsnTableBody');
    
    if (!hsnData || hsnData.length === 0) {
        tbody.innerHTML = '<tr><td colspan="11" class="no-data">No HSN data available for the selected period and filters.</td></tr>';
        return;
    }
    
    let html = '';
    hsnData.forEach((row, index) => {
        // Truncate item names if too long
        const itemNames = row.ItemNames || 'N/A';
        const displayNames = itemNames.length > 100 ? itemNames.substring(0, 100) + '...' : itemNames;
        
        html += `
            <tr>
                <td class="text-center">${index + 1}</td>
                <td class="hsn-code-cell">${row.HSNCode || 'NOT SPECIFIED'}</td>
                <td class="item-names-cell" title="${itemNames}">${displayNames}</td>
                <td class="text-right">${row.TransactionCount || 0}</td>
                <td class="text-right">${formatNumber(row.TotalQuantity)}</td>
                <td class="text-right">${formatCurrency(row.TaxableAmount)}</td>
                <td class="text-right">${formatCurrency(row.CGSTAmount)}</td>
                <td class="text-right">${formatCurrency(row.SGSTAmount)}</td>
                <td class="text-right">${formatCurrency(row.IGSTAmount)}</td>
                <td class="text-right amount-positive">${formatCurrency(row.TotalTax)}</td>
                <td class="text-right amount-positive"><strong>${formatCurrency(row.TotalAmount)}</strong></td>
            </tr>
        `;
    });
    
    tbody.innerHTML = html;
    
    // Update footer totals
    document.getElementById('totalQtyFooter').textContent = formatNumber(summary.totalQuantity);
    document.getElementById('totalTaxableFooter').textContent = formatCurrency(summary.taxableAmount);
    document.getElementById('totalCGSTFooter').textContent = formatCurrency(summary.cgstAmount);
    document.getElementById('totalSGSTFooter').textContent = formatCurrency(summary.sgstAmount);
    document.getElementById('totalIGSTFooter').textContent = formatCurrency(summary.igstAmount);
    document.getElementById('totalTaxFooter').textContent = formatCurrency(summary.totalTax);
    document.getElementById('totalFinalFooter').textContent = formatCurrency(summary.totalSales);
}

// Export to Excel
function exportToExcel() {
    const startDate = document.getElementById('startDate').value;
    const endDate = document.getElementById('endDate').value;
    const customerId = document.getElementById('customerFilter').value;
    const salesType = document.getElementById('salesTypeFilter').value;
    const hsnCode = document.getElementById('hsnFilter').value;
    
    if (!startDate || !endDate) {
        alert('Please generate a report first');
        return;
    }
    
    // Get table data
    const table = document.querySelector('.data-table');
    if (!table) {
        alert('No data to export');
        return;
    }
    
    // Create workbook
    let csv = 'HSN Wise Sales Report\n';
    csv += `Period: ${formatDate(startDate)} to ${formatDate(endDate)}\n`;
    csv += `Generated: ${new Date().toLocaleString('en-IN')}\n\n`;
    
    // Add headers
    const headers = ['S.No', 'HSN/SAC Code', 'Item Names', 'Transactions', 'Total Qty', 'Taxable Value', 'CGST Amt', 'SGST Amt', 'IGST Amt', 'Total Tax', 'Total Amount'];
    csv += headers.join(',') + '\n';
    
    // Add data rows
    const tbody = table.querySelector('tbody');
    const rows = tbody.querySelectorAll('tr');
    
    rows.forEach(row => {
        const cells = row.querySelectorAll('td');
        if (cells.length > 1) {
            const rowData = [];
            cells.forEach(cell => {
                let text = cell.textContent.trim();
                // Remove currency symbols and format
                text = text.replace(/₹/g, '').replace(/,/g, '');
                // Escape commas in item names
                if (text.includes(',')) {
                    text = `"${text}"`;
                }
                rowData.push(text);
            });
            csv += rowData.join(',') + '\n';
        }
    });
    
    // Add footer totals
    csv += '\nTOTALS:,,,';
    const tfoot = table.querySelector('tfoot');
    const footerCells = tfoot.querySelectorAll('td');
    footerCells.forEach((cell, index) => {
        if (index > 0) {
            let text = cell.textContent.trim().replace(/₹/g, '').replace(/,/g, '');
            csv += text + ',';
        }
    });
    
    // Download CSV
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', `HSN_Wise_Sales_Report_${startDate}_to_${endDate}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

// Open print view
function openPrintView() {
    const startDate = document.getElementById('startDate').value;
    const endDate = document.getElementById('endDate').value;
    const customerId = document.getElementById('customerFilter').value;
    const salesType = document.getElementById('salesTypeFilter').value;
    const hsnCode = document.getElementById('hsnFilter').value;
    
    if (!startDate || !endDate) {
        alert('Please generate a report first');
        return;
    }
    
    let printUrl = `print-hsn-wise-sales.php?startDate=${startDate}&endDate=${endDate}`;
    
    if (customerId) {
        printUrl += `&customerId=${encodeURIComponent(customerId)}`;
    }
    
    if (salesType) {
        printUrl += `&salesType=${encodeURIComponent(salesType)}`;
    }
    
    if (hsnCode) {
        printUrl += `&hsnCode=${encodeURIComponent(hsnCode)}`;
    }
    
    window.open(printUrl, '_blank');
}

// Load HSN codes for dropdown
async function loadHSNCodes() {
    try {
        const response = await fetch('api/get-hsn-wise-sales.php?startDate=2020-01-01&endDate=2099-12-31');
        const data = await response.json();
        
        if (data.success && data.hsnList) {
            const hsnFilter = document.getElementById('hsnFilter');
            
            data.hsnList.forEach(hsn => {
                const option = document.createElement('option');
                option.value = hsn;
                option.textContent = hsn;
                hsnFilter.appendChild(option);
            });
        }
    } catch (error) {
        console.error('Error loading HSN codes:', error);
    }
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    // Initialize Select2
    $('#customerFilter, #salesTypeFilter, #hsnFilter').select2({
        theme: 'bootstrap-5',
        width: '100%'
    });
    
    // Load HSN codes
    loadHSNCodes();
    
    // Set default to current month
    const today = new Date();
    const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
    const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0);
    
    document.getElementById('startDate').value = formatDateForInput(firstDay);
    document.getElementById('endDate').value = formatDateForInput(lastDay);
});
