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

// Format number
function formatNumber(num) {
    return parseFloat(num).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 categoryId = document.getElementById('categoryFilter').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-category-wise-sales.php?startDate=${startDate}&endDate=${endDate}`;
    if (customerId) {
        apiUrl += `&customerId=${encodeURIComponent(customerId)}`;
    }
    if (salesType) {
        apiUrl += `&salesType=${encodeURIComponent(salesType)}`;
    }
    if (categoryId) {
        apiUrl += `&categoryId=${encodeURIComponent(categoryId)}`;
    }
    
    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, categories, startDate, endDate, customerInfo, salesTypeInfo, categoryInfo } = data;
    
    // Update report period
    let periodText = `${formatDate(startDate)} to ${formatDate(endDate)}`;
    if (categoryInfo) {
        periodText += ` - ${categoryInfo}`;
    }
    if (customerInfo) {
        periodText += ` - ${customerInfo.CustomerName}`;
    }
    if (salesTypeInfo) {
        periodText += ` - ${salesTypeInfo}`;
    }
    document.getElementById('reportPeriod').textContent = periodText;
    
    // Update summary cards
    document.getElementById('totalCategories').textContent = summary.totalCategories;
    document.getElementById('totalItems').textContent = summary.totalItems;
    document.getElementById('totalQuantity').textContent = formatNumber(summary.totalQuantity);
    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) + '%';
    
    // Update footer totals
    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) + '%';
    
    // Render categories table
    renderCategoriesTable(categories, summary);
}

// Render categories table
function renderCategoriesTable(categories, summary) {
    const tbody = document.getElementById('categoriesTableBody');
    
    document.getElementById('categoryCount').textContent = `(${categories.length} categories)`;
    
    if (categories.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="11" class="no-data">No categories found for the selected criteria.</td>
            </tr>
        `;
        return;
    }
    
    let rows = '';
    let serialNo = 1;
    
    categories.forEach(category => {
        // Calculate profit margin
        const profitMargin = category.TotalSales > 0 ? ((category.TotalProfit / category.TotalSales) * 100) : 0;
        
        // Calculate percentage of total sales
        const percentOfTotal = summary.totalSales > 0 ? ((category.TotalSales / summary.totalSales) * 100) : 0;
        
        // Determine profit margin class
        let marginClass = '';
        if (profitMargin >= 20) {
            marginClass = 'text-success';
        } else if (profitMargin >= 10) {
            marginClass = 'text-warning';
        } else if (profitMargin < 10 && profitMargin > 0) {
            marginClass = '';
        } else {
            marginClass = 'text-danger';
        }
        
        rows += `
            <tr>
                <td class="text-center">${serialNo++}</td>
                <td><strong>${category.CategoryName}</strong></td>
                <td class="text-center"><strong>${category.ItemsCount}</strong></td>
                <td class="text-right"><strong>${formatNumber(category.TotalQuantity)}</strong></td>
                <td class="text-right">${formatCurrency(category.AvgRate)}</td>
                <td class="text-right">${formatCurrency(category.TotalAmount)}</td>
                <td class="text-right">${formatCurrency(category.TotalDiscount)}</td>
                <td class="text-right amount-positive">${formatCurrency(category.TotalSales)}</td>
                <td class="text-right text-success">${formatCurrency(category.TotalProfit)}</td>
                <td class="text-right ${marginClass}">${profitMargin.toFixed(2)}%</td>
                <td class="text-center">${percentOfTotal.toFixed(1)}%</td>
            </tr>
        `;
    });
    
    tbody.innerHTML = rows;
}

// 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 - Category-wise Sales 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 = 'Category_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 categoryId = document.getElementById('categoryFilter').value;

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

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

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

// Load report on page load
document.addEventListener('DOMContentLoaded', function() {
    // Initialize Select2 for all dropdowns
    $('#customerFilter').select2({
        placeholder: 'All Customers',
        allowClear: true,
        width: '100%',
        theme: 'default'
    });
    
    $('#salesTypeFilter').select2({
        placeholder: 'All Types',
        allowClear: true,
        width: '100%',
        theme: 'default'
    });
    
    $('#categoryFilter').select2({
        placeholder: 'All Categories',
        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();
});
