$(document).ready(function() {
    let searchTimeout;
    let currentPage = 1;
    const branchOrder = [3, 5, 2, 4]; // Defined order of branches
    let branchNames = {}; // To store branch ID to Name mapping

    loadInventory(currentPage);

    // =========================================================================
    // CARGA DE DATOS (AJAX)
    // =========================================================================
    function loadInventory(page, searchTerm = '') {
        $.ajax({
            url: 'api/get_inventory.php',
            type: 'GET',
            data: { page: page, term: searchTerm },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    // Store branch names for dynamic headers
                    response.branches.forEach(b => {
                        branchNames[b.id] = b.nombre;
                    });
                    updateInventoryTable(response.products, response.branches);
                    updateInventoryPagination(response.totalPages, response.currentPage);
                    updateInventoryTableInfo(response.currentPage, response.products.length, response.totalRecords);
                } else {
                    showInventoryError(response.message);
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error("Error en AJAX al cargar inventario:", textStatus, errorThrown, jqXHR.responseText);
                showInventoryError(`<b>Error al cargar el inventario.</b><br>Revisa la consola del navegador (F12) para más detalles.`);
            }
        });
    }

    // =========================================================================
    // RENDERIZADO DE LA INTERFAZ
    // =========================================================================
    function updateInventoryTable(products, branches) {
        const tableHeadRow = $('#inventory-table-body').closest('table').find('thead tr');
        const tableBody = $('#inventory-table-body');
        tableBody.empty();

        // Dynamically update table headers for branches
        let branchHeadersHtml = '';
        branchOrder.forEach(branchId => {
            const branchName = branchNames[branchId] || `Sucursal ${branchId}`;
            branchHeadersHtml += `<th>Cantidad en ${branchName} (ID ${branchId})</th>`;
        });
        tableHeadRow.html(`
            <th>Código Producto</th>
            <th>Nombre Comercial</th>
            <th>Laboratorio</th>
            <th>Presentación</th>
            ${branchHeadersHtml}
            <th>Fecha y Hora Actualización</th>
            <th>Fecha Vencimiento</th>
        `);

        if (!products || products.length === 0) {
            tableBody.append('<tr><td colspan="${6 + branchOrder.length}" class="text-center">No se encontraron productos.</td></tr>');
            return;
        }

        const presentationOptions = ['UNIDAD', 'BLISTER', 'CAJA', 'BOLSA', 'BOTE', 'FARDO', 'GALON'];

        products.forEach(function(p) {
            let branchQuantitiesHtml = '';
            let latestUpdate = '';

            branchOrder.forEach(branchId => {
                const inventory = p.inventory[branchId];
                const quantity = inventory ? inventory.quantity : 0;
                const lastUpdated = inventory ? inventory.last_updated : '';
                const isBranch2 = branchId == 2;
                const readonly = isBranch2 ? '' : 'readonly';
                const tdClass = isBranch2 ? 'class="highlight-branch"' : '';

                branchQuantitiesHtml += `<td ${tdClass}><input type="number" class="form-control form-control-sm inventory-quantity" data-product-id="${p.id}" data-branch-id="${branchId}" value="${quantity}" ${readonly}></td>`;
                
                if (lastUpdated && (latestUpdate === '' || lastUpdated > latestUpdate)) {
                    latestUpdate = lastUpdated;
                }
            });

            let presentationSelectHtml = `<select class="form-select form-select-sm inventory-presentation" data-product-id="${p.id}">`;
            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;
                }
            }

            presentationOptions.forEach(option => {
                const selected = (productPresentation === option) ? 'selected' : '';
                presentationSelectHtml += `<option value="${option}" ${selected}>${option}</option>`;
            });
            presentationSelectHtml += '</select>';

            const row = `<tr>
                <td>${p.CodigoInterno || ''}</td>
                <td>${p.NombreComercial || ''}</td>
                <td>${p.laboratorio || ''}</td>
                <td>${presentationSelectHtml}</td>
                ${branchQuantitiesHtml}
                <td data-product-id="${p.id}" data-field="last_updated">${formatDateTime(latestUpdate)}</td>
                <td><input type="date" class="form-control form-control-sm inventory-expiration-date" data-product-id="${p.id}" value="${p.FechaVencimiento || ''}"></td>
                <td><button class="btn btn-primary btn-sm save-inventory-btn" data-product-id="${p.id}" disabled>Guardar</button></td>
            </tr>`;
            tableBody.append(row);
        });
    }

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

    function updateInventoryPagination(totalPages, currentPage) {
        const pagination = $('#inventory-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 showInventoryError(message) {
        $('#inventory-table-body').html(`<tr><td colspan="${5 + branchOrder.length}" class="text-center text-danger">${message}</td></tr>`);
    }

    // =========================================================================
    // MANEJO DE EVENTOS
    // =========================================================================
    $('#search-term').on('keyup', function() {
        clearTimeout(searchTimeout);
        const searchTerm = $(this).val();
        searchTimeout = setTimeout(() => loadInventory(1, searchTerm), 300);
    });

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

    $(document).on('click', '#inventory-pagination .page-link', function(e) {
        e.preventDefault();
        const page = $(this).data('page');
        if (page) {
            currentPage = page;
            loadInventory(currentPage, $('#search-term').val());
        }
    });

    // Handle changes to quantity input fields
    $(document).on('input', '.inventory-quantity', function() {
        $(this).closest('tr').find('.save-inventory-btn').prop('disabled', false);
    });

    // Handle changes to presentation dropdown
    $(document).on('change', '.inventory-presentation', function() {
        $(this).closest('tr').find('.save-inventory-btn').prop('disabled', false);
    });

    // Handle changes to expiration date input
    $(document).on('change', '.inventory-expiration-date', function() {
        $(this).closest('tr').find('.save-inventory-btn').prop('disabled', false);
    });

    // Handle save button click
    $(document).on('click', '.save-inventory-btn', function() {
        const button = $(this);
        const productId = button.data('product-id');
        const row = button.closest('tr');

        const quantities = {};
        row.find('.inventory-quantity').each(function() {
            const branchId = $(this).data('branch-id');
            quantities[branchId] = $(this).val();
        });

        const presentation = row.find('.inventory-presentation').val();
        const expirationDate = row.find('.inventory-expiration-date').val();

        // Send all data for this product to the backend
        updateProductInventory(productId, quantities, presentation, expirationDate, button);
    });

    function updateProductInventory(productId, quantities, presentation, expirationDate, button) {
        button.prop('disabled', true).text('Guardando...');
        $.ajax({
            url: 'api/update_inventory.php',
            type: 'POST',
            data: { productId, quantities, presentation, expirationDate },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    console.log('Inventario del producto actualizado con éxito.');
                    // Update the last_updated cell in the table
                    if (response.last_updated) {
                        const lastUpdatedCell = $(`td[data-product-id="${productId}"][data-field="last_updated"]`);
                        lastUpdatedCell.text(formatDateTime(response.last_updated));
                    }
                    button.text('Guardar');
                } else {
                    console.error('Error al actualizar el inventario del producto:', response.message);
                    alert(response.message || 'Error al actualizar el inventario del producto.');
                    button.prop('disabled', false).text('Guardar');
                }
            }
        });
    }

    // Removed individual updateInventory function

    // =========================================================================
    // FUNCIONES DE UTILIDAD
    // =========================================================================
    function formatDateTime(isoDateTime) {
        // Also check for common MySQL "zero" date value
        if (!isoDateTime || isoDateTime === '0000-00-00 00:00:00' || isoDateTime === '0000-00-00') return '';
        const date = new Date(isoDateTime);
        // Check if date is valid (e.g., if isoDateTime was an invalid date string)
        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}`;
    }
});