
document.addEventListener('DOMContentLoaded', function () {
    const supplierModal = new bootstrap.Modal(document.getElementById('supplierSearchModal'));
    const supplierSearchInput = document.getElementById('supplierModalSearchInput');
    const supplierSelectedLabel = document.getElementById('supplierSelectedLabel');
    const supplierIdInput = document.getElementById('supplier_id');
    let supplierTable;

    // Inicializar DataTable
    function initializeSupplierTable() {
        supplierTable = $('#supplierModalTable').DataTable({
            processing: true,
            serverSide: true,
            ajax: {
                url: "/admin-fit/bill/search-suppliers-dt",
                data: function (d) {
                    d.search.value = supplierSearchInput.value;
                }
            },
            columns: [
                { data: 'supplier_name', name: 'supplier_name' },
                { data: 'rif', name: 'rif', defaultContent: 'N/A' },
                {
                    data: 'id',
                    render: function (data, type, row) {
                        return `<button type="button" class="btn btn-sm btn-primary select-supplier-btn" data-id="${row.id}" data-name="${row.supplier_name}">Seleccionar</button>`;
                    },
                    orderable: false,
                    searchable: false
                }
            ],
            language: {
                url: '//cdn.datatables.net/plug-ins/1.13.7/i18n/es-ES.json',
            },
            searching: false,
            lengthChange: false,
        });
    }

    document.getElementById('openSupplierSearchModal').addEventListener('click', () => {
        supplierModal.show();
        if (!supplierTable) {
            initializeSupplierTable();
        } else {
            supplierTable.ajax.reload();
        }
    });

    supplierSearchInput.addEventListener('keyup', function (e) {
        if (e.key === 'Enter') {
            supplierTable.ajax.reload();
        }
    });

    document.getElementById('supplierModalSearchBtn').addEventListener('click', function () {
        supplierTable.ajax.reload();
    });

    $('#supplierModalTable tbody').on('click', '.select-supplier-btn', function () {
        const supplierId = $(this).data('id');
        const supplierName = $(this).data('name');

        supplierIdInput.value = supplierId;
        supplierSelectedLabel.innerHTML = `<small class="text-muted d-block">Proveedor:</small><span class="fw-bold text-primary">${supplierName}</span>`;

        supplierModal.hide();
    });
});
