/**
 * Main JavaScript for Admission System
 */

$(document).ready(function() {
    
    // Initialize tooltips
    $('[data-bs-toggle="tooltip"]').tooltip();
    
    // Initialize popovers
    $('[data-bs-toggle="popover"]').popover();
    
    // Real-time email validation
    $('#email').on('blur', function() {
        const email = $(this).val();
        if (email && !validateEmail(email)) {
            showError($(this), 'Please enter a valid email address');
        }
    });
    
    // Password strength meter
    $('#password').on('keyup', function() {
        const password = $(this).val();
        const strength = checkPasswordStrength(password);
        updatePasswordStrength(strength);
    });
    
    // Form submission handling
    $('form').submit(function(e) {
        // Validate required fields
        let isValid = true;
        
        $(this).find('[required]').each(function() {
            if (!$(this).val()) {
                showError($(this), 'This field is required');
                isValid = false;
            }
        });
        
        if (!isValid) {
            e.preventDefault();
            return false;
        }
        
        // Show loading
        $(this).find('button[type="submit"]').prop('disabled', true)
            .html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Processing...');
        
        return true;
    });
    
    // File upload preview
    $('.file-upload').change(function(e) {
        const input = $(this);
        const fileName = e.target.files[0].name;
        const fileSize = e.target.files[0].size;
        
        // Validate file size (max 2MB)
        if (fileSize > 2 * 1024 * 1024) {
            showError(input, 'File size must be less than 2MB');
            input.val('');
            return;
        }
        
        // Validate file type
        const allowedTypes = ['pdf', 'jpg', 'jpeg', 'png'];
        const fileExt = fileName.split('.').pop().toLowerCase();
        
        if (!allowedTypes.includes(fileExt)) {
            showError(input, 'Only PDF, JPG, PNG files are allowed');
            input.val('');
            return;
        }
        
        // Show file name
        input.siblings('.file-name').text(fileName);
        input.siblings('.file-error').text('');
    });
    
    // Real-time application status check
    if ($('#applicationStatus').length) {
        setInterval(checkApplicationStatus, 30000); // Check every 30 seconds
    }
    
    // Course filter
    $('#courseFilter').on('keyup', function() {
        const filter = $(this).val().toLowerCase();
        $('.course-card').each(function() {
            const text = $(this).text().toLowerCase();
            $(this).toggle(text.indexOf(filter) > -1);
        });
    });
    
    // Mark calculation
    $('.mark-input').on('input', function() {
        calculateTotal();
    });
    
    // Auto-save forms
    let autoSaveTimer;
    $('.auto-save').on('input', function() {
        clearTimeout(autoSaveTimer);
        autoSaveTimer = setTimeout(saveForm, 2000);
    });
    
    // Initialize charts if Chart.js is available
    if (typeof Chart !== 'undefined') {
        initializeCharts();
    }
});

/**
 * Helper Functions
 */

function validateEmail(email) {
    const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return re.test(email);
}

function checkPasswordStrength(password) {
    let strength = 0;
    
    if (password.length >= 8) strength++;
    if (password.match(/[a-z]+/)) strength++;
    if (password.match(/[A-Z]+/)) strength++;
    if (password.match(/[0-9]+/)) strength++;
    if (password.match(/[$@#&!]+/)) strength++;
    
    return strength;
}

function updatePasswordStrength(strength) {
    const meter = $('#passwordStrength');
    const text = $('#passwordStrengthText');
    
    if (!meter.length) return;
    
    meter.removeClass('bg-danger bg-warning bg-success').width('0%');
    
    switch(strength) {
        case 0:
        case 1:
            meter.addClass('bg-danger').width('20%');
            text.text('Very Weak').removeClass().addClass('text-danger');
            break;
        case 2:
            meter.addClass('bg-warning').width('40%');
            text.text('Weak').removeClass().addClass('text-warning');
            break;
        case 3:
            meter.addClass('bg-warning').width('60%');
            text.text('Good').removeClass().addClass('text-warning');
            break;
        case 4:
            meter.addClass('bg-success').width('80%');
            text.text('Strong').removeClass().addClass('text-success');
            break;
        case 5:
            meter.addClass('bg-success').width('100%');
            text.text('Very Strong').removeClass().addClass('text-success');
            break;
    }
}

function showError(element, message) {
    element.addClass('is-invalid');
    const errorDiv = element.siblings('.invalid-feedback');
    if (errorDiv.length) {
        errorDiv.text(message);
    } else {
        element.after('<div class="invalid-feedback">' + message + '</div>');
    }
}

function clearError(element) {
    element.removeClass('is-invalid');
    element.siblings('.invalid-feedback').remove();
}

function checkApplicationStatus() {
    const applicationId = $('#applicationStatus').data('id');
    
    $.ajax({
        url: baseUrl + 'api/check-status',
        method: 'POST',
        data: { application_id: applicationId },
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')
        },
        success: function(response) {
            if (response.success) {
                updateStatusDisplay(response.data);
            }
        }
    });
}

function updateStatusDisplay(data) {
    const statusBadge = $('#statusBadge');
    const statusText = $('#statusText');
    const lastUpdated = $('#lastUpdated');
    
    statusBadge.removeClass().addClass('badge badge-' + data.status);
    statusText.text(data.status_text);
    lastUpdated.text('Last updated: ' + data.updated_at);
    
    // Add animation
    statusBadge.addClass('animate__animated animate__pulse');
    setTimeout(() => {
        statusBadge.removeClass('animate__animated animate__pulse');
    }, 1000);
}

function calculateTotal() {
    let total = 0;
    let count = 0;
    
    $('.mark-input').each(function() {
        const value = parseFloat($(this).val()) || 0;
        if (value > 0) {
            total += value;
            count++;
        }
    });
    
    const average = count > 0 ? total / count : 0;
    $('#totalMarks').text(total.toFixed(2));
    $('#averageMarks').text(average.toFixed(2));
}

function saveForm() {
    const form = $('.auto-save').closest('form');
    const formData = new FormData(form[0]);
    
    $.ajax({
        url: form.attr('action'),
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content')
        },
        success: function(response) {
            if (response.success) {
                showToast('Auto-saved successfully', 'success');
            }
        }
    });
}

function showToast(message, type = 'info') {
    const toast = $('#liveToast');
    toast.find('.toast-body').text(message);
    toast.addClass('text-bg-' + type);
    
    const bsToast = new bootstrap.Toast(toast);
    bsToast.show();
    
    setTimeout(() => {
        toast.removeClass('text-bg-' + type);
    }, 5000);
}

function initializeCharts() {
    // Application Status Chart
    const ctx1 = document.getElementById('statusChart');
    if (ctx1) {
        new Chart(ctx1, {
            type: 'doughnut',
            data: {
                labels: ['Pending', 'Approved', 'Rejected', 'Under Review'],
                datasets: [{
                    data: [12, 19, 3, 5],
                    backgroundColor: [
                        '#ffc107',
                        '#198754',
                        '#dc3545',
                        '#0dcaf0'
                    ]
                }]
            }
        });
    }
    
    // Course Popularity Chart
    const ctx2 = document.getElementById('courseChart');
    if (ctx2) {
        new Chart(ctx2, {
            type: 'bar',
            data: {
                labels: ['CS101', 'ME102', 'BT103', 'BCOM201', 'BBA202'],
                datasets: [{
                    label: 'Applications',
                    data: [65, 59, 80, 81, 56],
                    backgroundColor: 'rgba(67, 97, 238, 0.7)'
                }]
            }
        });
    }
}

// AJAX setup
$.ajaxSetup({
    beforeSend: function(xhr) {
        const token = $('meta[name="csrf_token"]').attr('content');
        if (token) {
            xhr.setRequestHeader('X-CSRF-TOKEN', token);
        }
    },
    error: function(xhr, status, error) {
        if (xhr.status === 401) {
            // Unauthorized - redirect to login
            window.location.href = baseUrl + 'login';
        } else if (xhr.status === 419) {
            // CSRF token mismatch
            showToast('Session expired. Please refresh the page.', 'danger');
        } else {
            showToast('An error occurred: ' + error, 'danger');
        }
    }
});

// Global variables
const baseUrl = $('meta[name="base_url"]').attr('content') || '/';