document.addEventListener("DOMContentLoaded", function () {
    $(".multi-filter-select").each(function () {
        const $tableEl = $(this);
        const skipColumnsAttr = $tableEl.data("skip-columns");
        const skipColumns = skipColumnsAttr
            ? skipColumnsAttr.toString().split(',').map(Number)
            : [];
        const orderAttr = $tableEl.attr("data-datatables-order");
        const orderConfig = orderAttr ? JSON.parse(orderAttr) : [[0, 'asc']];

        const pageLengthAttr = $tableEl.attr("data-page-length");
        const pageLength = pageLengthAttr ? parseInt(pageLengthAttr, 10) : 10;
        $tableEl.DataTable({
            pageLength: pageLength,
            dom: "<'row'<'col-sm-12 col-md-9'f><'pl-3 col-sm-12 col-md-3'l>>" +
                "<'row'<'col-sm-12'tr>>" +
                "<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
            language: {
                search: "",
                lengthMenu: "Entries _MENU_"
            },
            order: orderConfig,
            initComplete: function () {
                this.api().columns().every(function (index) {
                    if (skipColumns.includes(index)) {
                        return;
                    }

                    const column = this;

                    const select = $('<select class="form-select"><option value=""></option></select>')
                        .appendTo($(column.footer()).empty())
                        .on('change', function () {
                            const val = $.fn.dataTable.util.escapeRegex($(this).val());

                            column.search(val ? '^' + val + '$' : '', true, false).draw();
                        });

                    // Collect unique filter values
                    let uniqueValues = new Set();

                    column.nodes().each(function (cell) {
                        const cleanText = $(cell).data("filter") || $(cell).text().trim();

                        if (cleanText !== "") {
                            uniqueValues.add(cleanText);
                        }
                    });

                    // Sort + append unique values
                    Array.from(uniqueValues).sort().forEach(function (val) {
                        select.append('<option value="' + val + '">' + val + '</option>');
                    });
                });
            }

        });

        // Customize search input
        $tableEl.closest('.dataTables_wrapper').find('[type=search]').each(function () {
            $(this).attr("placeholder", __('search_'));
        });
    });
});