// Format currency
function formatCurrency(amount) {
    return '₹' + parseFloat(amount).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;
    
    if (!startDate || !endDate) {
        await MsgBox.alert('Please select both start and end dates');
        return;
    }
    
    document.getElementById('loadingState').style.display = 'block';
    document.getElementById('reportContent').style.display = 'none';
    
    let apiUrl = `api/get-customer-accounts.php?startDate=${startDate}&endDate=${endDate}`;
    if (customerId) {
        apiUrl += `&customerId=${encodeURIComponent(customerId)}`;
    }
    
    try {
        const response = await fetch(apiUrl);
        const data = await response.json();
        
        if (!data.success) {
            throw new Error(data.message || 'Failed to load report');
        }
        renderReport(data);
    } catch (error) {
        await MsgBox.alert('Error loading report: ' + error.message);
        document.getElementById('loadingState').style.display = 'none';
    }
}

// Render report
function renderReport(data) {
    const { summary, transactions, startDate, endDate, customerInfo } = data;
    
    // Update report period
    let periodText = `${formatDate(startDate)} to ${formatDate(endDate)}`;
    if (customerInfo) {
        periodText += ` - ${customerInfo.CustomerName}`;
    } else {
        periodText += ' - All Customers';
    }
    document.getElementById('reportPeriod').textContent = periodText;
    
    // Update totals
    document.getElementById('totalDebitFooter').textContent = formatCurrency(summary.totalSales);
    document.getElementById('totalCreditFooter').textContent = formatCurrency(summary.totalPayments);
    
    document.getElementById('closingBalanceFooter').textContent = formatCurrency(summary.closingBalance);
    const closingClass = summary.closingBalance >= 0 ? 'amount-negative' : 'amount-positive';
    document.getElementById('closingBalanceFooter').className = `text-right ${closingClass}`;
    
    // Render ledger
    renderLedger(transactions, summary);
    
    document.getElementById('loadingState').style.display = 'none';
    document.getElementById('reportContent').style.display = 'block';
}

// Render ledger table
function renderLedger(transactions, summary) {
    const tbody = document.getElementById('ledgerTableBody');
    
    document.getElementById('ledgerCount').textContent = `(${transactions.length} transactions)`;
    
    if (transactions.length === 0 && summary.openingBalance === 0) {
        tbody.innerHTML = '<tr><td colspan="8" class="no-data">No transactions found for the selected period.</td></tr>';
        return;
    }
    
    let rows = '';
    
    // Add Opening Balance Row
    rows += `
        <tr class="opening-balance-row">
            <td colspan="6"><strong>OPENING BALANCE</strong></td>
            <td class="text-right ${summary.openingBalance >= 0 ? 'amount-negative' : ''}">${summary.openingBalance >= 0 ? formatCurrency(summary.openingBalance) : '-'}</td>
            <td class="text-right ${summary.openingBalance < 0 ? 'amount-positive' : ''}">${summary.openingBalance < 0 ? formatCurrency(Math.abs(summary.openingBalance)) : '-'}</td>
        </tr>
    `;
    
    // Render transaction rows
    transactions.forEach(txn => {
        const typeClass = txn.TransactionType === 'Debit' ? 'badge-debit' : 'badge-credit';
        
        rows += `
            <tr>
                <td>${formatDate(txn.TransactionDate)}</td>
                <td>${txn.CustomerName || '-'}</td>
                <td><span class="badge ${typeClass}">${txn.TransactionType}</span></td>
                <td>${txn.InvoiceNumber || txn.ReferenceNumber || '-'}</td>
                <td title="${txn.Description || '-'}">${(txn.Description || '-').substring(0, 50)}</td>
                <td>${txn.PaymentMode || '-'}</td>
                <td class="text-right ${txn.DebitAmount ? 'amount-negative' : ''}">${txn.DebitAmount ? formatCurrency(txn.DebitAmount) : '-'}</td>
                <td class="text-right ${txn.CreditAmount ? 'amount-positive' : ''}">${txn.CreditAmount ? formatCurrency(txn.CreditAmount) : '-'}</td>
            </tr>
        `;
    });
    
    // Add Closing Balance Row
    rows += `
        <tr class="closing-balance-row">
            <td colspan="6"><strong>CLOSING BALANCE</strong></td>
            <td class="text-right ${summary.closingBalance >= 0 ? 'amount-negative' : ''}">${summary.closingBalance >= 0 ? formatCurrency(summary.closingBalance) : '-'}</td>
            <td class="text-right ${summary.closingBalance < 0 ? 'amount-positive' : ''}">${summary.closingBalance < 0 ? formatCurrency(Math.abs(summary.closingBalance)) : '-'}</td>
        </tr>
    `;
    
    tbody.innerHTML = rows;
}

// Load report on page load
document.addEventListener('DOMContentLoaded', function() {
    // Initialize Select2 for customer filter
    $('#customerFilter').select2({
        placeholder: 'All Customers',
        allowClear: true,
        width: '100%',
        theme: 'default'
    });
    
    // Read URL parameters and set form values
    const urlParams = new URLSearchParams(window.location.search);
    const customerId = urlParams.get('customerId');
    const startDate = urlParams.get('startDate');
    const endDate = urlParams.get('endDate');
    
    // Set customer filter if provided
    if (customerId) {
        $('#customerFilter').val(customerId).trigger('change');
    }
    
    // Set date range if provided
    if (startDate) {
        document.getElementById('startDate').value = startDate;
    }
    if (endDate) {
        document.getElementById('endDate').value = endDate;
    }
    
    // Load report with default or URL parameters
    loadReport();
});

// Export to Excel
async function exportToExcel() {
    const startDate = document.getElementById('startDate').value;
    const endDate = document.getElementById('endDate').value;
    
    if (!startDate || !endDate) {
        await MsgBox.alert('Please select both start and end dates');
        return;
    }
    
    const table = document.getElementById('ledgerTableBody').parentElement;
    
    let html = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">';
    html += '<head>';
    html += '<meta charset="UTF-8">';
    html += '<style>';
    html += 'table { border-collapse: collapse; width: 100%; }';
    html += 'th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }';
    html += 'th { background-color: #4e73df; color: white; font-weight: bold; }';
    html += '.amount-positive { color: #1cc88a; }';
    html += '.amount-negative { color: #e74a3b; }';
    html += '</style>';
    html += '</head>';
    html += '<body>';
    html += '<h2>UZRS INVENTORY - Customer Accounts Report</h2>';
    html += '<p>Period: ' + formatDate(startDate) + ' to ' + formatDate(endDate) + '</p>';
    html += table.outerHTML;
    html += '</body></html>';
    
    const blob = new Blob([html], { type: 'application/vnd.ms-excel' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'Customer_Accounts_Report_' + startDate + '_to_' + endDate + '.xls';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
}

// Open dedicated print view
async function openPrintView() {
    const startDate = document.getElementById('startDate').value;
    const endDate = document.getElementById('endDate').value;
    const customerId = document.getElementById('customerFilter').value;

    if (!startDate || !endDate) {
        await MsgBox.alert('Please select both start and end dates');
        return;
    }

    let printUrl = `print-customer-accounts.php?startDate=${startDate}&endDate=${endDate}`;
    if (customerId) {
        printUrl += `&customerId=${encodeURIComponent(customerId)}`;
    }

    window.open(printUrl, '_blank', 'width=1024,height=768');
}
