/**
 * DataTable Helper — Server-side DataTable initialization
 */
const DataTableHelper = {
    instances: {},

    init(tableId, options = {}) {
        const table = document.getElementById(tableId);
        if (!table) return null;

        const url = table.getAttribute('data-url');
        let columns = [];
        try {
            columns = JSON.parse(table.getAttribute('data-columns') || '[]');
        } catch (e) {
            console.error('Invalid data-columns JSON for', tableId);
            return null;
        }

        const defaultOptions = {
            processing: true,
            serverSide: true,
            ajax: {
                url: url,
                type: 'GET',
                data: function(d) {
                    // Append any filter inputs
                    const filterForm = document.querySelector('[data-filter-table="' + tableId + '"]');
                    if (filterForm) {
                        const formData = new FormData(filterForm);
                        for (const [key, value] of formData.entries()) {
                            if (value) d[key] = value;
                        }
                    }
                    return d;
                },
                error: function(xhr) {
                    console.error('DataTable AJAX error:', xhr);
                }
            },
            columns: columns,
            order: [[0, 'desc']],
            pageLength: 25,
            lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
            language: {
                processing: '<div class="spinner-border spinner-border-sm text-primary" role="status"><span class="visually-hidden">Loading...</span></div>',
                emptyTable: 'No data available',
                zeroRecords: 'No matching records found',
            },
            responsive: true,
            stateSave: true,
            dom: '<"row"<"col-sm-6"l><"col-sm-6"f>>rtip',
            drawCallback: function() {
                // Re-init tooltips on redraw
                document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(function(el) {
                    new bootstrap.Tooltip(el);
                });
            }
        };

        const finalOptions = Object.assign({}, defaultOptions, options);
        this.instances[tableId] = $('#' + tableId).DataTable(finalOptions);
        return this.instances[tableId];
    },

    reload(tableId) {
        if (this.instances[tableId]) {
            this.instances[tableId].ajax.reload(null, false);
        }
    },

    getInstance(tableId) {
        return this.instances[tableId] || null;
    }
};