<?php
    // Zero-Breakage: Safely fetch the app version from the root version.php file
    $appVersion = '1.0.0';
    $versionFile = APPROOT . '/version.php';
    if (file_exists($versionFile)) {
        $appVersion = include $versionFile;
    }
?>
        </div>
        <footer class="bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700/70 mt-auto flex-shrink-0 z-20 relative w-full md:h-[84px] flex items-center">
            <div class="<?php echo isLoggedIn() ? 'px-4 md:px-8' : 'container mx-auto px-4'; ?> py-3 flex flex-col md:flex-row justify-between items-center w-full">
                
                <div class="mb-3 md:mb-0 w-full md:w-1/3 text-center md:text-left">
                    <div class="mb-1 text-sm text-gray-600 dark:text-gray-400">
                        Copyright &copy; <?php echo date('Y'); ?> <?php echo $appSettings['app_name'] ?? SITENAME; ?>. All rights reserved.
                    </div>
                    <?php if(isLoggedIn()): ?>
                        <div class="text-[10px] md:text-xs mt-1 text-gray-400 dark:text-gray-500 leading-relaxed">
                            This software is protected by a License Verification System. Should <br class="hidden md:block">
                            any of the source code be tampered with the system will disable itself.
                        </div>
                    <?php endif; ?>
                    <?php if(!isLoggedIn()): ?>
                        <div class="flex space-x-4 mt-1.5 justify-center md:justify-start text-xs md:text-sm text-gray-500">
                            <a href="<?php echo URLROOT; ?>/pages/privacy" class="hover:text-primary transition-colors">Privacy</a>
                            <a href="<?php echo URLROOT; ?>/pages/terms" class="hover:text-primary transition-colors">Terms</a>
                            <a href="<?php echo URLROOT; ?>/pages/contact" class="hover:text-primary transition-colors">Contact</a>
                        </div>
                    <?php endif; ?>
                </div>
                
                <div class="mb-3 md:mb-0 w-full md:w-1/3 flex justify-center items-center">
                    <div class="inline-flex items-center bg-transparent border border-gray-200 dark:border-gray-700 rounded-full px-3 py-1.5 text-xs font-medium shadow-sm">
                        <div class="flex items-center text-primary">
                            <svg class="w-3.5 h-3.5 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6a2 2 0 012-2h12a2 2 0 012 2v12a2 2 0 01-2 2H6a2 2 0 01-2-2V6z"></path>
                                <circle cx="18" cy="6" r="2" fill="currentColor" stroke="none"></circle>
                            </svg>
                            <span class="text-gray-700 dark:text-gray-300">App v<?php echo htmlspecialchars((string)$appVersion); ?></span>
                        </div>
                        <div class="w-px h-3.5 bg-gray-300 dark:bg-gray-600 mx-3"></div>
                        <div class="flex items-center text-primary">
                            <svg class="w-3.5 h-3.5 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4m0 5c0 2.21-3.582 4-8 4s-8-1.79-8-4"></path></svg>
                            <span class="text-gray-700 dark:text-gray-300">DB v<?php echo htmlspecialchars((string)($appSettings['db_version'] ?? '0')); ?></span>
                        </div>
                    </div>
                </div>
                
                <div class="w-full md:w-1/3 flex flex-col items-center md:items-end text-center md:text-right">
                    <div class="flex items-center justify-center md:justify-end text-xs text-sm text-gray-500 dark:text-gray-400 italic">
                        <span>Developed by <a href="https://christodev.co.za" target="_blank" class="hover:text-primary transition-colors font-bold ml-1"><img src="<?php echo URLROOT; ?>/uploads/brand/developed_by.png" alt="Developer Brand" class="h-3.5 md:h-4 object-contain inline-block opacity-80 hover:opacity-100 transition-opacity"></a></span>
                    </div>
                    <div class="text-[10px] md:text-xs mt-1.5 text-gray-400 dark:text-gray-500 font-mono tracking-wide">
                        info@christodev.co.za | +27 61 523 9126
                    </div>
                </div>
                
            </div>
        </footer>
    </main>
<?php if(isLoggedIn()): ?>
    </div>
<?php endif; ?>

    <div id="scroll-progress-container" class="fixed bottom-8 right-8 z-40 hidden items-center justify-center w-12 h-12 bg-white dark:bg-gray-800 rounded-full shadow-lg border border-gray-200 dark:border-gray-700 transition-transform duration-300 transform scale-0 cursor-pointer hover:shadow-xl group" onclick="document.getElementById('main-scroll-area').scrollTo({top: 0, behavior: 'smooth'});" title="Back to top">
        <svg class="w-12 h-12 transform -rotate-90 absolute" viewBox="0 0 36 36">
            <path class="text-gray-100 dark:text-gray-700" stroke-width="3" stroke="currentColor" fill="none" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" />
            <path id="scroll-progress-path" class="text-primary transition-all duration-150 ease-out" stroke-dasharray="100, 100" stroke-dashoffset="100" stroke-width="3" stroke-linecap="round" stroke="currentColor" fill="none" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831" />
        </svg>
        <div class="absolute text-gray-500 dark:text-gray-400 group-hover:text-primary transition-colors">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M5 15l7-7 7 7"></path></svg>
        </div>
    </div>

    <div id="global-confirm-modal" class="fixed inset-0 z-50 hidden items-center justify-center bg-black bg-opacity-60 backdrop-blur-sm transition-opacity">
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-xl border border-gray-200 dark:border-gray-700 p-6 max-w-md w-full mx-4 transform transition-all">
            <h3 id="global-confirm-title" class="text-xl font-bold text-gray-900 dark:text-white mb-2">Confirm Action</h3>
            <p id="global-confirm-text" class="text-gray-600 dark:text-gray-400 mb-6">Are you sure you want to proceed?</p>
            <div class="flex justify-end space-x-3">
                <button type="button" id="global-cancel-btn" class="px-4 py-2 bg-gray-200 hover:bg-gray-300 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-800 dark:text-gray-200 font-bold rounded-lg transition-colors focus:outline-none">Cancel</button>
                <button type="button" id="global-confirm-btn" class="px-4 py-2 bg-red-500 hover:bg-red-600 text-white font-bold rounded-lg transition-colors focus:outline-none focus:ring-4 focus:ring-red-500/50">Confirm</button>
            </div>
        </div>
    </div>

    <div id="global-help-modal" class="fixed inset-0 z-50 hidden items-center justify-center bg-black bg-opacity-60 backdrop-blur-sm transition-opacity">
        <div class="bg-white dark:bg-gray-800 rounded-xl shadow-xl border border-gray-200 dark:border-gray-700 p-6 max-w-2xl w-full mx-4 max-h-[85vh] flex flex-col transform transition-all">
            <div class="flex justify-between items-center mb-4 border-b border-gray-200 dark:border-gray-700 pb-4">
                <h3 class="text-xl font-bold text-gray-900 dark:text-white flex items-center">
                    <div class="p-2 bg-primary/10 rounded-lg mr-3">
                        <svg class="w-6 h-6 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                    </div>
                    <?php echo $data['help_title'] ?? 'Page Guide & Help'; ?>
                </h3>
                <button type="button" id="close-help-modal-btn" class="text-gray-400 hover:text-red-500 focus:outline-none transition-colors">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
                </button>
            </div>
            
            <div class="overflow-y-auto pr-2 prose dark:prose-invert prose-sm max-w-none text-gray-600 dark:text-gray-300">
                <?php if(isset($data['help_content'])): ?>
                    <?php echo $data['help_content']; ?>
                <?php else: ?>
                    <p>Documentation for this specific view is currently being written. Please check back later.</p>
                    <p>If you need immediate assistance with this feature, please use the Developer Support module on the sidebar to open a ticket.</p>
                <?php endif; ?>
            </div>
            
            <div class="mt-6 pt-4 border-t border-gray-200 dark:border-gray-700 flex justify-end">
                <button type="button" id="global-help-close-btn" class="px-6 py-2 bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-800 dark:text-white font-bold rounded-lg transition-colors focus:outline-none focus:ring-4 focus:ring-gray-500/50 shadow-sm">Got it, thanks!</button>
            </div>
        </div>
    </div>

    <div id="pwa-install-prompt" class="fixed bottom-4 left-4 right-4 md:bottom-8 md:left-8 md:w-96 bg-white dark:bg-gray-800 rounded-xl shadow-2xl border border-gray-200 dark:border-gray-700 p-4 z-50 transform transition-transform duration-500 translate-y-[150%] flex items-center justify-between">
        <div class="flex items-center space-x-4 overflow-hidden">
            <img src="<?php echo !empty(getSettings()['favicon']) ? URLROOT . '/uploads/' . getSettings()['favicon'] : URLROOT . '/uploads/brand/icon.png'; ?>" alt="App Icon" class="w-12 h-12 rounded-lg object-contain flex-shrink-0 bg-gray-50 dark:bg-gray-700 p-1">
            <div class="truncate">
                <h4 class="text-sm font-bold text-gray-900 dark:text-white truncate">Install <?php echo htmlspecialchars(getSettings()['app_name'] ?? SITENAME); ?></h4>
                <p class="text-xs text-gray-500 dark:text-gray-400 truncate">Install the app for quick access.</p>
            </div>
        </div>
        <div class="flex items-center space-x-2 ml-4 flex-shrink-0">
            <button id="pwa-cancel-btn" class="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 p-2 rounded-full focus:outline-none">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
            </button>
            <button id="pwa-install-btn" class="bg-primary hover:opacity-90 text-white text-sm font-bold py-2 px-4 rounded-lg shadow-sm transition-colors focus:outline-none focus:ring-2 focus:ring-primary/50">
                Install
            </button>
        </div>
    </div>

    <?php flash('system_msg'); ?>
    
    <script src="<?php echo URLROOT; ?>/js/theme.js"></script>
    <script>
        // PWA Service Worker Registration
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', function() {
                navigator.serviceWorker.register('<?php echo URLROOT; ?>/sw.js').then(function(registration) {
                    console.log('PWA ServiceWorker registered successfully.');
                }).catch(function(err) {
                    console.log('PWA ServiceWorker registration failed: ', err);
                });
            });
        }

        let deferredPrompt;
        const pwaPrompt = document.getElementById('pwa-install-prompt');
        const pwaInstallBtn = document.getElementById('pwa-install-btn');
        const pwaCancelBtn = document.getElementById('pwa-cancel-btn');

        window.addEventListener('beforeinstallprompt', (e) => {
            e.preventDefault(); 
            deferredPrompt = e;
            
            if(localStorage.getItem('pwa_dismissed') !== 'true') {
                setTimeout(() => {
                    pwaPrompt.classList.remove('translate-y-[150%]');
                    pwaPrompt.classList.add('translate-y-0');
                }, 2000); 
            }
        });

        if (pwaInstallBtn) {
            pwaInstallBtn.addEventListener('click', async () => {
                pwaPrompt.classList.remove('translate-y-0');
                pwaPrompt.classList.add('translate-y-[150%]');
                if (deferredPrompt) {
                    deferredPrompt.prompt();
                    const { outcome } = await deferredPrompt.userChoice;
                    deferredPrompt = null;
                }
            });
        }

        if (pwaCancelBtn) {
            pwaCancelBtn.addEventListener('click', () => {
                pwaPrompt.classList.remove('translate-y-0');
                pwaPrompt.classList.add('translate-y-[150%]');
                localStorage.setItem('pwa_dismissed', 'true'); 
            });
        }

        // Global Confirmation Logic
        let formToSubmit = null;
        function confirmAction(event, form, title, message) {
            event.preventDefault();
            formToSubmit = form;
            document.getElementById('global-confirm-title').innerText = title;
            document.getElementById('global-confirm-text').innerText = message;
            
            const modal = document.getElementById('global-confirm-modal');
            modal.classList.remove('hidden');
            modal.classList.add('flex');
        }

        document.getElementById('global-cancel-btn').addEventListener('click', function() {
            const modal = document.getElementById('global-confirm-modal');
            modal.classList.add('hidden');
            modal.classList.remove('flex');
            formToSubmit = null; 
        });

        document.getElementById('global-confirm-btn').addEventListener('click', function() {
            if (formToSubmit) {
                formToSubmit.submit(); 
            }
        });

        // Global Contextual Help Logic
        const helpToggleBtn = document.getElementById('help-toggle-btn');
        const globalHelpModal = document.getElementById('global-help-modal');
        const closeHelpBtn = document.getElementById('close-help-modal-btn');
        const closeHelpBtnBottom = document.getElementById('global-help-close-btn');

        function toggleHelpModal() {
            if (globalHelpModal) {
                if (globalHelpModal.classList.contains('hidden')) {
                    globalHelpModal.classList.remove('hidden');
                    globalHelpModal.classList.add('flex');
                } else {
                    globalHelpModal.classList.add('hidden');
                    globalHelpModal.classList.remove('flex');
                }
            }
        }

        if (helpToggleBtn) helpToggleBtn.addEventListener('click', toggleHelpModal);
        if (closeHelpBtn) closeHelpBtn.addEventListener('click', toggleHelpModal);
        if (closeHelpBtnBottom) closeHelpBtnBottom.addEventListener('click', toggleHelpModal);

        // Close Help Modal if user clicks outside the modal box
        if (globalHelpModal) {
            globalHelpModal.addEventListener('click', function(e) {
                if (e.target === globalHelpModal) {
                    toggleHelpModal();
                }
            });
        }

        // Dashboard Mobile Sidebar Toggle
        const mobileMenuBtn = document.getElementById('mobile-menu-btn');
        const closeSidebarBtn = document.getElementById('close-sidebar-btn');
        const sidebar = document.getElementById('main-sidebar');
        const sidebarOverlay = document.getElementById('sidebar-overlay');

        function toggleSidebar() {
            if (sidebar && sidebarOverlay) {
                sidebar.classList.toggle('-translate-x-full');
                sidebarOverlay.classList.toggle('hidden');
            }
        }

        if (mobileMenuBtn) mobileMenuBtn.addEventListener('click', toggleSidebar);
        if (closeSidebarBtn) closeSidebarBtn.addEventListener('click', toggleSidebar);
        if (sidebarOverlay) sidebarOverlay.addEventListener('click', toggleSidebar);

        // Public Mobile Navigation Dropdown Toggle
        const publicMobileBtn = document.getElementById('public-mobile-btn');
        const publicMobileMenu = document.getElementById('public-mobile-menu');
        
        if (publicMobileBtn && publicMobileMenu) {
            publicMobileBtn.addEventListener('click', function() {
                publicMobileMenu.classList.toggle('hidden');
            });
        }

        // Scroll Progress Indicator Logic
        const scrollArea = document.getElementById('main-scroll-area');
        const scrollContainer = document.getElementById('scroll-progress-container');
        const scrollPath = document.getElementById('scroll-progress-path');

        if (scrollArea && scrollContainer && scrollPath) {
            scrollArea.addEventListener('scroll', function() {
                const scrollTop = scrollArea.scrollTop;
                const scrollHeight = scrollArea.scrollHeight - scrollArea.clientHeight;
                
                if (scrollHeight > 0) {
                    const scrollPercentage = (scrollTop / scrollHeight);
                    const dashoffset = 100 - (scrollPercentage * 100);
                    scrollPath.style.strokeDashoffset = dashoffset;

                    if (scrollTop > 100) {
                        scrollContainer.classList.remove('hidden'); 
                        scrollContainer.classList.add('flex');
                        setTimeout(() => {
                            scrollContainer.classList.remove('scale-0');
                            scrollContainer.classList.add('scale-100');
                        }, 10);
                    } else {
                        scrollContainer.classList.remove('scale-100');
                        scrollContainer.classList.add('scale-0');
                        setTimeout(() => {
                            if (scrollArea.scrollTop <= 100) {
                                scrollContainer.classList.remove('flex');
                                scrollContainer.classList.add('hidden');
                            }
                        }, 300);
                    }
                }
            });
        }
    </script>

    <!-- ========================================== -->
    <!-- DATATABLES MOBILE UI ENHANCEMENTS v2.0 -->
    <!-- ========================================== -->
    <style>
        /* 1. NUCLEAR ACTION COLUMN FIX (Desktop & Mobile) */
        
        /* Force minimum width on the header and cell so DataTables CANNOT compress it */
        table.dataTable > thead > tr > th:last-child,
        table.dataTable > tbody > tr > td:last-child {
            white-space: nowrap !important;
            width: 1% !important;
            min-width: 140px !important; /* GUARANTEES space for 3+ buttons */
            text-align: right !important; /* Keeps them neatly aligned to the right */
            vertical-align: middle !important;
            display: table-cell !important;
            visibility: visible !important;
            opacity: 1 !important;
        }

        /* Force all links, buttons, and forms in that column to sit side-by-side */
        table.dataTable > tbody > tr > td:last-child a,
        table.dataTable > tbody > tr > td:last-child button,
        table.dataTable > tbody > tr > td:last-child form {
            display: inline-block !important;
            vertical-align: middle !important;
            margin: 0 3px !important; /* Neat horizontal spacing */
            float: none !important;
        }

        /* Reset wrappers that might be squishing them */
        table.dataTable > tbody > tr > td:last-child > div {
            display: block !important;
            white-space: nowrap !important;
        }

        @media (max-width: 768px) {
            /* Support BOTH v1.x wrapper rows and v2.x modern grid layouts */
            div.dataTables_wrapper > div.row:first-child,
            div.dataTables_wrapper > div.dt-layout-row:first-child,
            div.dataTables_wrapper > div:first-child {
                display: flex !important;
                justify-content: space-between !important;
                align-items: flex-end !important; 
                flex-direction: row !important;
                width: 100% !important;
                margin-bottom: 1.25rem !important;
            }
            
            /* Support BOTH .dataTables_length (v1) and .dt-length (v2) */
            div.dataTables_length, div.dt-length {
                margin: 0 !important;
                text-align: left !important;
                float: none !important;
                flex: 1 !important;
            }

            div.dataTables_length label.mobile-optimized-length, 
            div.dt-length label.mobile-optimized-length {
                display: flex !important;
                flex-direction: column !important;
                align-items: flex-start !important;
                margin-bottom: 0 !important;
            }

            .length-text {
                margin-bottom: 6px !important;
                font-size: 11px !important;
                text-transform: uppercase !important;
                letter-spacing: 0.05em !important;
                font-weight: 700 !important;
                color: #64748b !important;
            }

            html.dark .length-text { color: #94a3b8 !important; }

            div.dataTables_length select, div.dt-length select {
                margin: 0 !important;
                padding: 6px 28px 6px 12px !important;
                border-radius: 0.5rem !important;
                background-color: #f8fafc !important;
                border: 1px solid #e2e8f0 !important;
            }

            html.dark div.dataTables_length select, 
            html.dark div.dt-length select {
                background-color: #1e293b !important;
                border-color: #334155 !important;
                color: #f8fafc !important;
            }

            /* Support BOTH .dataTables_filter (v1) and .dt-search (v2) */
            div.dataTables_filter, div.dt-search {
                position: relative !important;
                margin: 0 !important;
                text-align: right !important;
                float: none !important;
            }
            
            div.dataTables_filter label, div.dt-search label {
                display: flex !important;
                align-items: center !important;
                justify-content: flex-end !important;
                margin-bottom: 0 !important;
            }
            
            .hidden-search-text { display: none !important; }

            div.dataTables_filter input, div.dt-search input {
                display: none !important; 
                position: absolute !important;
                top: 100% !important;
                right: 0 !important;
                z-index: 50 !important;
                background: #ffffff !important; 
                color: #0f172a !important;
                padding: 12px 16px !important;
                border: 1px solid #e2e8f0 !important;
                border-radius: 0.5rem !important;
                box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1) !important;
                width: 240px !important;
                margin-top: 8px !important;
                font-size: 14px !important;
                outline: none !important;
            }
            
            html.dark div.dataTables_filter input, 
            html.dark div.dt-search input {
                background: #1e293b !important;
                color: #f8fafc !important;
                border-color: #334155 !important;
                box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.3) !important;
            }
            
            div.dataTables_filter input:focus, div.dt-search input:focus {
                border-color: #3b82f6 !important;
            }
            
            div.dataTables_filter input.mobile-search-active, 
            div.dt-search input.mobile-search-active {
                display: block !important;
            }
            
            .mobile-search-btn {
                display: inline-flex !important;
                align-items: center !important;
                justify-content: center !important;
                width: 38px !important;
                height: 38px !important;
                background-color: transparent !important;
                border: 1px solid #e2e8f0 !important;
                border-radius: 0.5rem !important;
                color: #64748b !important;
                cursor: pointer !important;
                transition: all 0.2s ease-in-out !important;
            }
            
            html.dark .mobile-search-btn {
                border-color: #334155 !important;
                color: #94a3b8 !important;
            }
            
            .mobile-search-btn:active {
                transform: scale(0.95) !important;
            }
            
            .mobile-search-btn svg {
                width: 20px !important;
                height: 20px !important;
            }
        }
        
        @media (min-width: 769px) {
            .mobile-search-btn { display: none !important; }
            .hidden-search-text { display: inline !important; }

            div.dataTables_length label.mobile-optimized-length,
            div.dt-length label.mobile-optimized-length {
                display: inline-flex !important;
                align-items: center !important;
            }
            .length-text { margin-right: 8px !important; }
        }
    </style>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        if (typeof $ !== 'undefined' && $.fn.dataTable) {
            
            $.extend(true, $.fn.dataTable.defaults, {
                columnDefs: [{ responsivePriority: 1, targets: -1 }]
            });

            function enhanceDataTablesSearch() {
                try {
                    // Target BOTH v1 (.dataTables_filter) AND v2 (.dt-search)
                    $('.dataTables_filter, .dt-search').each(function() {
                        var $filter = $(this);
                        var $input = $filter.find('input');
                        var $label = $filter.find('label');
                        
                        if ($input.length && $filter.find('.mobile-search-btn').length === 0) {
                            
                            $label.contents().filter(function() {
                                return this.nodeType === 3 && $.trim(this.nodeValue).length > 0;
                            }).wrap('<span class="hidden-search-text"></span>');
                            
                            if(!$input.attr('placeholder')) {
                                $input.attr('placeholder', 'Search records...');
                            }
                            
                            var searchIcon = '<div class="mobile-search-btn"><svg fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path></svg></div>';
                            $input.after(searchIcon);
                            
                            $filter.find('.mobile-search-btn').off('click').on('click', function(e) {
                                e.preventDefault();
                                e.stopPropagation();
                                $input.toggleClass('mobile-search-active');
                                if($input.hasClass('mobile-search-active')) {
                                    $input.focus();
                                }
                            });

                            $(document).off('click.dtSearch').on('click.dtSearch', function(e) {
                                if (!$(e.target).closest('.dataTables_filter, .dt-search').length) {
                                    $input.removeClass('mobile-search-active');
                                }
                            });
                            
                            $input.off('click.dtInput').on('click.dtInput', function(e) { e.stopPropagation(); });
                        }
                    });

                    // Target BOTH v1 (.dataTables_length) AND v2 (.dt-length)
                    $('.dataTables_length, .dt-length').each(function() {
                        var $lengthDiv = $(this);
                        var $label = $lengthDiv.find('label');
                        
                        if ($label.length && $lengthDiv.find('.length-text').length === 0) {
                            $label.addClass('mobile-optimized-length');
                            var $select = $label.find('select').detach();
                            var text = $label.text().trim().replace(/\s+/g, ' ');
                            $label.empty().append('<span class="length-text">' + text + '</span>').append($select);
                        }
                    });
                } catch(e) {
                    console.error("DataTables enhancement error:", e);
                }
            }

            // 1. Initial run
            enhanceDataTablesSearch();

            // 2. DataTables core event hooks
            $(document).on('init.dt draw.dt', function() {
                enhanceDataTablesSearch();
            });

            // 3. MutationObserver for sneaky DOM injections
            const dtObserver = new MutationObserver(function() {
                enhanceDataTablesSearch();
            });
            dtObserver.observe(document.body, { childList: true, subtree: true });

            // 4. The "Pulse Check" heartbeat (runs every 500ms for the first 3 seconds)
            let pulseCount = 0;
            const pulse = setInterval(function() {
                enhanceDataTablesSearch();
                pulseCount++;
                if (pulseCount >= 6) clearInterval(pulse);
            }, 500);
        }
    });
    </script>
    <!-- ========================================== -->

</body>
</html>