// Global variables
let currentStockStatus = 'in-stock';

// Initialize on page load
$(document).ready(function() {
    // Initialize Select2 for better dropdowns
    $('#categoryFilter, #brandFilter, #locationFilter, #itemFilter').select2({
        theme: 'bootstrap-5',
        width: '100%',
        placeholder: function() {
            return $(this).data('placeholder');
        },
        allowClear: true
    });

    // Auto-load report on page load with default filter
    loadReport();
});

// Set stock status filter
function setStockFilter(status) {
    currentStockStatus = status;
    
    // Update active button
    document.querySelectorAll('.quick-filter-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    event.target.classList.add('active');
    
    // Auto-load report
    loadReport();
}

// Load report data
async function loadReport() {
    const categoryId = document.getElementById('categoryFilter').value;
    const brandId = document.getElementById('brandFilter').value;
    const locationId = document.getElementById('locationFilter').value;
    const itemCode = document.getElementById('itemFilter').value;

    // Build API URL
    let apiUrl = 'api/get-item-stock-report.php?';
    const params = [];

    if (categoryId) params.push(`categoryId=${encodeURIComponent(categoryId)}`);
    if (brandId) params.push(`brandId=${encodeURIComponent(brandId)}`);
    if (locationId) params.push(`locationId=${encodeURIComponent(locationId)}`);
    if (itemCode) params.push(`itemCode=${encodeURIComponent(itemCode)}`);
    if (currentStockStatus) params.push(`stockStatus=${encodeURIComponent(currentStockStatus)}`);

    apiUrl += params.join('&');

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

    // Fetch data
    try {
        const response = await fetch(apiUrl);
        const data = await response.json();
        
        if (data.success) {
            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, items } = data;

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

    // Update summary cards
    document.getElementById('totalItems').textContent = summary.totalItems;
    document.getElementById('totalOpeningStock').textContent = formatNumber(summary.totalOpeningStock);
    document.getElementById('totalCurrentStock').textContent = formatNumber(summary.totalCurrentStock);
    document.getElementById('totalStockValueCost').textContent = formatCurrency(summary.totalStockValueAtCost);
    document.getElementById('totalStockValueSelling').textContent = formatCurrency(summary.totalStockValueAtSelling);
    document.getElementById('totalPotentialProfit').textContent = formatCurrency(summary.totalPotentialProfit);
    document.getElementById('inStockItems').textContent = summary.inStockItems;
    document.getElementById('lowStockItems').textContent = summary.lowStockItems;
    document.getElementById('outOfStockItems').textContent = summary.outOfStockItems;
    document.getElementById('negativeStockItems').textContent = summary.negativeStockItems;

    // Update footer totals
    document.getElementById('totalOpeningFooter').textContent = formatNumber(summary.totalOpeningStock);
    document.getElementById('totalCurrentFooter').textContent = formatNumber(summary.totalCurrentStock);
    document.getElementById('totalValueFooter').textContent = formatCurrency(summary.totalStockValueAtCost);

    // Render items table
    renderItemsTable(items);
}

// Render items table
function renderItemsTable(items) {
    const tbody = document.getElementById('itemsTableBody');
    document.getElementById('itemCount').textContent = `(${items.length})`;

    if (!items.length) {
        tbody.innerHTML = '<tr><td colspan="14" class="no-data">No items found with the selected filters.</td></tr>';
        return;
    }

    let rows = '';
    let serialNo = 1;

    items.forEach(item => {
        let statusClass = '';
        let statusText = item.StockStatus;

        switch (item.StockStatus) {
            case 'In Stock':
                statusClass = 'status-in-stock';
                break;
            case 'Low Stock':
                statusClass = 'status-low-stock';
                break;
            case 'Out of Stock':
                statusClass = 'status-out-of-stock';
                break;
            case 'Negative':
                statusClass = 'status-negative';
                break;
        }

        rows += `
            <tr>
                <td class="text-center">${serialNo++}</td>
                <td><strong>${escapeHtml(item.ItemCode)}</strong></td>
                <td>${escapeHtml(item.ItemName)}</td>
                <td>${escapeHtml(item.CategoryName || '-')}</td>
                <td>${escapeHtml(item.BrandName || '-')}</td>
                <td>${escapeHtml(item.LocationName || '-')}</td>
                <td class="text-center">${escapeHtml(item.UnitName || '-')}</td>
                <td class="text-right">${formatNumber(item.OpeningStock)}</td>
                <td class="text-right"><strong>${formatNumber(item.CurrentStock)}</strong></td>
                <td class="text-right">${formatNumber(item.AlertQuantity)}</td>
                <td class="text-right">${formatCurrency(item.PurchasePrice)}</td>
                <td class="text-right">${formatCurrency(item.SalesPrice)}</td>
                <td class="text-right"><strong>${formatCurrency(item.StockValueAtCost)}</strong></td>
                <td class="text-center">
                    <span class="status-badge ${statusClass}">${statusText}</span>
                </td>
            </tr>
        `;
    });

    tbody.innerHTML = rows;
}

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

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

// Escape HTML
function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Open print view
function openPrintView() {
    const categoryId = document.getElementById('categoryFilter').value;
    const brandId = document.getElementById('brandFilter').value;
    const locationId = document.getElementById('locationFilter').value;
    const itemCode = document.getElementById('itemFilter').value;

    let printUrl = 'print-item-stock-report.php?';
    const params = [];

    if (categoryId) params.push(`categoryId=${encodeURIComponent(categoryId)}`);
    if (brandId) params.push(`brandId=${encodeURIComponent(brandId)}`);
    if (locationId) params.push(`locationId=${encodeURIComponent(locationId)}`);
    if (itemCode) params.push(`itemCode=${encodeURIComponent(itemCode)}`);
    if (currentStockStatus) params.push(`stockStatus=${encodeURIComponent(currentStockStatus)}`);

    printUrl += params.join('&');

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

// Export to Excel
async function exportToExcel() {
    const table = document.querySelector('.data-table');
    
    if (!table) {
        await MsgBox.alert('No data to export');
        return;
    }

    // Clone table
    const clonedTable = table.cloneNode(true);
    
    // Remove status badges styling for Excel
    clonedTable.querySelectorAll('.status-badge').forEach(badge => {
        badge.className = '';
    });

    // Create workbook
    const wb = XLSX.utils.table_to_book(clonedTable, { sheet: 'Stock Report' });
    
    // Generate filename
    const filename = `Item_Stock_Report_${new Date().toISOString().split('T')[0]}.xlsx`;
    
    // Download
    XLSX.writeFile(wb, filename);
}

// Add SheetJS library dynamically if not present
if (typeof XLSX === 'undefined') {
    const script = document.createElement('script');
    script.src = 'https://cdn.sheetjs.com/xlsx-0.20.0/package/dist/xlsx.full.min.js';
    document.head.appendChild(script);
}
