$(document).ready(function() {
    let searchTimeout;

    loadProducts(1);

    // =========================================================================
    // CARGA DE DATOS (AJAX)
    // =========================================================================
    function loadProducts(page, searchTerm = '') {
        $.ajax({
            url: 'api/get_products.php',
            type: 'GET',
            data: { page: page, term: searchTerm },
            dataType: 'json',
            success: function(response) {
                if (response) {
                    updateTable(response.products);
                    updatePagination(response.totalPages, response.currentPage);
                    updateTableInfo(response.currentPage, response.products.length, response.totalRecords);
                } else {
                    showError('La respuesta del servidor está vacía.');
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error("Error en AJAX:", textStatus, errorThrown, jqXHR.responseText);
                showError(`<b>Error al cargar los productos.</b><br>Revisa la consola del navegador (F12) para más detalles.`);
            }
        });
    }

    // =========================================================================
    // RENDERIZADO DE LA INTERFAZ
    // =========================================================================
    function updateTable(products) {
        const tableBody = $('#products-table-body');
        tableBody.empty();

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

        products.forEach(function(p) {
            const codes = `Interno<br><strong class="editable" data-field="CodigoInterno" data-id="${p.id}">${p.CodigoInterno || 'N/A'}</strong><br>
                           Barras<br><strong class="editable" data-field="CodigoBarra" data-id="${p.id}">${p.CodigoBarra || 'N/A'}</strong>`;
            const exentoText = p.exento_iva == 1 ? 'Sí' : 'No';
            const exentoClass = p.exento_iva == 1 ? 'badge bg-success' : 'badge bg-secondary';

            const row = `<tr>
                <td>${codes}</td>
                <td class="editable" data-field="NombreComercial" data-id="${p.id}">${p.NombreComercial || ''}</td>
                <td class="editable" data-field="NombreGenerico" data-id="${p.id}">${p.NombreGenerico || ''}</td>
                <td class="editable" data-field="laboratorio" data-id="${p.id}">${p.laboratorio || ''}</td>
                <td class="editable text-end" data-field="CostoUnidad" data-id="${p.id}">${formatCurrency(p.CostoUnidad)}</td>
                <td class="editable text-end" data-field="CostoBlister" data-id="${p.id}">${formatCurrency(p.CostoBlister)}</td>
                <td class="editable text-end" data-field="CostoMayor" data-id="${p.id}">${formatCurrency(p.CostoMayor)}</td>
                <td class="editable text-end" data-field="CostoMixto" data-id="${p.id}">${formatCurrency(p.CostoMixto)}</td>
                <td class="editable text-end" data-field="PrecioVentaUnidad" data-id="${p.id}">${formatCurrency(p.PrecioVentaUnidad)}</td>
                <td class="editable text-end" data-field="PrecioVentaBlister" data-id="${p.id}">${formatCurrency(p.PrecioVentaBlister)}</td>
                <td class="editable text-end" data-field="PrecioVentaMayor" data-id="${p.id}">${formatCurrency(p.PrecioVentaMayor)}</td>
                <td class="editable text-end" data-field="PrecioVentaMixto" data-id="${p.id}">${formatCurrency(p.PrecioVentaMixto)}</td>
                <td class="editable" data-field="FechaIngreso" data-id="${p.id}">${formatDateToDMY(p.FechaIngreso)}</td>
                <td class="editable" data-field="FechaVencimiento" data-id="${p.id}">${formatDateToDMY(p.FechaVencimiento)}</td>
                <td class="editable text-center" data-field="existencia" data-id="${p.id}">${p.existencia}</td>
                <td class="text-center"><span class="${exentoClass} toggle-iva" data-id="${p.id}" data-value="${p.exento_iva}" style="cursor:pointer;">${exentoText}</span></td>
            </tr>`;
            tableBody.append(row);
        });
    }

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

    function updatePagination(totalPages, currentPage) {
        const pagination = $('#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 showError(message) {
        $('#products-table-body').html(`<tr><td colspan="16" class="text-center text-danger">${message}</td></tr>`);
    }

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

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

    // Edición en línea para campos que no son de fecha
    $(document).on('click', '.editable:not([data-field="FechaIngreso"]):not([data-field="FechaVencimiento"])', function() {
        $(this).attr('contenteditable', 'true').focus();
    });

    $(document).on('blur', '.editable:not([data-field="FechaIngreso"]):not([data-field="FechaVencimiento"])', function() {
        $(this).attr('contenteditable', 'false');
        const field = $(this).data('field');
        const id = $(this).data('id');
        let value = $(this).text();

        $.ajax({
            url: 'api/update_product.php',
            type: 'POST',
            data: { id, field, value },
            dataType: 'json',
            success: (response) => {
                if (response.success) {
                    $(this).addClass('bg-success-light');
                    setTimeout(() => $(this).removeClass('bg-success-light'), 2000);
                } else {
                    alert(response.message || 'Error al actualizar.');
                }
            }
        });
    });

    // Edición con calendario para fechas
    $(document).on('click', '.editable[data-field="FechaIngreso"], .editable[data-field="FechaVencimiento"]', function() {
        const td = $(this);
        if (td.find('input').length > 0) return;

        const originalDate = td.text();
        const isoDate = formatDateToISO(originalDate);
        const id = td.data('id');
        const field = td.data('field');

        td.html(`<input type="date" class="form-control form-control-sm" value="${isoDate}">`);
        const input = td.find('input');
        input.focus();

        input.on('blur', function() {
            const newValue = $(this).val();
            $.ajax({
                url: 'api/update_product.php',
                type: 'POST',
                data: { id, field, value: newValue },
                dataType: 'json',
                success: (response) => {
                    if (response.success) {
                        td.html(formatDateToDMY(newValue));
                        td.addClass('bg-success-light');
                        setTimeout(() => td.removeClass('bg-success-light'), 2000);
                    } else {
                        alert(response.message || 'Error al actualizar.');
                        td.html(originalDate);
                    }
                }
            });
        });
    });
    
    $(document).on('click', '.toggle-iva', function() {
        const span = $(this);
        const id = span.data('id');
        const newValue = span.data('value') == 1 ? 0 : 1;
        
        $.ajax({
            url: 'api/update_product.php',
            type: 'POST',
            data: { id: id, field: 'exento_iva', value: newValue },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    span.data('value', newValue).text(newValue == 1 ? 'Sí' : 'No').toggleClass('bg-success bg-secondary');
                } else {
                    alert(response.message || 'Error al cambiar el estado de IVA.');
                }
            }
        });
    });

    $('#add-product-form').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            url: 'api/create_product.php',
            type: 'POST',
            data: $(this).serialize(),
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    $('#addProductModal').modal('hide');
                    $('#add-product-form')[0].reset();
                    loadProducts(1);
                } else {
                    alert(response.message || 'Error al crear el producto.');
                }
            }
        });
    });

    // =========================================================================
    // FUNCIONES DE UTILIDAD
    // =========================================================================
    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 `${day}/${month}/${year}`;
    }

    function formatDateToISO(dmyDate) {
        if (!dmyDate) return null;
        const parts = dmyDate.split('/');
        if (parts.length !== 3) return null;
        const [day, month, year] = parts;
        if (isNaN(day) || isNaN(month) || isNaN(year) || day.length !== 2 || month.length !== 2 || year.length !== 4) return null;
        return `${year}-${month}-${day}`;
    }
    
    function formatCurrency(value) {
        if (value === null || value === undefined) return '0.00';
        return parseFloat(value).toFixed(2);
    }
});
