                </div>

                <footer class="content-footer" style="background: var(--tcs-gray-800); color: var(--tcs-white); margin-top: 4rem;">
                    <div class="container-xxl">
                        <div class="py-4">
                            <div class="d-flex align-items-center justify-content-between flex-md-row flex-column">
                                <div class="mb-2 mb-md-0 text-white-75">
                                    &copy; <?php echo date('Y'); ?> SmartThink Admin. All rights reserved.
                                </div>
                                <div class="d-flex gap-4 text-white-75">
                                    <a href="#" class="text-decoration-none hover-primary">Security</a>
                                    <a href="#" class="text-decoration-none hover-primary">Compliance</a>
                                    <a href="#" class="text-decoration-none hover-primary">Status</a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <style>
                        .hover-primary:hover {
                            color: var(--tcs-primary-light) !important;
                            transition: color 0.2s ease;
                        }
                    </style>
                </footer>

                <div class="content-backdrop fade"></div>
            </div>
        </div>
    </div>

    <div class="layout-overlay layout-menu-toggle"></div>
</div>

    <!-- Scripts -->
    <script src="<?php echo APP_URL; ?>/assets/materio/assets/vendor/libs/jquery/jquery.js"></script>
    <script src="<?php echo APP_URL; ?>/assets/materio/assets/vendor/libs/popper/popper.js"></script>
    <script src="<?php echo APP_URL; ?>/assets/materio/assets/vendor/js/bootstrap.js"></script>
    <script src="<?php echo APP_URL; ?>/assets/materio/assets/vendor/libs/node-waves/node-waves.js"></script>
    <script src="<?php echo APP_URL; ?>/assets/materio/assets/vendor/libs/perfect-scrollbar/perfect-scrollbar.js"></script>
    <script src="<?php echo APP_URL; ?>/assets/materio/assets/vendor/js/menu.js"></script>

    <script src="<?php echo APP_URL; ?>/assets/materio/assets/js/main.js"></script>

    <script>
        // Auto-hide alerts after 5 seconds
        setTimeout(function() {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(function(alert) {
                const bsAlert = new bootstrap.Alert(alert);
                bsAlert.close();
            });
        }, 5000);

        // Confirm delete actions
        document.querySelectorAll('[data-confirm]').forEach(function(element) {
            element.addEventListener('click', function(e) {
                const message = this.getAttribute('data-confirm');
                if (message && !confirm(message)) {
                    e.preventDefault();
                }
            });
        });
        
        // Initialize tooltips
        const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
        
        // Initialize popovers
        const popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
        popoverTriggerList.map(function (popoverTriggerEl) {
            return new bootstrap.Popover(popoverTriggerEl);
        });
        
        // Form validation
        document.querySelectorAll('form[data-validate]').forEach(function(form) {
            form.addEventListener('submit', function(e) {
                if (!form.checkValidity()) {
                    e.preventDefault();
                    e.stopPropagation();
                }
                form.classList.add('was-validated');
            });
        });
        
        // Loading states for buttons
        document.querySelectorAll('[data-loading]').forEach(function(button) {
            button.addEventListener('click', function() {
                const originalText = this.innerHTML;
                this.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Loading...';
                this.disabled = true;
                
                // Reset after 3 seconds (for demo purposes)
                setTimeout(() => {
                    this.innerHTML = originalText;
                    this.disabled = false;
                }, 3000);
            });
        });
        
        // AJAX form submissions
        document.querySelectorAll('form[data-ajax]').forEach(function(form) {
            form.addEventListener('submit', function(e) {
                e.preventDefault();
                
                const formData = new FormData(this);
                const url = this.getAttribute('action') || window.location.href;
                const method = this.getAttribute('method') || 'POST';
                
                fetch(url, {
                    method: method,
                    body: formData,
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Show success message
                        showAlert('success', data.message || 'Operation completed successfully');
                        
                        // Redirect if specified
                        if (data.redirect) {
                            setTimeout(() => {
                                window.location.href = data.redirect;
                            }, 1500);
                        }
                        
                        // Reset form if specified
                        if (data.reset) {
                            form.reset();
                        }
                    } else {
                        // Show error message
                        showAlert('danger', data.message || 'An error occurred');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showAlert('danger', 'An unexpected error occurred');
                });
            });
        });
        
        // Helper function to show alerts
        function showAlert(type, message) {
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
            alertDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            
            // Insert at the top of the content wrapper
            const contentWrapper = document.querySelector('.content-wrapper');
            contentWrapper.insertBefore(alertDiv, contentWrapper.firstChild);
            
            // Auto-hide after 5 seconds
            setTimeout(() => {
                const bsAlert = new bootstrap.Alert(alertDiv);
                bsAlert.close();
            }, 5000);
        }
        
        // Data tables initialization
        document.querySelectorAll('.datatable').forEach(function(table) {
            // Simple search functionality
            const searchInput = document.createElement('input');
            searchInput.type = 'text';
            searchInput.className = 'form-control mb-3';
            searchInput.placeholder = 'Search...';
            
            table.parentNode.insertBefore(searchInput, table);
            
            searchInput.addEventListener('keyup', function() {
                const searchTerm = this.value.toLowerCase();
                const rows = table.querySelectorAll('tbody tr');
                
                rows.forEach(function(row) {
                    const text = row.textContent.toLowerCase();
                    row.style.display = text.includes(searchTerm) ? '' : 'none';
                });
            });
        });
        
        // Bulk actions
        document.querySelectorAll('.bulk-actions').forEach(function(container) {
            const checkboxes = document.querySelectorAll('input[name="selected[]"]');
            const actionSelect = container.querySelector('select[name="bulk_action"]');
            const applyButton = container.querySelector('button[name="apply_bulk"]');
            
            function updateBulkActions() {
                const checkedCount = document.querySelectorAll('input[name="selected[]"]:checked').length;
                actionSelect.disabled = checkedCount === 0;
                applyButton.disabled = checkedCount === 0;
            }
            
            checkboxes.forEach(function(checkbox) {
                checkbox.addEventListener('change', updateBulkActions);
            });
            
            // Select all checkbox
            const selectAllCheckbox = document.querySelector('input[name="select_all"]');
            if (selectAllCheckbox) {
                selectAllCheckbox.addEventListener('change', function() {
                    checkboxes.forEach(function(checkbox) {
                        checkbox.checked = this.checked;
                    });
                    updateBulkActions();
                });
            }
            
            updateBulkActions();
        });
        
        // File upload preview
        document.querySelectorAll('input[type="file"][data-preview]').forEach(function(input) {
            input.addEventListener('change', function() {
                const file = this.files[0];
                const previewId = this.getAttribute('data-preview');
                const preview = document.getElementById(previewId);
                
                if (file && preview) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        if (file.type.startsWith('image/')) {
                            preview.src = e.target.result;
                            preview.style.display = 'block';
                        } else {
                            preview.style.display = 'none';
                        }
                    };
                    reader.readAsDataURL(file);
                }
            });
        });
        
        // Rich text editor initialization (if available)
        if (typeof tinymce !== 'undefined') {
            tinymce.init({
                selector: 'textarea[data-editor="tinymce"]',
                height: 400,
                plugins: [
                    'advlist autolink lists link image charmap print preview anchor',
                    'searchreplace visualblocks code fullscreen',
                    'insertdatetime media table paste code help wordcount'
                ],
                toolbar: 'undo redo | formatselect | bold italic backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | help',
                content_css: '../assets/css/editor.css'
            });
        }
        
        // Chart initialization (if Chart.js is available)
        if (typeof Chart !== 'undefined') {
            document.querySelectorAll('canvas[data-chart]').forEach(function(canvas) {
                const type = canvas.getAttribute('data-chart');
                const data = JSON.parse(canvas.getAttribute('data-chart-data'));
                const options = JSON.parse(canvas.getAttribute('data-chart-options') || '{}');
                
                new Chart(canvas, {
                    type: type,
                    data: data,
                    options: options
                });
            });
        }
        
        // Real-time notifications (WebSocket or polling)
        function checkNotifications() {
            fetch('../api/v1/notifications.php', {
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.notifications && data.notifications.length > 0) {
                    data.notifications.forEach(function(notification) {
                        showNotification(notification);
                    });
                }
            })
            .catch(error => {
                console.error('Notification error:', error);
            });
        }

        function showNotification(notification) {
            // Create notification element
            const notificationEl = document.createElement('div');
            notificationEl.className = 'notification-toast toast';
            notificationEl.innerHTML = `
                <div class="toast-header">
                    <strong class="me-auto">${notification.title}</strong>
                    <small>${notification.time}</small>
                    <button type="button" class="btn-close" data-bs-dismiss="toast"></button>
                </div>
                <div class="toast-body">
                    ${notification.message}
                </div>
            `;

            // Add to container or create one
            let container = document.querySelector('.notification-container');
            if (!container) {
                container = document.createElement('div');
                container.className = 'notification-container';
                container.style.cssText = `
                    position: fixed;
                    top: 20px;
                    right: 20px;
                    z-index: 1050;
                    max-width: 350px;
                `;
                document.body.appendChild(container);
            }

            container.appendChild(notificationEl);

            // Show toast
            const toast = new bootstrap.Toast(notificationEl);
            toast.show();

            // Remove after hiding
            notificationEl.addEventListener('hidden.bs.toast', function() {
                notificationEl.remove();
            });
        }

        // Check notifications every 30 seconds
        setInterval(checkNotifications, 30000);

        // Initial check
        checkNotifications();

        // Keyboard shortcuts
        document.addEventListener('keydown', function(e) {
            // Ctrl/Cmd + S for save
            if ((e.ctrlKey || e.metaKey) && e.key === 's') {
                e.preventDefault();
                const saveButton = document.querySelector('button[type="submit"], button[data-action="save"]');
                if (saveButton) {
                    saveButton.click();
                }
            }
            
            // Ctrl/Cmd + N for new
            if ((e.ctrlKey || e.metaKey) && e.key === 'n') {
                e.preventDefault();
                const newButton = document.querySelector('button[data-action="new"], a[href*="new"], a[href*="create"]');
                if (newButton) {
                    window.location.href = newButton.href;
                }
            }
            
            // Escape to close modals
            if (e.key === 'Escape') {
                const openModal = document.querySelector('.modal.show');
                if (openModal) {
                    const modal = bootstrap.Modal.getInstance(openModal);
                    if (modal) {
                        modal.hide();
                    }
                }
            }
        });
        
        // Print functionality
        document.querySelectorAll('[data-print]').forEach(function(element) {
            element.addEventListener('click', function() {
                const printArea = this.getAttribute('data-print');
                if (printArea) {
                    const elementToPrint = document.querySelector(printArea);
                    if (elementToPrint) {
                        const printWindow = window.open('', '_blank');
                        printWindow.document.write(`
                            <html>
                                <head>
                                    <title>Print</title>
                                    <style>
                                        body { font-family: Arial, sans-serif; margin: 20px; }
                                        @media print { body { margin: 0; } }
                                    </style>
                                </head>
                                <body>
                                    ${elementToPrint.innerHTML}
                                </body>
                            </html>
                        `);
                        printWindow.document.close();
                        printWindow.print();
                    }
                } else {
                    window.print();
                }
            });
        });
        
        // Export functionality
        document.querySelectorAll('[data-export]').forEach(function(element) {
            element.addEventListener('click', function() {
                const format = this.getAttribute('data-export');
                const table = document.querySelector(this.getAttribute('data-export-table'));
                
                if (table) {
                    exportTable(table, format);
                }
            });
        });
        
        function exportTable(table, format) {
            let data = '';
            let filename = 'export';
            
            if (format === 'csv') {
                data = tableToCSV(table);
                filename = filename + '.csv';
                downloadFile(data, filename, 'text/csv');
            } else if (format === 'excel') {
                // For Excel export, you would typically use a library like SheetJS
                alert('Excel export requires additional library implementation');
            }
        }
        
        function tableToCSV(table) {
            let csv = [];
            
            // Get headers
            const headers = [];
            table.querySelectorAll('thead th').forEach(function(th) {
                headers.push(th.textContent.trim());
            });
            csv.push(headers.join(','));
            
            // Get rows
            table.querySelectorAll('tbody tr').forEach(function(row) {
                const rowData = [];
                row.querySelectorAll('td').forEach(function(td) {
                    rowData.push('"' + td.textContent.trim().replace(/"/g, '""') + '"');
                });
                csv.push(rowData.join(','));
            });
            
            return csv.join('\n');
        }
        
        function downloadFile(data, filename, type) {
            const blob = new Blob([data], { type: type });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
        }
    </script>
</body>
</html>
