</div><!-- End content-wrapper -->
    </div><!-- End main-content -->
    
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    
    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- DataTables -->
    <script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.7/js/dataTables.bootstrap5.min.js"></script>
    
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <!-- Admin Common Scripts -->
    <script>
        $(document).ready(function() {
            // Sidebar toggle
            $('#menuToggle').click(function() {
                if ($(window).width() > 768) {
                    $('#sidebar').toggleClass('collapsed');
                } else {
                    $('#sidebar').toggleClass('show');
                    $('#sidebarOverlay').toggleClass('show');
                }
            });
            
            // Close sidebar when clicking overlay
            $('#sidebarOverlay').click(function() {
                $('#sidebar').removeClass('show');
                $(this).removeClass('show');
            });
            
            // Initialize all DataTables
            if ($.fn.DataTable) {
                $('.data-table').DataTable({
                    pageLength: 10,
                    responsive: true,
                    language: {
                        search: "_INPUT_",
                        searchPlaceholder: "Search...",
                        lengthMenu: "Show _MENU_ entries",
                        info: "Showing _START_ to _END_ of _TOTAL_ entries",
                        infoEmpty: "No entries to show",
                        infoFiltered: "(filtered from _MAX_ total entries)",
                        paginate: {
                            first: "First",
                            last: "Last",
                            next: "Next",
                            previous: "Previous"
                        }
                    },
                    dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>rtip'
                });
            }
            
            // Global search functionality
            $('#globalSearch').on('keyup', function(e) {
                if (e.key === 'Enter') {
                    const searchTerm = $(this).val();
                    if (searchTerm.length > 0) {
                        // Implement global search
                        window.location.href = 'search.php?q=' + encodeURIComponent(searchTerm);
                    }
                }
            });
            
            // Auto-hide alerts after 5 seconds
            $('.alert').each(function() {
                if (!$(this).hasClass('alert-permanent')) {
                    setTimeout(() => {
                        $(this).fadeOut();
                    }, 5000);
                }
            });
            
            // Confirm delete actions
            $('.delete-btn').click(function(e) {
                e.preventDefault();
                const url = $(this).attr('href') || $(this).data('url');
                const itemName = $(this).data('name') || 'this item';
                
                Swal.fire({
                    title: 'Are you sure?',
                    text: `You are about to delete ${itemName}. This action cannot be undone!`,
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#d33',
                    cancelButtonColor: '#3085d6',
                    confirmButtonText: 'Yes, delete it!',
                    cancelButtonText: 'Cancel'
                }).then((result) => {
                    if (result.isConfirmed) {
                        window.location.href = url;
                    }
                });
            });
            
            // Form validation helper
            $('form[data-validate="true"]').submit(function(e) {
                let isValid = true;
                $(this).find('[required]').each(function() {
                    if ($(this).val().trim() === '') {
                        isValid = false;
                        $(this).addClass('is-invalid');
                    } else {
                        $(this).removeClass('is-invalid');
                    }
                });
                
                if (!isValid) {
                    e.preventDefault();
                    Swal.fire({
                        icon: 'error',
                        title: 'Validation Error',
                        text: 'Please fill in all required fields'
                    });
                }
            });
            
            // AJAX form submission helper
            $('.ajax-form').submit(function(e) {
                e.preventDefault();
                const form = $(this);
                const submitBtn = form.find('[type="submit"]');
                const originalText = submitBtn.html();
                
                // Disable submit button
                submitBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Processing...');
                
                $.ajax({
                    url: form.attr('action'),
                    type: form.attr('method') || 'POST',
                    data: new FormData(this),
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        try {
                            const data = typeof response === 'string' ? JSON.parse(response) : response;
                            
                            if (data.success) {
                                Swal.fire({
                                    icon: 'success',
                                    title: 'Success!',
                                    text: data.message || 'Operation completed successfully',
                                    timer: 2000
                                }).then(() => {
                                    if (data.redirect) {
                                        window.location.href = data.redirect;
                                    } else if (data.reload) {
                                        location.reload();
                                    }
                                });
                            } else {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Error',
                                    text: data.message || 'Operation failed'
                                });
                            }
                        } catch (e) {
                            console.error('Response parsing error:', e);
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: 'An unexpected error occurred'
                            });
                        }
                    },
                    error: function(xhr) {
                        console.error('AJAX error:', xhr);
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: xhr.responseJSON?.message || 'Server error occurred'
                        });
                    },
                    complete: function() {
                        submitBtn.prop('disabled', false).html(originalText);
                    }
                });
            });
            
            // Image preview
            $('input[type="file"][data-preview]').change(function() {
                const previewId = $(this).data('preview');
                const file = this.files[0];
                
                if (file && file.type.startsWith('image/')) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        $(`#${previewId}`).attr('src', e.target.result).show();
                    };
                    reader.readAsDataURL(file);
                }
            });
            
            // Copy to clipboard
            $('.copy-btn').click(function() {
                const text = $(this).data('copy');
                navigator.clipboard.writeText(text).then(() => {
                    Swal.fire({
                        icon: 'success',
                        title: 'Copied!',
                        text: 'Text copied to clipboard',
                        timer: 1500,
                        showConfirmButton: false
                    });
                });
            });
            
            // Status toggle
            $('.status-toggle').change(function() {
                const checkbox = $(this);
                const url = checkbox.data('url');
                const status = checkbox.is(':checked') ? 1 : 0;
                
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: { 
                        status: status,
                        csrf_token: $('meta[name="csrf-token"]').attr('content')
                    },
                    success: function(response) {
                        const data = typeof response === 'string' ? JSON.parse(response) : response;
                        
                        if (!data.success) {
                            checkbox.prop('checked', !checkbox.is(':checked'));
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: data.message || 'Failed to update status'
                            });
                        }
                    },
                    error: function() {
                        checkbox.prop('checked', !checkbox.is(':checked'));
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: 'Failed to update status'
                        });
                    }
                });
            });
            
            // Auto-refresh notifications
            setInterval(function() {
                $.get('ajax/get-notifications.php', function(data) {
                    if (data.count > 0) {
                        $('.notification-badge').text(data.count).show();
                    } else {
                        $('.notification-badge').hide();
                    }
                });
            }, 60000); // Every minute
            
            // Tooltips
            const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
            const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl));
            
            // Popovers
            const popoverTriggerList = document.querySelectorAll('[data-bs-toggle="popover"]');
            const popoverList = [...popoverTriggerList].map(popoverTriggerEl => new bootstrap.Popover(popoverTriggerEl));
        });
        
        // Number formatting
        function formatNumber(num) {
            return new Intl.NumberFormat('en-NG', {
                style: 'currency',
                currency: 'NGN',
                minimumFractionDigits: 0
            }).format(num);
        }
        
        // Date formatting
        function formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleDateString('en-NG', {
                year: 'numeric',
                month: 'short',
                day: 'numeric'
            });
        }
        
        // Success message
        function showSuccess(message, redirect = null) {
            Swal.fire({
                icon: 'success',
                title: 'Success!',
                text: message,
                timer: 2000,
                showConfirmButton: false
            }).then(() => {
                if (redirect) {
                    window.location.href = redirect;
                }
            });
        }
        
        // Error message
        function showError(message) {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: message
            });
        }
    </script>
</body>
</html>