/**
 * Facilities Module JavaScript
 */
(function() {
    'use strict';

    // Auto-init Select2 on tab show for modals
    document.addEventListener('shown.bs.tab', function() {
        if ($.fn.select2) {
            $('.select2:not(.select2-hidden-accessible)').select2({
                theme: 'bootstrap-5',
                width: '100%'
            });
        }
    });

    // Auto-reload DataTables after successful AJAX form submission in modals
    document.addEventListener('submit', function(e) {
        var form = e.target;
        if (form.closest('.modal') && form.getAttribute('data-ajax') === 'true') {
            var modal = form.closest('.modal');
            // Listen for the success response to reload tables
            var origSuccess = null;
            setTimeout(function() {
                // After form submit processes, check for success and reload
                var tables = document.querySelectorAll('.tab-pane.active table[id]');
                tables.forEach(function(tbl) {
                    if (DataTableHelper.instances && DataTableHelper.instances[tbl.id]) {
                        setTimeout(function() {
                            DataTableHelper.reload(tbl.id);
                        }, 1500);
                    }
                });
            }, 500);
        }
    });

})();