$(document).ready(function() {
    let searchTimeout;
    let currentPage = 1;

    loadInventoryReport(currentPage);

    // =========================================================================
    // CARGA DE DATOS (AJAX)
    // =========================================================================
    function loadInventoryReport(page, searchTerm = '', laboratoryFilter = '', branchFilter = 0, presentationFilter = '') {
        $.ajax({
            url: 'api/get_inventory_report.php',
            type: 'GET',
            data: {
                page: page,
                term: searchTerm,
                laboratory: laboratoryFilter,
                branch: branchFilter,
                presentation: presentationFilter
            },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    updateBranchFilter(response.branches);
                    updateInventoryReportTable(response.report_data);
                    updateInventoryReportPagination(response.totalPages, response.currentPage);
                    updateInventoryReportTableInfo(response.currentPage, response.report_data.length, response.totalRecords);
                } else {
                    showInventoryReportError(response.message);
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error("Error en AJAX al cargar reporte de inventario:", textStatus, errorThrown, jqXHR.responseText);
                showInventoryReportError(`<b>Error al cargar el reporte de inventario.</b><br>Revisa la consola del navegador (F12) para más detalles.`);
            }
        });
    }

    // =========================================================================
    // RENDERIZADO DE LA INTERFAZ
    // =========================================================================
    function updateBranchFilter(branches) {
        const branchFilterSelect = $('#report-branch-filter');
        branchFilterSelect.empty();
        branchFilterSelect.append('<option value="">Todas las Sucursales</option>');
        branches.forEach(branch => {
            branchFilterSelect.append(`<option value="${branch.id}">${branch.nombre}</option>`);
        });
    }

    function updateInventoryReportTable(reportData) {
        const tableBody = $('#inventory-report-table-body');
        tableBody.empty();

        if (!reportData || reportData.length === 0) {
            tableBody.append('<tr><td colspan="9" class="text-center">No se encontraron registros de inventario.</td></tr>'); // Adjusted colspan
            return;
        }

        const branchOrder = [3, 5, 2, 4]; // Defined order of branches (should match backend)
        // presentationOptions is not directly used here for rendering, but kept for context if needed

        reportData.forEach(function(p) { // Renamed item to p for consistency with conteo
            let branchQuantitiesHtml = '';
            let latestUpdate = '';

            branchOrder.forEach(branchId => {
                const inventory = p.inventory[branchId];
                const quantity = inventory ? inventory.quantity : 0;
                const lastUpdated = inventory ? inventory.last_updated : '';
                
                branchQuantitiesHtml += `<td>${quantity}</td>`; // Display quantity, not input field
                
                if (lastUpdated && (latestUpdate === '' || lastUpdated > latestUpdate)) {
                    latestUpdate = lastUpdated;
                }
            });

            let productPresentation = '';
            // Find the presentation from any of the product's inventory entries
            for (let i = 0; i < branchOrder.length; i++) {
                const branchId = branchOrder[i];
                if (p.inventory[branchId] && p.inventory[branchId].presentation) {
                    productPresentation = p.inventory[branchId].presentation;
                    break;
                }
            }

            const row = `<tr>
                <td>${p.CodigoInterno || ''}</td>
                <td>${p.NombreComercial || ''}</td>
                <td>${p.laboratorio || ''}</td>
                <td>${productPresentation || ''}</td>
                ${branchQuantitiesHtml}
                <td>${formatDateTime(latestUpdate)}</td>
            </tr>`;
            tableBody.append(row);
        });
    }

    function updateInventoryReportTableInfo(currentPage, currentCount, totalRecords) {
        const start = (currentPage - 1) * 15 + 1;
        const end = start + currentCount - 1;
        $('#inventory-report-table-info').text(totalRecords > 0 ? `Mostrando ${start} a ${end} de ${totalRecords} registros` : 'Mostrando 0 registros');
    }

    function updateInventoryReportPagination(totalPages, currentPage) {
        const pagination = $('#inventory-report-pagination');
        pagination.empty();
        if (totalPages <= 1) return;

        let paginationHtml = '<ul class="pagination pagination-sm">';
        const maxPagesToShow = 4;
        const startPage = Math.max(1, currentPage - Math.floor(maxPagesToShow / 2));
        const endPage = Math.min(totalPages, startPage + maxPagesToShow - 1);

        paginationHtml += `<li class="page-item ${currentPage === 1 ? 'disabled' : ''}"><a class="page-link" href="#" data-page="${currentPage - 1}">Anterior</a></li>`;

        if (startPage > 1) {
            paginationHtml += '<li class="page-item"><a class="page-link" href="#" data-page="1">1</a></li>';
            if (startPage > 2) {
                paginationHtml += '<li class="page-item disabled"><span class="page-link">...</span></li>';
            }
        }

        for (let i = startPage; i <= endPage; i++) {
            paginationHtml += `<li class="page-item ${i === currentPage ? 'active' : ''}"><a class="page-link" href="#" data-page="${i}">${i}</a></li>`;
        }

        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                paginationHtml += '<li class="page-item disabled"><span class="page-link">...</span></li>';
            }
            paginationHtml += `<li class="page-item"><a class="page-link" href="#" data-page="${totalPages}">${totalPages}</a></li>`;
        }

        paginationHtml += `<li class="page-item ${currentPage === totalPages ? 'disabled' : ''}"><a class="page-link" href="#" data-page="${currentPage + 1}">Siguiente</a></li>`;
        paginationHtml += '</ul>';
        pagination.html(paginationHtml);
    }

    function showInventoryReportError(message) {
        $('#inventory-report-table-body').html(`<tr><td colspan="9" class="text-center text-danger">${message}</td></tr>`); // Adjusted colspan
    }

    // =========================================================================
    // MANEJO DE EVENTOS
    // =========================================================================
    $('#report-search-term, #report-laboratory-filter').on('keyup', function() {
        clearTimeout(searchTimeout);
        const searchTerm = $('#report-search-term').val();
        const laboratoryFilter = $('#report-laboratory-filter').val();
        const branchFilter = $('#report-branch-filter').val();
        const presentationFilter = $('#report-presentation-filter').val();
        searchTimeout = setTimeout(() => loadInventoryReport(1, searchTerm, laboratoryFilter, branchFilter, presentationFilter), 300);
    });

    $('#report-branch-filter, #report-presentation-filter').on('change', function() {
        const searchTerm = $('#report-search-term').val();
        const laboratoryFilter = $('#report-laboratory-filter').val();
        const branchFilter = $('#report-branch-filter').val();
        const presentationFilter = $('#report-presentation-filter').val();
        loadInventoryReport(1, searchTerm, laboratoryFilter, branchFilter, presentationFilter);
    });

    $(document).on('click', '#inventory-report-pagination .page-link', function(e) {
        e.preventDefault();
        const page = $(this).data('page');
        if (page) {
            currentPage = page;
            const searchTerm = $('#report-search-term').val();
            const laboratoryFilter = $('#report-laboratory-filter').val();
            const branchFilter = $('#report-branch-filter').val();
            const presentationFilter = $('#report-presentation-filter').val();
            loadInventoryReport(currentPage, searchTerm, laboratoryFilter, branchFilter, presentationFilter);
        }
    });

    // Prevent form submission on Enter key for filter form
    $('#inventory-report-filter-form').on('submit', function(e) {
        e.preventDefault();
    });

    // Export button click handler
    $('#export-inventory-btn').on('click', function() {
        const searchTerm = $('#report-search-term').val();
        const laboratoryFilter = $('#report-laboratory-filter').val();
        const branchFilter = $('#report-branch-filter').val();
        const presentationFilter = $('#report-presentation-filter').val();

        // Construct the URL for export
        const exportUrl = `api/export_inventory_report.php?term=${searchTerm}&laboratory=${laboratoryFilter}&branch=${branchFilter}&presentation=${presentationFilter}`;
        window.location.href = exportUrl;
    });

    // =========================================================================
    // FUNCIONES DE UTILIDAD (reused from inventory.js)
    // =========================================================================
    function formatDateTime(isoDateTime) {
        if (!isoDateTime || isoDateTime === '0000-00-00 00:00:00' || isoDateTime === '0000-00-00') return '';
        const date = new Date(isoDateTime);
        if (isNaN(date.getTime())) return '';

        const day = String(date.getDate()).padStart(2, '0');
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const year = date.getFullYear();
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        return `${day}/${month}/${year} ${hours}:${minutes}`;
    }
});