// assets/js/main.js

// Document Ready
$(document).ready(function() {
    // Initialize tooltips
    $('[data-bs-toggle="tooltip"]').tooltip();
    
    // Initialize popovers
    $('[data-bs-toggle="popover"]').popover();
    
    // Auto-hide alerts after 5 seconds
    setTimeout(function() {
        $('.alert').fadeOut('slow', function() {
            $(this).remove();
        });
    }, 5000);
    
    // Add active class to current nav item
    var currentPage = window.location.pathname.split('/').pop();
    $('.nav-link').each(function() {
        var link = $(this).attr('href');
        if (link === currentPage) {
            $(this).addClass('active');
        }
    });
});

// Form validation helper
function validateForm(formId) {
    var isValid = true;
    var form = $('#' + formId);
    
    form.find('input[required], select[required], textarea[required]').each(function() {
        if (!$(this).val()) {
            $(this).addClass('is-invalid');
            isValid = false;
        } else {
            $(this).removeClass('is-invalid');
        }
    });
    
    return isValid;
}

// Show notification
function showNotification(message, type = 'info') {
    var alertClass = {
        'success': 'alert-success',
        'error': 'alert-danger',
        'info': 'alert-info',
        'warning': 'alert-warning'
    }[type] || 'alert-info';
    
    var iconClass = {
        'success': 'fa-check-circle',
        'error': 'fa-exclamation-triangle',
        'info': 'fa-info-circle',
        'warning': 'fa-exclamation-circle'
    }[type] || 'fa-info-circle';
    
    var alertHtml = `
        <div class="alert ${alertClass} alert-dismissible fade show custom-notification" role="alert" 
             style="position: fixed; top: 20px; right: 20px; z-index: 9999; min-width: 300px; animation: fadeIn 0.3s ease;">
            <i class="fas ${iconClass} me-2"></i>
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    
    $('body').append(alertHtml);
    
    setTimeout(function() {
        $('.custom-notification').fadeOut('slow', function() {
            $(this).remove();
        });
    }, 5000);
}

// Confirm dialog
function confirmAction(message, callback) {
    if (confirm(message)) {
        if (callback && typeof callback === 'function') {
            callback();
        }
        return true;
    }
    return false;
}

// Copy to clipboard
function copyToClipboard(text) {
    var textarea = document.createElement('textarea');
    textarea.value = text;
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand('copy');
    document.body.removeChild(textarea);
    showNotification('Copied to clipboard!', 'success');
}

// Print element
function printElement(elementId) {
    var printContent = document.getElementById(elementId).innerHTML;
    var printWindow = window.open('', '_blank');
    
    printWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
            <title>Print</title>
            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
            <style>
                body { padding: 20px; }
                @media print {
                    body { padding: 0; }
                }
            </style>
        </head>
        <body>
            ${printContent}
            <script>
                window.onload = function() {
                    window.print();
                    window.close();
                };
            <\/script>
        </body>
        </html>
    `);
    
    printWindow.document.close();
}

// Download as PNG using html2canvas
function downloadAsPNG(elementId, filename) {
    var element = document.getElementById(elementId);
    
    if (typeof html2canvas === 'undefined') {
        showNotification('html2canvas library not loaded', 'error');
        return;
    }
    
    showNotification('Generating image...', 'info');
    
    html2canvas(element, {
        scale: 3,
        backgroundColor: null,
        useCORS: true,
        logging: false
    }).then(function(canvas) {
        var link = document.createElement('a');
        link.download = filename + '.png';
        link.href = canvas.toDataURL('image/png');
        link.click();
        showNotification('Downloaded successfully!', 'success');
    }).catch(function(error) {
        console.error('Error:', error);
        showNotification('Failed to generate image', 'error');
    });
}

// Export table to Excel
function exportToExcel(tableId, filename) {
    var table = document.getElementById(tableId);
    var html = table.outerHTML;
    var url = 'data:application/vnd.ms-excel,' + encodeURIComponent(html);
    var downloadLink = document.createElement('a');
    
    downloadLink.href = url;
    downloadLink.download = filename + '.xls';
    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
    
    showNotification('Exported successfully!', 'success');
}

// Password strength checker
function checkPasswordStrength(password) {
    var strength = 0;
    
    if (password.length >= 8) strength++;
    if (password.match(/[a-z]/) && password.match(/[A-Z]/)) strength++;
    if (password.match(/\d/)) strength++;
    if (password.match(/[^a-zA-Z\d]/)) strength++;
    
    var strengthText = ['Weak', 'Fair', 'Good', 'Strong'];
    var strengthClass = ['danger', 'warning', 'info', 'success'];
    
    return {
        score: strength,
        text: strengthText[strength - 1] || 'Very Weak',
        class: strengthClass[strength - 1] || 'danger'
    };
}

// Update password strength indicator
function updatePasswordStrength(inputId, indicatorId) {
    var password = $('#' + inputId).val();
    var strength = checkPasswordStrength(password);
    
    $('#' + indicatorId).html(`
        <div class="progress mt-1" style="height: 5px;">
            <div class="progress-bar bg-${strength.class}" style="width: ${strength.score * 25}%"></div>
        </div>
        <small class="text-${strength.class}">${strength.text}</small>
    `);
}

// Toggle password visibility
function togglePassword(inputId, iconId) {
    var input = $('#' + inputId);
    var icon = $('#' + iconId);
    
    if (input.attr('type') === 'password') {
        input.attr('type', 'text');
        icon.removeClass('fa-eye').addClass('fa-eye-slash');
    } else {
        input.attr('type', 'password');
        icon.removeClass('fa-eye-slash').addClass('fa-eye');
    }
}

// Loader show/hide
function showLoader() {
    $('body').append('<div class="loader-overlay"><div class="loader"></div></div>');
}

function hideLoader() {
    $('.loader-overlay').remove();
}

// Add loader styles
$(document).ready(function() {
    if (!$('#loader-styles').length) {
        $('head').append(`
            <style id="loader-styles">
                .loader-overlay {
                    position: fixed;
                    top: 0;
                    left: 0;
                    width: 100%;
                    height: 100%;
                    background: rgba(0,0,0,0.5);
                    z-index: 9999;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                }
                .loader {
                    width: 50px;
                    height: 50px;
                    border: 3px solid rgba(255,255,255,0.3);
                    border-radius: 50%;
                    border-top-color: white;
                    animation: spin 0.8s linear infinite;
                }
                @keyframes spin {
                    to { transform: rotate(360deg); }
                }
            </style>
        `);
    }
});