// 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;
    const salesType = document.getElementById('salesTypeFilter').value;
    const paymentStatus = document.getElementById('paymentStatusFilter').value;
    
    if (!startDate || !endDate) {
        await MsgBox.alert('Please select start and end dates');
        return;
    }
    
    document.getElementById('loadingState').style.display = 'block';
    document.getElementById('reportContent').style.display = 'none';
    
    let apiUrl = `api/get-bill-wise-sales.php?startDate=${startDate}&endDate=${endDate}`;
    if (customerId) {
        apiUrl += `&customerId=${encodeURIComponent(customerId)}`;
    }
    if (salesType) {
        apiUrl += `&salesType=${encodeURIComponent(salesType)}`;
    }
    if (paymentStatus) {
        apiUrl += `&paymentStatus=${encodeURIComponent(paymentStatus)}`;
    }
    
    try {
        const response = await fetch(apiUrl);
        const data = await response.json();
        
        document.getElementById('loadingState').style.display = 'none';
        if (data.success) {
            renderReport(data);
            document.getElementById('reportContent').style.display = 'block';
        } else {
            await MsgBox.alert('Error loading report: ' + data.message);
        }
    } catch (error) {
        document.getElementById('loadingState').style.display = 'none';
        await MsgBox.alert('Error loading report: ' + error.message);
        console.error('Error:', error);
    }
}

// Render report
function renderReport(data) {
    const { summary, sales, startDate, endDate, customerInfo, salesTypeInfo, paymentStatusInfo } = data;
    
    // Update report period
    let periodText = `${formatDate(startDate)} to ${formatDate(endDate)}`;
    if (customerInfo) {
        periodText += ` - ${customerInfo.CustomerName}`;
    }
    if (salesTypeInfo) {
        periodText += ` - ${salesTypeInfo}`;
    }
    if (paymentStatusInfo) {
        periodText += ` - ${paymentStatusInfo}`;
    }
    document.getElementById('reportPeriod').textContent = periodText;
    
    // Update summary cards
    document.getElementById('totalBills').textContent = summary.totalBills;
    document.getElementById('totalSubTotal').textContent = formatCurrency(summary.totalSubTotal);
    document.getElementById('totalDiscount').textContent = formatCurrency(summary.totalDiscount);
    document.getElementById('totalBillAmount').textContent = formatCurrency(summary.totalBillAmount);
    document.getElementById('totalProfit').textContent = formatCurrency(summary.totalProfit);
    document.getElementById('totalPaid').textContent = formatCurrency(summary.totalPaid);
    document.getElementById('totalUnpaid').textContent = formatCurrency(summary.totalUnpaid);
    document.getElementById('totalCash').textContent = formatCurrency(summary.totalCash);
    
    // Update footer totals
    document.getElementById('totalSubTotalFooter').textContent = formatCurrency(summary.totalSubTotal);
    document.getElementById('totalDiscountFooter').textContent = formatCurrency(summary.totalDiscount);
    document.getElementById('totalBillAmountFooter').textContent = formatCurrency(summary.totalBillAmount);
    document.getElementById('totalProfitFooter').textContent = formatCurrency(summary.totalProfit);
    document.getElementById('totalPaidFooter').textContent = formatCurrency(summary.totalPaid);
    
    // Render sales table
    renderSalesTable(sales);
}

// Render sales table
function renderSalesTable(sales) {
    const tbody = document.getElementById('salesTableBody');
    
    document.getElementById('billCount').textContent = `(${sales.length} bills)`;
    
    if (sales.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="14" class="no-data">No sales found for the selected criteria.</td>
            </tr>
        `;
        return;
    }
    
    let rows = '';
    let serialNo = 1;
    
    sales.forEach(sale => {
        const isReturn = sale.SalesType && sale.SalesType.includes('RETURN');
        
        const typeClass = sale.SalesType === 'GST' ? 'badge-gst' : 
                         sale.SalesType === 'NON-GST' ? 'badge-non-gst' : 
                         sale.SalesType === 'ONLINE' ? 'badge-online' :
                         isReturn ? 'badge-danger' : 'badge-gst';
        
        const salesTypeDisplay = sale.SalesTypeDescription || sale.SalesType || '-';
        
        const paymentStatusClass = sale.PaymentStatus === 'Paid' ? 'badge-paid' : 
                                   sale.PaymentStatus === 'Unpaid' ? 'badge-unpaid' : 
                                   'badge-partial';
        
        // For returns, show negative values
        const multiplier = isReturn ? -1 : 1;
        
        // Payment mode display
        let paymentModeText = '-';
        if (sale.CashAmount > 0 && sale.UpiAmount > 0) {
            paymentModeText = `Cash + UPI`;
        } else if (sale.CashAmount > 0 && sale.CreditAmount > 0) {
            paymentModeText = `Cash + Credit`;
        } else if (sale.UpiAmount > 0 && sale.CreditAmount > 0) {
            paymentModeText = `UPI + Credit`;
        } else if (sale.CashAmount > 0) {
            paymentModeText = 'Cash';
        } else if (sale.UpiAmount > 0) {
            paymentModeText = 'UPI';
        } else if (sale.CreditAmount > 0) {
            paymentModeText = 'Credit';
        } else if (sale.PaymentMode) {
            paymentModeText = sale.PaymentMode;
        }
        
        rows += `
            <tr ${isReturn ? 'style="background-color: #fff5f5;"' : ''}>
                <td class="text-center">${serialNo++}</td>
                <td>${formatDate(sale.SaleDate)}</td>
                <td><strong>${sale.InvoiceNumber}</strong></td>
                <td>
                    ${sale.CustomerName || 'Walk-in Customer'}
                    ${sale.City ? '<br><small style="color: #858796;">' + sale.City + '</small>' : ''}
                </td>
                <td><span class="badge ${typeClass}">${salesTypeDisplay}</span></td>
                <td class="text-center">${sale.ItemCount}</td>
                <td class="text-right ${isReturn ? 'text-danger' : ''}">${formatCurrency(sale.SubTotal * multiplier)}</td>
                <td class="text-right ${isReturn ? 'text-danger' : ''}">${formatCurrency(sale.DiscountAmount * multiplier)}</td>
                <td class="text-right ${isReturn ? 'text-danger' : 'amount-positive'}">${formatCurrency(sale.FinalAmount * multiplier)}</td>
                <td class="text-right ${isReturn ? 'text-danger' : 'text-success'}">${formatCurrency(sale.TotalProfit * multiplier)}</td>
                <td class="text-center"><span class="badge ${paymentStatusClass}">${sale.PaymentStatus}</span></td>
                <td class="text-right">${formatCurrency(sale.PaymentAmount)}</td>
                <td>${paymentModeText}</td>
                <td class="text-center">
                    <button class="action-btn view" onclick="viewBill('${sale.InvoiceNumber}')" title="View Bill">
                        <i class="fas fa-eye"></i>
                    </button>
                    <button class="action-btn print" onclick="printBill('${sale.InvoiceNumber}')" title="Print Bill">
                        <i class="fas fa-print"></i>
                    </button>
                </td>
            </tr>
        `;
    });
    
    tbody.innerHTML = rows;
}

// View bill details
function viewBill(invoiceNumber) {
    window.open(`../Sales/index.php?invoice=${encodeURIComponent(invoiceNumber)}`, '_blank');
}

// Print bill
function printBill(invoiceNumber) {
    window.open(`../Sales/print-invoice.php?invoice=${encodeURIComponent(invoiceNumber)}`, '_blank', 'width=800,height=600');
}

// 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 start and end dates first');
        return;
    }
    
    const table = document.querySelector('.data-table');
    
    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 += '.text-right { text-align: right; }';
    html += '</style>';
    html += '</head>';
    html += '<body>';
    html += '<h2>UZRS Inventory - Bill-wise Sales Report</h2>';
    html += '<p>Period: ' + formatDate(startDate) + ' to ' + formatDate(endDate) + '</p>';
    
    // Clone table and remove action column
    const clonedTable = table.cloneNode(true);
    const headerRow = clonedTable.querySelector('thead tr');
    const lastTh = headerRow.querySelector('th:last-child');
    if (lastTh && lastTh.textContent.includes('Actions')) {
        lastTh.remove();
    }
    
    const bodyRows = clonedTable.querySelectorAll('tbody tr');
    bodyRows.forEach(row => {
        const lastTd = row.querySelector('td:last-child');
        if (lastTd && lastTd.querySelector('.action-btn')) {
            lastTd.remove();
        }
    });
    
    html += clonedTable.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 = 'Bill_Wise_Sales_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;
    const salesType = document.getElementById('salesTypeFilter').value;
    const paymentStatus = document.getElementById('paymentStatusFilter').value;

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

    let printUrl = `print-bill-wise-sales.php?startDate=${startDate}&endDate=${endDate}`;
    if (customerId) {
        printUrl += `&customerId=${encodeURIComponent(customerId)}`;
    }
    if (salesType) {
        printUrl += `&salesType=${encodeURIComponent(salesType)}`;
    }
    if (paymentStatus) {
        printUrl += `&paymentStatus=${encodeURIComponent(paymentStatus)}`;
    }

    window.open(printUrl, '_blank', 'width=1400,height=800');
}

// Open detailed print view
async function openDetailedPrintView() {
    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 paymentStatus = document.getElementById('paymentStatusFilter').value;

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

    let printUrl = `print-detailed-sales.php?startDate=${startDate}&endDate=${endDate}`;
    if (customerId) {
        printUrl += `&customerId=${encodeURIComponent(customerId)}`;
    }
    if (salesType) {
        printUrl += `&salesType=${encodeURIComponent(salesType)}`;
    }
    if (paymentStatus) {
        printUrl += `&paymentStatus=${encodeURIComponent(paymentStatus)}`;
    }

    window.open(printUrl, '_blank', 'width=1400,height=900');
}

// 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'
    });
    
    // Initialize Select2 for sales type filter
    $('#salesTypeFilter').select2({
        placeholder: 'All Types',
        allowClear: true,
        width: '100%',
        theme: 'default'
    });
    
    // Set default to current month
    const today = new Date();
    const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
    const endOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 0);
    
    document.getElementById('startDate').value = formatDateForInput(startOfMonth);
    document.getElementById('endDate').value = formatDateForInput(endOfMonth);
    
    // Load initial report
    loadReport();
});
