// Global variables
let currentData = null;

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

// Date formatter
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}`;
}

// 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');

    switch (filter) {
        case 'today':
            startDate = endDate = today;
            break;
        case 'yesterday':
            const yesterday = new Date(today);
            yesterday.setDate(yesterday.getDate() - 1);
            startDate = endDate = yesterday;
            break;
        case 'thisWeek':
            const firstDayOfWeek = new Date(today);
            firstDayOfWeek.setDate(today.getDate() - today.getDay());
            startDate = firstDayOfWeek;
            endDate = today;
            break;
        case 'lastWeek':
            const lastWeekEnd = new Date(today);
            lastWeekEnd.setDate(today.getDate() - today.getDay() - 1);
            const lastWeekStart = new Date(lastWeekEnd);
            lastWeekStart.setDate(lastWeekEnd.getDate() - 6);
            startDate = lastWeekStart;
            endDate = lastWeekEnd;
            break;
        case 'thisMonth':
            startDate = new Date(today.getFullYear(), today.getMonth(), 1);
            endDate = today;
            break;
        case 'lastMonth':
            const lastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);
            const lastMonthEnd = new Date(today.getFullYear(), today.getMonth(), 0);
            startDate = lastMonth;
            endDate = lastMonthEnd;
            break;
        case 'thisYear':
            startDate = new Date(today.getFullYear(), 0, 1);
            endDate = today;
            break;
        case 'custom':
            // Keep current values
            return;
    }

    if (startDate && endDate) {
        document.getElementById('startDate').value = startDate.toISOString().split('T')[0];
        document.getElementById('endDate').value = endDate.toISOString().split('T')[0];
        
        // Auto-load if not custom
        if (filter !== 'custom') {
            loadReport();
        }
    }
}

// Load report
async function loadReport() {
    const startDate = document.getElementById('startDate').value;
    const endDate = document.getElementById('endDate').value;
    const transactionType = document.getElementById('transactionTypeFilter').value;
    const paymentMode = document.getElementById('paymentModeFilter').value;

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

    // Show loading state
    document.getElementById('loadingState').style.display = 'block';
    document.getElementById('reportContent').style.display = 'none';

    // Build API URL
    let apiUrl = `api/get-cash-flow-report.php?startDate=${startDate}&endDate=${endDate}`;
    if (transactionType) {
        apiUrl += `&transactionType=${encodeURIComponent(transactionType)}`;
    }
    if (paymentMode) {
        apiUrl += `&paymentMode=${encodeURIComponent(paymentMode)}`;
    }

    // Fetch data
    try {
        const response = await fetch(apiUrl);
        const data = await response.json();
        
        if (data.success) {
            currentData = data;
            renderReport(data);
        } else {
            await MsgBox.alert('Error: ' + (data.message || 'Failed to load report'));
            document.getElementById('loadingState').style.display = 'none';
        }
    } catch (error) {
        console.error('Error:', error);
        await MsgBox.alert('Failed to load report. Please try again.');
        document.getElementById('loadingState').style.display = 'none';
    }
}

// Render report
function renderReport(data) {
    const { summary, transactions, startDate, endDate } = data;

    // Hide loading, show content
    document.getElementById('loadingState').style.display = 'none';
    document.getElementById('reportContent').style.display = 'block';

    // Update period
    const periodText = `${formatDate(startDate)} to ${formatDate(endDate)}`;
    document.getElementById('reportPeriod').textContent = periodText;

    // Update summary cards
    document.getElementById('totalCashIn').textContent = formatCurrency(summary.totalCashIn);
    document.getElementById('totalCashOut').textContent = formatCurrency(summary.totalCashOut);
    document.getElementById('netCashFlow').textContent = formatCurrency(summary.netCashFlow);
    
    document.getElementById('totalUpiIn').textContent = formatCurrency(summary.totalUpiIn);
    document.getElementById('totalUpiOut').textContent = formatCurrency(summary.totalUpiOut);
    document.getElementById('netUpiFlow').textContent = formatCurrency(summary.netUpiFlow);
    
    document.getElementById('totalTransactions').textContent = summary.totalTransactions;
    document.getElementById('netTotalFlow').textContent = formatCurrency(summary.netTotalFlow);

    // Update sub-details
    document.getElementById('salesCash').textContent = formatCurrency(summary.salesCash);
    document.getElementById('salesUpi').textContent = formatCurrency(summary.salesUpi);
    document.getElementById('customerPaymentsCash').textContent = formatCurrency(summary.customerPaymentsCash);
    document.getElementById('customerPaymentsUpi').textContent = formatCurrency(summary.customerPaymentsUpi);
    
    document.getElementById('purchasesCash').textContent = formatCurrency(summary.purchasesCash);
    document.getElementById('purchasesUpi').textContent = formatCurrency(summary.purchasesUpi);
    document.getElementById('supplierPaymentsCash').textContent = formatCurrency(summary.supplierPaymentsCash);
    document.getElementById('supplierPaymentsUpi').textContent = formatCurrency(summary.supplierPaymentsUpi);
    document.getElementById('expensesCash').textContent = formatCurrency(summary.expensesCash);
    document.getElementById('expensesUpi').textContent = formatCurrency(summary.expensesUpi);

    // Color code net flows
    const netCashElement = document.getElementById('netCashFlow');
    const netUpiElement = document.getElementById('netUpiFlow');
    const netTotalElement = document.getElementById('netTotalFlow');
    
    netCashElement.className = summary.netCashFlow >= 0 ? 'amount amount-positive' : 'amount amount-negative';
    netUpiElement.className = summary.netUpiFlow >= 0 ? 'amount amount-positive' : 'amount amount-negative';
    netTotalElement.className = summary.netTotalFlow >= 0 ? 'amount amount-positive' : 'amount amount-negative';

    // Render transactions table
    renderTransactionsTable(transactions);

    // Update footer totals
    document.getElementById('totalCashInFooter').textContent = formatCurrency(summary.totalCashIn);
    document.getElementById('totalCashOutFooter').textContent = formatCurrency(summary.totalCashOut);
    document.getElementById('totalUpiInFooter').textContent = formatCurrency(summary.totalUpiIn);
    document.getElementById('totalUpiOutFooter').textContent = formatCurrency(summary.totalUpiOut);
    document.getElementById('netCashFlowFooter').textContent = formatCurrency(summary.netCashFlow);
    document.getElementById('netUpiFlowFooter').textContent = formatCurrency(summary.netUpiFlow);
}

// Render transactions table
function renderTransactionsTable(transactions) {
    const tbody = document.getElementById('transactionsTableBody');
    document.getElementById('transactionCount').textContent = transactions.length;

    if (!transactions.length) {
        tbody.innerHTML = '<tr><td colspan="10" class="no-data">No transactions found for the selected period and filters.</td></tr>';
        return;
    }

    let rows = '';
    let serialNo = 1;

    transactions.forEach(txn => {
        const badgeClass = getBadgeClass(txn.TransactionType);
        
        rows += `
            <tr>
                <td class="text-center">${serialNo++}</td>
                <td>${formatDate(txn.TransactionDate)}</td>
                <td>
                    <span class="transaction-type-badge ${badgeClass}">
                        ${txn.TransactionType.replace('-', ' ')}
                    </span>
                </td>
                <td>${txn.Reference || '-'}</td>
                <td>
                    <strong>${txn.Party}</strong>
                    ${txn.PartyCode !== '-' ? '<br><small style="color: #64748b;">' + txn.PartyCode + '</small>' : ''}
                </td>
                <td>${txn.Description || '-'}</td>
                <td class="text-right ${txn.CashIn > 0 ? 'amount-positive' : ''}">${txn.CashIn > 0 ? formatCurrency(txn.CashIn) : '-'}</td>
                <td class="text-right ${txn.CashOut > 0 ? 'amount-negative' : ''}">${txn.CashOut > 0 ? formatCurrency(txn.CashOut) : '-'}</td>
                <td class="text-right ${txn.UpiIn > 0 ? 'amount-upi' : ''}">${txn.UpiIn > 0 ? formatCurrency(txn.UpiIn) : '-'}</td>
                <td class="text-right ${txn.UpiOut > 0 ? 'amount-upi' : ''}">${txn.UpiOut > 0 ? formatCurrency(txn.UpiOut) : '-'}</td>
            </tr>
        `;
    });

    tbody.innerHTML = rows;
}

// Get badge class for transaction type
function getBadgeClass(type) {
    const badgeMap = {
        'SALES': 'badge-sales',
        'SALES-RETURN': 'badge-sales-return',
        'CUSTOMER-PAYMENT': 'badge-customer-payment',
        'PURCHASE': 'badge-purchase',
        'PURCHASE-RETURN': 'badge-purchase-return',
        'SUPPLIER-PAYMENT': 'badge-supplier-payment',
        'EXPENSE': 'badge-expense'
    };
    return badgeMap[type] || 'badge-sales';
}

// Open print view
async function openPrintView() {
    if (!currentData) {
        await MsgBox.alert('Please generate a report first');
        return;
    }

    const startDate = document.getElementById('startDate').value;
    const endDate = document.getElementById('endDate').value;
    const transactionType = document.getElementById('transactionTypeFilter').value;
    const paymentMode = document.getElementById('paymentModeFilter').value;

    let printUrl = `print-cash-flow.php?startDate=${startDate}&endDate=${endDate}`;
    if (transactionType) {
        printUrl += `&transactionType=${encodeURIComponent(transactionType)}`;
    }
    if (paymentMode) {
        printUrl += `&paymentMode=${encodeURIComponent(paymentMode)}`;
    }

    window.open(printUrl, '_blank');
}

// Export to Excel
async function exportToExcel() {
    if (!currentData) {
        await MsgBox.alert('Please generate a report first');
        return;
    }

    const { transactions, summary, startDate, endDate } = currentData;
    
    // Create workbook
    let csv = 'UZRS Inventory System - Master Cash Flow Report\n';
    csv += `Period: ${formatDate(startDate)} to ${formatDate(endDate)}\n\n`;
    
    // Summary section
    csv += 'SUMMARY\n';
    csv += `Total Cash In,${summary.totalCashIn}\n`;
    csv += `Total Cash Out,${summary.totalCashOut}\n`;
    csv += `Net Cash Flow,${summary.netCashFlow}\n`;
    csv += `Total UPI In,${summary.totalUpiIn}\n`;
    csv += `Total UPI Out,${summary.totalUpiOut}\n`;
    csv += `Net UPI Flow,${summary.netUpiFlow}\n`;
    csv += `Net Total Flow,${summary.netTotalFlow}\n`;
    csv += `Total Transactions,${summary.totalTransactions}\n\n`;
    
    // Transactions table header
    csv += 'TRANSACTIONS\n';
    csv += 'S.No,Date,Type,Reference,Party,Party Code,Description,Cash In,Cash Out,UPI In,UPI Out\n';
    
    // Transactions data
    transactions.forEach((txn, index) => {
        csv += `${index + 1},`;
        csv += `${formatDate(txn.TransactionDate)},`;
        csv += `${txn.TransactionType},`;
        csv += `${txn.Reference || '-'},`;
        csv += `"${txn.Party}",`;
        csv += `${txn.PartyCode},`;
        csv += `"${txn.Description || '-'}",`;
        csv += `${txn.CashIn || 0},`;
        csv += `${txn.CashOut || 0},`;
        csv += `${txn.UpiIn || 0},`;
        csv += `${txn.UpiOut || 0}\n`;
    });
    
    // 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', `Cash_Flow_Report_${startDate}_to_${endDate}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    // Set default date range (current month)
    const today = new Date();
    const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
    
    document.getElementById('startDate').value = firstDay.toISOString().split('T')[0];
    document.getElementById('endDate').value = today.toISOString().split('T')[0];
    
    // Auto-load report
    loadReport();
});
