$(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>
            <th>Acciones</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 isBranch4 = branchId == 4; // Sucursal 4 es la editable
                const readonly = isBranch4 ? '' : 'readonly';
                const tdClass = isBranch4 ? '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 = (option === productPresentation) ? 'selected' : '';
                presentationSelectHtml += `<option value="${option}" ${selected}>${option}</option>`;
            });
            presentationSelectHtml += '</select>';

            const formattedDate = p.FechaVencimiento ? formatDateToDMY(p.FechaVencimiento) : '';
            const row = `
                <tr data-product-id="${p.id}">
                    <td>${p.CodigoInterno}</td>
                    <td>${p.NombreComercial}</td>
                    <td>${p.laboratorio}</td>
                    <td>${presentationSelectHtml}</td>
                    ${branchQuantitiesHtml}
                    <td>${formatDateTime(latestUpdate)}</td>
                    <td><input type="date" class="form-control form-control-sm inventory-expiration" 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}">Guardar</button></td>
                </tr>
            `;
            tableBody.append(row);
        });
    }

    function updateInventoryPagination(totalPages, currentPage) {
        const paginationContainer = $('#inventory-pagination');
        paginationContainer.empty();
        if (totalPages > 1) {
            const paginationHtml = `
                <ul class="pagination pagination-sm">
                    <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                        <a class="page-link" href="#" data-page="${currentPage - 1}">Anterior</a>
                    </li>
                    ${Array.from({ length: totalPages }, (_, i) => `
                        <li class="page-item ${currentPage === i + 1 ? 'active' : ''}">
                            <a class="page-link" href="#" data-page="${i + 1}">${i + 1}</a>
                        </li>
                    `).join('')}
                    <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                        <a class="page-link" href="#" data-page="${currentPage + 1}">Siguiente</a>
                    </li>
                </ul>
            `;
            paginationContainer.html(paginationHtml);
        }
    }

    function updateInventoryTableInfo(currentPage, productsCount, totalRecords) {
        $('#inventory-table-info').text(`Mostrando ${productsCount} de ${totalRecords} registros (Página ${currentPage})`);
    }

    function showInventoryError(message) {
        const errorHtml = `
            <div class="alert alert-danger" role="alert">
                <i class="fas fa-exclamation-triangle"></i>
                ${message}
            </div>
        `;
        $('#inventory-table-body').empty().append(`<tr><td colspan="10" class="text-center p-4">${errorHtml}</td></tr>`);
        $('#inventory-pagination').empty();
        $('#inventory-table-info').empty();
    }

    // =========================================================================
    // MANEJADORES DE EVENTOS
    // =========================================================================
    $('#inventory-filter-form').on('input', '#search-term', function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            const searchTerm = $(this).val();
            loadInventory(1, searchTerm);
        }, 500);
    });

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

    // Handle saving inventory changes
    $(document).on('click', '.save-inventory-btn', function() {
        const button = $(this);
        button.prop('disabled', true).text('Guardando...'); // Deshabilita el botón y cambia el texto
        const productId = button.data('product-id');
        const row = button.closest('tr');

        // Find quantities for editable branch
        const quantities = {};
        row.find('.inventory-quantity').each(function() {
            const branchId = $(this).data('branch-id');
            const quantity = $(this).val();
            if (branchId == 4) { // Only send quantity for branch 4
                quantities[branchId] = quantity;
            }
        });

        // Find presentation
        const presentation = row.find('.inventory-presentation').val();

        // Find expiration date
        const expirationDate = row.find('.inventory-expiration').val();
        
        $.ajax({
            url: 'api/update_inventory.php',
            type: 'POST',
            data: {
                productId: productId,
                quantities: quantities,
                presentation: presentation,
                expirationDate: expirationDate
            },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    // Éxito: vuelve a habilitar el botón y cambia el texto a "Guardado" por un momento
                    button.text('Guardado').addClass('btn-success').removeClass('btn-primary');
                    setTimeout(() => {
                        button.prop('disabled', false).text('Guardar').removeClass('btn-success').addClass('btn-primary');
                    }, 2000); // Vuelve al estado original después de 2 segundos

                    // Opcionalmente, actualiza la hora de la última actualización sin recargar la página
                    const lastUpdatedCell = row.find('td').eq(4 + branchOrder.length);
                    if (response.last_updated) {
                        lastUpdatedCell.text(formatDateTime(response.last_updated));
                    }
                } else {
                    console.error('Error al actualizar el inventario del producto:', response.message);
                    // Error: vuelve a habilitar el botón y muestra "Error"
                    button.text('Error').addClass('btn-danger').removeClass('btn-primary');
                    setTimeout(() => {
                        button.prop('disabled', false).text('Guardar').removeClass('btn-danger').addClass('btn-primary');
                    }, 3000); // Vuelve al estado original después de 3 segundos
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error("Error en AJAX al guardar inventario:", textStatus, errorThrown, jqXHR.responseText);
                button.text('Error').addClass('btn-danger').removeClass('btn-primary');
                setTimeout(() => {
                    button.prop('disabled', false).text('Guardar').removeClass('btn-danger').addClass('btn-primary');
                }, 3000);
            }
        });
    });

    // =========================================================================
    // 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}`;
    }

    function formatDateToDMY(isoDate) {
        if (!isoDate) return '';
        const datePart = isoDate.split(' ')[0];
        const parts = datePart.split('-');
        if (parts.length !== 3) return '';
        const [year, month, day] = parts;
        return `${year}-${month}-${day}`;
    }
});