<!-- Control Sidebar -->
<aside class="control-sidebar control-sidebar-dark">
    <!-- Control sidebar content goes here -->
</aside>
<!-- /.control-sidebar -->

</div>
<!-- ./wrapper -->

<!-- jQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<!-- jQuery UI 1.11.4 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"></script>
<!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip -->
<script>
  $.widget.bridge('uibutton', $.ui.button)
</script>
<!-- Bootstrap 4 -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
<!-- ChartJS -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<!-- Sparkline -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-sparklines/2.1.2/jquery.sparkline.min.js"></script>
<!-- JQVMap -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqvmap/1.5.1/jquery.vmap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqvmap/1.5.1/maps/jquery.vmap.usa.js"></script>
<!-- jQuery Knob Chart -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jQuery-Knob/1.2.13/jquery.knob.min.js"></script>
<!-- daterangepicker -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
<!-- Tempusdominus Bootstrap 4 -->
<script src="https://cdn.jsdelivr.net/npm/tempusdominus-bootstrap-4@5.39.0/build/js/tempusdominus-bootstrap-4.min.js"></script>
<!-- Summernote -->
<script src="https://cdn.jsdelivr.net/npm/summernote@0.8.20/dist/summernote-bs4.min.js"></script>
<!-- overlayScrollbars -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/overlayscrollbars/1.13.1/js/OverlayScrollbars.min.js"></script>
<!-- Select2 -->
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<!-- AdminLTE App -->
<script src="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/js/adminlte.min.js"></script>
<!-- Mobile Sidebar Fix -->
<script src="dist/js/mobile-sidebar-fix.js"></script>
<!-- DataTables & Plugins -->
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.bootstrap4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.colVis.min.js"></script>
<!-- Toastr -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<!-- Pace -->
<script src="https://cdn.jsdelivr.net/npm/pace-js@1.2.4/pace.min.js"></script>

<script>
$(document).ready(function() {
    // Initialize AdminLTE
    $('[data-toggle="tooltip"]').tooltip();
    $('[data-toggle="popover"]').popover();
    
    // Configure Toastr
    toastr.options = {
        "closeButton": true,
        "debug": false,
        "newestOnTop": true,
        "progressBar": true,
        "positionClass": "toast-top-right",
        "preventDuplicates": false,
        "onclick": null,
        "showDuration": "300",
        "hideDuration": "1000",
        "timeOut": "5000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    };
    
    // Initialize DataTables with enhanced features
    $.extend(true, $.fn.dataTable.defaults, {
        "responsive": true,
        "lengthChange": true,
        "autoWidth": false,
        "searching": true,
        "ordering": true,
        "info": true,
        "paging": true,
        "pageLength": 25,
        "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
        "language": {
            "search": "Search:",
            "lengthMenu": "Show _MENU_ entries",
            "info": "Showing _START_ to _END_ of _TOTAL_ entries",
            "infoEmpty": "Showing 0 to 0 of 0 entries",
            "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>>' +
               '<"row"<"col-sm-12"tr>>' +
               '<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>',
        "buttons": [
            {
                extend: 'copy',
                className: 'btn btn-sm btn-primary',
                text: '<i class="fas fa-copy"></i> Copy'
            },
            {
                extend: 'csv',
                className: 'btn btn-sm btn-success',
                text: '<i class="fas fa-file-csv"></i> CSV'
            },
            {
                extend: 'excel',
                className: 'btn btn-sm btn-success',
                text: '<i class="fas fa-file-excel"></i> Excel'
            },
            {
                extend: 'pdf',
                className: 'btn btn-sm btn-danger',
                text: '<i class="fas fa-file-pdf"></i> PDF'
            },
            {
                extend: 'print',
                className: 'btn btn-sm btn-info',
                text: '<i class="fas fa-print"></i> Print'
            }
        ]
    });
    
    // Initialize Select2
    $('.select2').select2({
        theme: 'bootstrap4',
        width: '100%'
    });
    
    // Initialize date range picker
    $('.daterange').daterangepicker({
        locale: {
            format: 'YYYY-MM-DD'
        }
    });
    
    // Initialize Summernote
    $('.summernote').summernote({
        height: 200,
        toolbar: [
            ['style', ['style']],
            ['font', ['bold', 'underline', 'clear']],
            ['fontname', ['fontname']],
            ['color', ['color']],
            ['para', ['ul', 'ol', 'paragraph']],
            ['table', ['table']],
            ['insert', ['link', 'picture', 'video']],
            ['view', ['fullscreen', 'codeview', 'help']]
        ]
    });
    
    // Auto-hide alerts after 5 seconds
    setTimeout(function() {
        $('.alert').fadeOut('slow');
    }, 5000);
    
    // Loading state for buttons
    $(document).on('click', '.btn-loading', function() {
        var $btn = $(this);
        var originalText = $btn.html();
        $btn.html('<i class="fas fa-spinner fa-spin"></i> Loading...');
        $btn.prop('disabled', true);
        
        setTimeout(function() {
            $btn.html(originalText);
            $btn.prop('disabled', false);
        }, 3000);
    });
    
    // Confirm delete actions
    $(document).on('click', '.btn-delete', function(e) {
        e.preventDefault();
        var $this = $(this);
        var message = $this.data('message') || 'Are you sure you want to delete this item?';
        
        Swal.fire({
            title: 'Are you sure?',
            text: message,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            if (result.isConfirmed) {
                if ($this.attr('href')) {
                    window.location.href = $this.attr('href');
                } else if ($this.data('url')) {
                    window.location.href = $this.data('url');
                }
            }
        });
    });
    
    // Form validation
    $('.needs-validation').on('submit', function(e) {
        var form = this;
        if (form.checkValidity() === false) {
            e.preventDefault();
            e.stopPropagation();
        }
        $(form).addClass('was-validated');
    });
    
    // Auto-resize textareas
    $('textarea').each(function() {
        this.style.height = 'auto';
        this.style.height = (this.scrollHeight) + 'px';
    });
    
    // Sidebar toggle persistence
    if (localStorage.getItem('sidebar_collapsed') === 'true') {
        $('body').addClass('sidebar-collapse');
    }
    
    $('.nav-sidebar-toggle').on('click', function() {
        setTimeout(function() {
            localStorage.setItem('sidebar_collapsed', $('body').hasClass('sidebar-collapse'));
        }, 300);
    });
    
    // Initialize overlay scrollbars
    if (typeof OverlayScrollbars !== 'undefined') {
        OverlayScrollbars(document.querySelectorAll('.sidebar'), {
            scrollbars: {
                autoHide: 'scroll'
            }
        });
    }
    
    // Real-time search
    $('.real-time-search').on('input', function() {
        var searchTerm = $(this).val().toLowerCase();
        var targetClass = $(this).data('target');
        
        $(targetClass).each(function() {
            var text = $(this).text().toLowerCase();
            if (text.indexOf(searchTerm) === -1) {
                $(this).hide();
            } else {
                $(this).show();
            }
        });
    });
    
    // Initialize charts if Chart.js is available
    if (typeof Chart !== 'undefined') {
        Chart.defaults.plugins.legend.display = true;
        Chart.defaults.plugins.legend.position = 'bottom';
        Chart.defaults.maintainAspectRatio = false;
        Chart.defaults.responsive = true;
    }
    
    // AJAX form submission
    $(document).on('submit', '.ajax-form', function(e) {
        e.preventDefault();
        var $form = $(this);
        var $submitBtn = $form.find('[type="submit"]');
        var originalText = $submitBtn.html();
        
        $submitBtn.html('<i class="fas fa-spinner fa-spin"></i> Processing...');
        $submitBtn.prop('disabled', true);
        
        $.ajax({
            url: $form.attr('action'),
            type: $form.attr('method') || 'POST',
            data: $form.serialize(),
            success: function(response) {
                if (response.success) {
                    toastr.success(response.message || 'Operation completed successfully!');
                    if (response.redirect) {
                        setTimeout(function() {
                            window.location.href = response.redirect;
                        }, 1500);
                    }
                } else {
                    toastr.error(response.message || 'An error occurred. Please try again.');
                }
            },
            error: function() {
                toastr.error('An error occurred. Please try again.');
            },
            complete: function() {
                $submitBtn.html(originalText);
                $submitBtn.prop('disabled', false);
            }
        });
    });
    
    // File upload preview
    $(document).on('change', '.file-preview', function() {
        var file = this.files[0];
        var $preview = $(this).siblings('.preview');
        
        if (file && file.type.startsWith('image/')) {
            var reader = new FileReader();
            reader.onload = function(e) {
                $preview.html('<img src="' + e.target.result + '" class="img-fluid" style="max-height: 200px;">');
            };
            reader.readAsDataURL(file);
        } else {
            $preview.html('');
        }
    });
    
    // Auto-logout warning
    var sessionTimeout = 30 * 60 * 1000; // 30 minutes
    var warningTime = 5 * 60 * 1000; // 5 minutes before timeout
    
    setTimeout(function() {
        Swal.fire({
            title: 'Session Expiring',
            text: 'Your session will expire in 5 minutes. Do you want to continue?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Continue Session',
            cancelButtonText: 'Logout'
        }).then((result) => {
            if (result.isConfirmed) {
                // Refresh session
                $.get('api/refresh_session.php');
            } else {
                window.location.href = 'logout.php';
            }
        });
    }, warningTime);
    
    // Mobile-specific optimizations
    if ('ontouchstart' in window) {
        // Make tables responsive on mobile
        $('.table').addClass('table-responsive');
        
        // Add touch-friendly sizing to buttons
        $('.btn').addClass('btn-touch-friendly');
        
        // Adjust modal sizing for mobile
        $('.modal').on('show.bs.modal', function() {
            $(this).find('.modal-dialog').css({
                'margin-top': '10px',
                'margin-bottom': '10px'
            });
        });
    }
    
    // High-DPI screen optimizations
    if (window.devicePixelRatio > 1.5) {
        // Use higher quality images for retina displays
        $('img[data-hd-src]').each(function() {
            $(this).attr('src', $(this).data('hd-src'));
        });
    }
    
    // Detect connection speed and optimize accordingly
    var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
    if (connection && connection.effectiveType) {
        if (connection.effectiveType === '4g') {
            // Load any deferred high-quality content
            $('.deferred-hq').each(function() {
                var $this = $(this);
                var hqSrc = $this.data('hq-src');
                if (hqSrc) {
                    if ($this.is('img')) {
                        $this.attr('src', hqSrc);
                    } else {
                        $this.css('background-image', 'url(' + hqSrc + ')');
                    }
                }
            });
        }
    }
});
</script>

</body>
</html>
