/**
 * Savit - Global DataTables Initialization
 * Automatically applies filtering, searching, and sorting to all tables
 * across the platform (Dashboard, Content, Audit, Analytics).
 */
document.addEventListener('DOMContentLoaded', function() {
    // Only initialize if jQuery and DataTables are loaded
    if (typeof jQuery !== 'undefined' && $.fn.DataTable) {
        // Initialize all tables that have the 'table' class but don't have 'no-datatable'
        $('.table:not(.no-datatable)').each(function() {
            // Prevent re-initialization and skip tables with empty headers
            if (!$.fn.DataTable.isDataTable(this) && $(this).find('thead th').length > 0) {
                $(this).DataTable({
                    pageLength: 25,
                    responsive: true,
                    // Auto-detect if table is small and don't paginate
                    bPaginate: $(this).find('tbody tr').length > 10,
                    language: {
                        search: "",
                        searchPlaceholder: "Search records...",
                        lengthMenu: "Show _MENU_"
                    },
                    // Disable sorting on columns with 'no-sort' class
                    columnDefs: [
                        { orderable: false, targets: 'no-sort' }
                    ],
                    // Modern DOM positioning for Bootstrap 5 + DataTables
                    dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>' +
                         '<"row"<"col-sm-12"tr>>' +
                         '<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>',
                    drawCallback: function(settings) {
                        // Re-initialize any bootstrap tooltips in the table after draw
                        if (typeof bootstrap !== 'undefined' && bootstrap.Tooltip) {
                            var tooltipTriggerList = [].slice.call(this[0].querySelectorAll('[data-bs-toggle="tooltip"]'));
                            tooltipTriggerList.map(function (tooltipTriggerEl) {
                                return new bootstrap.Tooltip(tooltipTriggerEl);
                            });
                        }
                    }
                });
            }
        });
    } else {
        console.warn('Savit Tables: jQuery or DataTables not loaded.');
    }
});
