/**
 * Admin Dashboard JavaScript
 */

$(document).ready(function() {
    
    // ===================================
    // Sidebar Toggle
    // ===================================
    
    $('#mobileToggle, #sidebarToggle').on('click', function() {
        $('.sidebar').toggleClass('active');
        $('body').toggleClass('sidebar-open');
    });
    
    // Close sidebar when clicking outside on mobile
    $(document).on('click', function(e) {
        if ($(window).width() <= 992) {
            if (!$(e.target).closest('.sidebar, #mobileToggle').length) {
                $('.sidebar').removeClass('active');
                $('body').removeClass('sidebar-open');
            }
        }
    });
    
    // ===================================
    // DataTables Initialization
    // ===================================
    
    if ($('.data-table').length) {
        $('.data-table').DataTable({
            responsive: true,
            pageLength: 20,
            language: {
                search: "_INPUT_",
                searchPlaceholder: "Search...",
                lengthMenu: "Show _MENU_ entries",
                info: "Showing _START_ to _END_ of _TOTAL_ entries",
                infoEmpty: "No entries available",
                infoFiltered: "(filtered from _MAX_ total entries)",
                zeroRecords: "No matching records found",
                emptyTable: "No data available in table"
            },
            dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>rtip'
        });
    }
    
    // ===================================
    // Form Validation
    // ===================================
    
    // Bootstrap form validation
    const forms = document.querySelectorAll('.needs-validation');
    Array.from(forms).forEach(form => {
        form.addEventListener('submit', event => {
            if (!form.checkValidity()) {
                event.preventDefault();
                event.stopPropagation();
            }
            form.classList.add('was-validated');
        }, false);
    });
    
    // ===================================
    // Delete Confirmation
    // ===================================
    
    $(document).on('click', '.btn-delete', function(e) {
        e.preventDefault();
        const url = $(this).attr('href');
        const itemName = $(this).data('name') || 'this item';
        
        Swal.fire({
            title: 'Are you sure?',
            text: `Do you want to delete ${itemName}?`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Yes, delete it!',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = url;
            }
        });
    });
    
    // ===================================
    // Toast Notifications
    // ===================================
    
    window.showToast = function(message, type = 'success') {
        const Toast = Swal.mixin({
            toast: true,
            position: 'top-end',
            showConfirmButton: false,
            timer: 3000,
            timerProgressBar: true,
            didOpen: (toast) => {
                toast.addEventListener('mouseenter', Swal.stopTimer);
                toast.addEventListener('mouseleave', Swal.resumeTimer);
            }
        });
        
        Toast.fire({
            icon: type,
            title: message
        });
    };
    
    // Show toast if message exists in URL params
    const urlParams = new URLSearchParams(window.location.search);
    const successMsg = urlParams.get('success');
    const errorMsg = urlParams.get('error');
    
    if (successMsg) {
        showToast(decodeURIComponent(successMsg), 'success');
    }
    if (errorMsg) {
        showToast(decodeURIComponent(errorMsg), 'error');
    }
    
    // ===================================
    // Image Preview
    // ===================================
    
    $('.image-input').on('change', function() {
        const file = this.files[0];
        const preview = $(this).data('preview');
        
        if (file && preview) {
            const reader = new FileReader();
            reader.onload = function(e) {
                $(preview).attr('src', e.target.result).show();
            };
            reader.readAsDataURL(file);
        }
    });
    
    // ===================================
    // Character Counter
    // ===================================
    
    $('.char-counter').each(function() {
        const maxLength = $(this).attr('maxlength');
        const counterId = $(this).attr('id') + '-counter';
        
        $(this).after(`<small class="text-muted" id="${counterId}">0 / ${maxLength}</small>`);
        
        $(this).on('input', function() {
            const length = $(this).val().length;
            $(`#${counterId}`).text(`${length} / ${maxLength}`);
        });
    });
    
    // ===================================
    // Date Picker Enhancement
    // ===================================
    
    $('input[type="date"]').each(function() {
        if (!$(this).val()) {
            $(this).addClass('text-muted');
        }
        
        $(this).on('change', function() {
            $(this).removeClass('text-muted');
        });
    });
    
    // ===================================
    // Auto-dismiss Alerts
    // ===================================
    
    $('.alert-auto-dismiss').each(function() {
        const alert = $(this);
        setTimeout(function() {
            alert.fadeOut('slow', function() {
                alert.remove();
            });
        }, 5000);
    });
    
    // ===================================
    // Tooltips & Popovers
    // ===================================
    
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
    
    const popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
    popoverTriggerList.map(function (popoverTriggerEl) {
        return new bootstrap.Popover(popoverTriggerEl);
    });
    
    // ===================================
    // Loading Overlay
    // ===================================
    
    window.showLoading = function() {
        $('body').append('<div class="loading-overlay"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div></div>');
    };
    
    window.hideLoading = function() {
        $('.loading-overlay').remove();
    };
    
    // ===================================
    // Confirm Navigation
    // ===================================
    
    let formChanged = false;
    
    $('form input, form textarea, form select').on('change', function() {
        formChanged = true;
    });
    
    $('form').on('submit', function() {
        formChanged = false;
    });
    
    $(window).on('beforeunload', function() {
        if (formChanged) {
            return 'You have unsaved changes. Are you sure you want to leave?';
        }
    });
    
    // ===================================
    // Phone Number Formatting
    // ===================================
    
    $('.phone-input').on('input', function() {
        let value = $(this).val().replace(/\D/g, '');
        if (value.length > 10) {
            value = value.substring(0, 10);
        }
        $(this).val(value);
    });
    
    // ===================================
    // Search Highlight
    // ===================================
    
    $('.search-input').on('input', function() {
        const searchTerm = $(this).val().toLowerCase();
        const targetClass = $(this).data('target');
        
        $(targetClass).each(function() {
            const text = $(this).text().toLowerCase();
            if (text.includes(searchTerm)) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    });
});

// ===================================
// Loading Overlay CSS (injected)
// ===================================

const loadingCSS = `
<style>
.loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;
}
.loading-overlay .spinner-border {
    width: 3rem;
    height: 3rem;
}
</style>
`;

$('head').append(loadingCSS);
