// Location-wise Sales Report JavaScript

let currentReportData = null;

// Initialize Select2 on page load
$(document).ready(function() {
    // Initialize Select2 for better dropdowns
    $('#locationFilter, #customerFilter, #salesTypeFilter').select2({
        theme: 'bootstrap-5',
        width: '100%'
    });
    
    // Set default to "This Month"
    setQuickFilter('thisMonth');
});

// Quick filter functions
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 = formatDate(today);
            document.getElementById('customDatesRow').style.display = 'none';
            break;
            
        case 'yesterday':
            const yesterday = new Date(today);
            yesterday.setDate(yesterday.getDate() - 1);
            startDate = endDate = formatDate(yesterday);
            document.getElementById('customDatesRow').style.display = 'none';
            break;
            
        case 'thisWeek':
            const weekStart = new Date(today);
            weekStart.setDate(today.getDate() - today.getDay());
            startDate = formatDate(weekStart);
            endDate = formatDate(today);
            document.getElementById('customDatesRow').style.display = 'none';
            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 = formatDate(lastWeekStart);
            endDate = formatDate(lastWeekEnd);
            document.getElementById('customDatesRow').style.display = 'none';
            break;
            
        case 'thisMonth':
            startDate = formatDate(new Date(today.getFullYear(), today.getMonth(), 1));
            endDate = formatDate(new Date(today.getFullYear(), today.getMonth() + 1, 0));
            document.getElementById('customDatesRow').style.display = 'none';
            break;
            
        case 'lastMonth':
            startDate = formatDate(new Date(today.getFullYear(), today.getMonth() - 1, 1));
            endDate = formatDate(new Date(today.getFullYear(), today.getMonth(), 0));
            document.getElementById('customDatesRow').style.display = 'none';
            break;
            
        case 'thisYear':
            startDate = formatDate(new Date(today.getFullYear(), 0, 1));
            endDate = formatDate(today);
            document.getElementById('customDatesRow').style.display = 'none';
            break;
            
        case 'custom':
            document.getElementById('customDatesRow').style.display = 'flex';
            return; // Don't set dates or load report for custom
    }
    
    document.getElementById('startDate').value = startDate;
    document.getElementById('endDate').value = endDate;
    
    // Auto-load report for quick filters
    if (filter !== 'custom') {
        loadReport();
    }
}

function formatDate(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}`;
}

async function loadReport() {
    const startDate = document.getElementById('startDate').value;
    const endDate = document.getElementById('endDate').value;
    const location = document.getElementById('locationFilter').value;
    const customerId = document.getElementById('customerFilter').value;
    const salesType = document.getElementById('salesTypeFilter').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-location-wise-sales.php?startDate=${startDate}&endDate=${endDate}`;
    
    if (location) {
        apiUrl += `&location=${encodeURIComponent(location)}`;
    }
    if (customerId) {
        apiUrl += `&customerId=${encodeURIComponent(customerId)}`;
    }
    if (salesType) {
        apiUrl += `&salesType=${encodeURIComponent(salesType)}`;
    }
    
    try {
        const response = await fetch(apiUrl);
        const data = await response.json();
        
        if (data.success) {
            currentReportData = data;
            renderReport(data);
        } else {
            await MsgBox.alert('Error: ' + data.message);
            document.getElementById('loadingState').style.display = 'none';
        }
    } catch (error) {
        console.error('Error:', error);
        await MsgBox.alert('Failed to load report data');
        document.getElementById('loadingState').style.display = 'none';
    }
}

function renderReport(data) {
    const { summary, locations, startDate, endDate } = data;
    
    // Hide loading, show content
    document.getElementById('loadingState').style.display = 'none';
    document.getElementById('reportContent').style.display = 'block';
    
    // Update report period
    const periodText = `${formatDisplayDate(startDate)} to ${formatDisplayDate(endDate)}`;
    document.getElementById('reportPeriod').textContent = periodText;
    
    // Update summary cards
    document.getElementById('totalLocations').textContent = summary.totalLocations;
    document.getElementById('totalCustomers').textContent = summary.totalCustomers;
    document.getElementById('totalBills').textContent = summary.totalBills;
    document.getElementById('totalAmount').textContent = formatCurrency(summary.totalAmount);
    document.getElementById('totalDiscount').textContent = formatCurrency(summary.totalDiscount);
    document.getElementById('totalSales').textContent = formatCurrency(summary.totalSales);
    document.getElementById('totalProfit').textContent = formatCurrency(summary.totalProfit);
    document.getElementById('avgProfitMargin').textContent = summary.avgProfitMargin.toFixed(2) + '%';
    
    // Render locations table
    renderLocationsTable(locations, summary);
}

function renderLocationsTable(locations, summary) {
    const tbody = document.getElementById('locationsTableBody');
    
    document.getElementById('locationCount').textContent = `(${locations.length})`;
    
    if (locations.length === 0) {
        tbody.innerHTML = '<tr><td colspan="11" class="no-data">No data found for the selected period and filters.</td></tr>';
    } else {
        let html = '';
        let serialNo = 1;
        
        locations.forEach(loc => {
            const profitMargin = loc.TotalSales > 0 ? ((loc.TotalProfit / loc.TotalSales) * 100) : 0;
            
            let marginClass = '';
            if (profitMargin >= 20) {
                marginClass = 'profit-high';
            } else if (profitMargin >= 10) {
                marginClass = 'profit-medium';
            } else if (profitMargin > 0) {
                marginClass = 'profit-low';
            } else {
                marginClass = 'profit-negative';
            }
            
            html += `
                <tr>
                    <td class="text-center">${serialNo++}</td>
                    <td><strong>${loc.Location}</strong></td>
                    <td class="text-center">${loc.TotalCustomers}</td>
                    <td class="text-center">${loc.TotalBills}</td>
                    <td class="text-right">${formatNumber(loc.TotalQuantity)}</td>
                    <td class="text-right">${formatCurrency(loc.TotalAmount)}</td>
                    <td class="text-right">${formatCurrency(loc.TotalDiscount)}</td>
                    <td class="text-right amount-highlight">${formatCurrency(loc.TotalSales)}</td>
                    <td class="text-right profit-amount">${formatCurrency(loc.TotalProfit)}</td>
                    <td class="text-right ${marginClass}">${profitMargin.toFixed(2)}%</td>
                    <td class="text-center">
                        <button class="btn-view-details" onclick="viewLocationDetails('${loc.Location}')" title="View Details">
                            <i class="fas fa-eye"></i>
                        </button>
                    </td>
                </tr>
            `;
        });
        
        tbody.innerHTML = html;
    }
    
    // Update footer totals
    document.getElementById('totalCustomersFooter').textContent = summary.totalCustomers;
    document.getElementById('totalBillsFooter').textContent = summary.totalBills;
    document.getElementById('totalQuantityFooter').textContent = formatNumber(summary.totalQuantity);
    document.getElementById('totalAmountFooter').textContent = formatCurrency(summary.totalAmount);
    document.getElementById('totalDiscountFooter').textContent = formatCurrency(summary.totalDiscount);
    document.getElementById('totalSalesFooter').textContent = formatCurrency(summary.totalSales);
    document.getElementById('totalProfitFooter').textContent = formatCurrency(summary.totalProfit);
    document.getElementById('avgMarginFooter').textContent = summary.avgProfitMargin.toFixed(2) + '%';
}

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

function formatNumber(num) {
    return Number(num).toLocaleString('en-IN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });
}

function formatDisplayDate(dateStr) {
    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}`;
}

function viewLocationDetails(location) {
    // Set the location filter and reload the report to show details for that location
    $('#locationFilter').val(location).trigger('change');
    loadReport();
}

async function openPrintView() {
    if (!currentReportData) {
        await MsgBox.alert('Please generate the report first');
        return;
    }
    
    const startDate = document.getElementById('startDate').value;
    const endDate = document.getElementById('endDate').value;
    const location = document.getElementById('locationFilter').value;
    const customerId = document.getElementById('customerFilter').value;
    const salesType = document.getElementById('salesTypeFilter').value;
    
    let printUrl = `print-location-wise-sales.php?startDate=${startDate}&endDate=${endDate}`;
    
    if (location) {
        printUrl += `&location=${encodeURIComponent(location)}`;
    }
    if (customerId) {
        printUrl += `&customerId=${encodeURIComponent(customerId)}`;
    }
    if (salesType) {
        printUrl += `&salesType=${encodeURIComponent(salesType)}`;
    }
    
    window.open(printUrl, '_blank');
}

async function exportToExcel() {
    if (!currentReportData) {
        await MsgBox.alert('Please generate the report first');
        return;
    }
    
    const { summary, locations, startDate, endDate } = currentReportData;
    
    // Create CSV content
    let csv = 'Location-wise Sales Report\n';
    csv += `Period: ${formatDisplayDate(startDate)} to ${formatDisplayDate(endDate)}\n\n`;
    
    // Summary
    csv += 'Summary\n';
    csv += `Total Locations,${summary.totalLocations}\n`;
    csv += `Total Customers,${summary.totalCustomers}\n`;
    csv += `Total Bills,${summary.totalBills}\n`;
    csv += `Total Quantity,${summary.totalQuantity}\n`;
    csv += `Gross Amount,${summary.totalAmount}\n`;
    csv += `Total Discount,${summary.totalDiscount}\n`;
    csv += `Net Sales,${summary.totalSales}\n`;
    csv += `Total Profit,${summary.totalProfit}\n`;
    csv += `Profit Margin %,${summary.avgProfitMargin.toFixed(2)}\n\n`;
    
    // Table headers
    csv += 'S.No,Location,Customers,Bills,Quantity,Gross Amount,Discount,Net Sales,Profit,Margin %\n';
    
    // Table data
    let serialNo = 1;
    locations.forEach(loc => {
        const profitMargin = loc.TotalSales > 0 ? ((loc.TotalProfit / loc.TotalSales) * 100) : 0;
        csv += `${serialNo++},"${loc.Location}",${loc.TotalCustomers},${loc.TotalBills},${loc.TotalQuantity},${loc.TotalAmount},${loc.TotalDiscount},${loc.TotalSales},${loc.TotalProfit},${profitMargin.toFixed(2)}\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', `Location_wise_Sales_Report_${startDate}_to_${endDate}.csv`);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}
