// School Management System JavaScript

// Global variables
let currentPage = 1;
let itemsPerPage = 10;

// Initialize when document is ready
document.addEventListener('DOMContentLoaded', function() {
    initializeComponents();
    setupEventListeners();
    loadDashboardData();
});

// Initialize components
function initializeComponents() {
    // Initialize tooltips
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
    
    // Initialize popovers
    var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
    var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
        return new bootstrap.Popover(popoverTriggerEl);
    });
    
    // Add fade-in animation to cards (skip notice modal content to avoid flicker)
    const cards = document.querySelectorAll('.card');
    cards.forEach((card, index) => {
        // If inside a notice modal, skip animation
        if (card.closest('.modal') && card.classList.contains('notice-card')) return;
        card.style.animationDelay = `${index * 0.1}s`;
        card.classList.add('fade-in-up');
    });
}

// Setup event listeners
function setupEventListeners() {
    // Search functionality
    const searchInputs = document.querySelectorAll('.search-input');
    searchInputs.forEach(input => {
        input.addEventListener('input', debounce(handleSearch, 300));
    });
    
    // Form validation
    const forms = document.querySelectorAll('.needs-validation');
    forms.forEach(form => {
        form.addEventListener('submit', handleFormSubmit);
    });
    
    // Delete confirmations
    const deleteButtons = document.querySelectorAll('.btn-delete');
    deleteButtons.forEach(button => {
        button.addEventListener('click', handleDeleteConfirmation);
    });
    
    // File upload
    const fileInputs = document.querySelectorAll('input[type="file"]');
    fileInputs.forEach(input => {
        input.addEventListener('change', handleFileUpload);
    });
    
    // Print buttons
    const printButtons = document.querySelectorAll('.btn-print');
    printButtons.forEach(button => {
        button.addEventListener('click', handlePrint);
    });
    
    // Export buttons
    const exportButtons = document.querySelectorAll('.btn-export');
    exportButtons.forEach(button => {
        button.addEventListener('click', handleExport);
    });
}

// Load dashboard data
function loadDashboardData() {
    // This would typically make AJAX calls to get real-time data
    updateDashboardStats();
    loadRecentActivities();
    loadNotices();
}

// Update dashboard statistics
function updateDashboardStats() {
    // Animate numbers
    const statNumbers = document.querySelectorAll('.stat-number');
    statNumbers.forEach(element => {
        const target = parseInt(element.textContent);
        animateNumber(element, 0, target, 2000);
    });
}

// Animate numbers
function animateNumber(element, start, end, duration) {
    const range = end - start;
    const increment = range / (duration / 16);
    let current = start;
    
    const timer = setInterval(() => {
        current += increment;
        if (current >= end) {
            current = end;
            clearInterval(timer);
        }
        element.textContent = Math.floor(current);
    }, 16);
}

// Handle search
function handleSearch(event) {
    const searchTerm = event.target.value.toLowerCase();
    const searchableElements = document.querySelectorAll('.searchable');
    
    searchableElements.forEach(element => {
        const text = element.textContent.toLowerCase();
        const row = element.closest('tr') || element.closest('.card');
        
        if (text.includes(searchTerm)) {
            row.style.display = '';
        } else {
            row.style.display = 'none';
        }
    });
}

// Handle form submission
function handleFormSubmit(event) {
    const form = event.target;
    
    if (!form.checkValidity()) {
        event.preventDefault();
        event.stopPropagation();
    }
    
    form.classList.add('was-validated');
    
    // Show loading spinner
    const submitButton = form.querySelector('button[type="submit"]');
    if (submitButton) {
        const originalText = submitButton.innerHTML;
        submitButton.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span> প্রক্রিয়াকরণ...';
        submitButton.disabled = true;
        
        // Re-enable button after 3 seconds (adjust based on actual processing time)
        setTimeout(() => {
            submitButton.innerHTML = originalText;
            submitButton.disabled = false;
        }, 3000);
    }
}

// Handle delete confirmation
function handleDeleteConfirmation(event) {
    event.preventDefault();
    
    const button = event.currentTarget;
    const itemName = button.dataset.itemName || 'এই আইটেম';
    
    if (confirm(`আপনি কি নিশ্চিত যে ${itemName} মুছে ফেলতে চান? এই কাজটি পূর্বাবস্থায় ফেরানো যাবে না।`)) {
        // Show loading message
        const originalText = button.innerHTML;
        button.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span> মুছে ফেলা হচ্ছে...';
        button.disabled = true;
        
        // Proceed with deletion after a short delay to show the loading message
        setTimeout(() => {
            const deleteUrl = button.href || button.dataset.deleteUrl;
            if (deleteUrl) {
                window.location.href = deleteUrl;
            }
        }, 100);
    }
}

// Handle file upload
function handleFileUpload(event) {
    const file = event.target.files[0];
    const maxSize = 5 * 1024 * 1024; // 5MB
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];
    
    if (file) {
        // Check file size
        if (file.size > maxSize) {
            showAlert('ফাইলের আকার ৫ MB এর বেশি হতে পারবে না।', 'danger');
            event.target.value = '';
            return;
        }
        
        // Check file type
        if (!allowedTypes.includes(file.type)) {
            showAlert('শুধুমাত্র JPG, PNG, GIF এবং PDF ফাইল আপলোড করা যাবে।', 'danger');
            event.target.value = '';
            return;
        }
        
        // Show preview for images
        if (file.type.startsWith('image/')) {
            const reader = new FileReader();
            reader.onload = function(e) {
                const preview = document.querySelector('.image-preview');
                if (preview) {
                    preview.src = e.target.result;
                    preview.style.display = 'block';
                }
            };
            reader.readAsDataURL(file);
        }
        
        showAlert('ফাইল সফলভাবে নির্বাচিত হয়েছে।', 'success');
    }
}

// Handle print
function handlePrint(event) {
    event.preventDefault();
    
    const printContent = document.querySelector('.print-content');
    if (printContent) {
        const originalContent = document.body.innerHTML;
        document.body.innerHTML = printContent.innerHTML;
        window.print();
        document.body.innerHTML = originalContent;
        location.reload(); // Reload to restore event listeners
    } else {
        window.print();
    }
}

// Handle export
function handleExport(event) {
    event.preventDefault();
    
    const button = event.target;
    const exportType = button.dataset.exportType || 'excel';
    const exportUrl = button.href || button.dataset.exportUrl;
    
    if (exportUrl) {
        // Show loading
        const originalText = button.innerHTML;
        button.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span> এক্সপোর্ট করা হচ্ছে...';
        button.disabled = true;
        
        // Create a temporary link to download
        const link = document.createElement('a');
        link.href = exportUrl;
        link.download = '';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        // Restore button
        setTimeout(() => {
            button.innerHTML = originalText;
            button.disabled = false;
        }, 2000);
    }
}

// Show alert message
function showAlert(message, type = 'info', duration = 5000) {
    const alertContainer = document.querySelector('.alert-container') || document.body;
    
    const alert = document.createElement('div');
    alert.className = `alert alert-${type} alert-dismissible fade show`;
    alert.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    alertContainer.insertBefore(alert, alertContainer.firstChild);
    
    // Auto dismiss
    setTimeout(() => {
        if (alert.parentNode) {
            alert.remove();
        }
    }, duration);
}

// Debounce function
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// Load recent activities
function loadRecentActivities() {
    // This would typically make an AJAX call
    // For now, we'll just add some animation to existing activities
    const activityRows = document.querySelectorAll('.recent-activities tr');
    activityRows.forEach((row, index) => {
        row.style.animationDelay = `${index * 0.1}s`;
        row.classList.add('fade-in-up');
    });
}

// Load notices
function loadNotices() {
    // This would typically make an AJAX call
    // For now, we'll just add some animation to existing notices
    const notices = document.querySelectorAll('.notice-item');
    notices.forEach((notice, index) => {
        notice.style.animationDelay = `${index * 0.1}s`;
        notice.classList.add('fade-in-up');
    });
}

// Pagination
function setupPagination(totalItems, currentPage, itemsPerPage) {
    const totalPages = Math.ceil(totalItems / itemsPerPage);
    const paginationContainer = document.querySelector('.pagination-container');
    
    if (!paginationContainer || totalPages <= 1) return;
    
    let paginationHTML = '<nav><ul class="pagination justify-content-center">';
    
    // Previous button
    paginationHTML += `
        <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
            <a class="page-link" href="#" data-page="${currentPage - 1}">পূর্ববর্তী</a>
        </li>
    `;
    
    // Page numbers
    for (let i = 1; i <= totalPages; i++) {
        if (i === 1 || i === totalPages || (i >= currentPage - 2 && i <= currentPage + 2)) {
            paginationHTML += `
                <li class="page-item ${i === currentPage ? 'active' : ''}">
                    <a class="page-link" href="#" data-page="${i}">${i}</a>
                </li>
            `;
        } else if (i === currentPage - 3 || i === currentPage + 3) {
            paginationHTML += '<li class="page-item disabled"><span class="page-link">...</span></li>';
        }
    }
    
    // Next button
    paginationHTML += `
        <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
            <a class="page-link" href="#" data-page="${currentPage + 1}">পরবর্তী</a>
        </li>
    `;
    
    paginationHTML += '</ul></nav>';
    paginationContainer.innerHTML = paginationHTML;
    
    // Add click handlers
    const pageLinks = paginationContainer.querySelectorAll('.page-link');
    pageLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            const page = parseInt(this.dataset.page);
            if (page && page !== currentPage) {
                loadPage(page);
            }
        });
    });
}

// Load page
function loadPage(page) {
    currentPage = page;
    // This would typically make an AJAX call to load the page data
    // For now, we'll just update the pagination
    const totalItems = parseInt(document.querySelector('.total-items')?.textContent) || 0;
    setupPagination(totalItems, currentPage, itemsPerPage);
}

// Format date
function formatDate(dateString, format = 'dd/mm/yyyy') {
    const date = new Date(dateString);
    const day = String(date.getDate()).padStart(2, '0');
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const year = date.getFullYear();
    
    switch (format) {
        case 'dd/mm/yyyy':
            return `${day}/${month}/${year}`;
        case 'mm/dd/yyyy':
            return `${month}/${day}/${year}`;
        case 'yyyy-mm-dd':
            return `${year}-${month}-${day}`;
        default:
            return `${day}/${month}/${year}`;
    }
}

// Format currency
function formatCurrency(amount, currency = '৳') {
    return `${currency} ${parseFloat(amount).toLocaleString('bn-BD', {minimumFractionDigits: 2})}`;
}

// Validate form fields
function validateField(field) {
    const value = field.value.trim();
    const type = field.type;
    const required = field.hasAttribute('required');
    
    // Clear previous validation
    field.classList.remove('is-valid', 'is-invalid');
    
    // Check if required field is empty
    if (required && !value) {
        field.classList.add('is-invalid');
        return false;
    }
    
    // Validate email
    if (type === 'email' && value) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(value)) {
            field.classList.add('is-invalid');
            return false;
        }
    }
    
    // Validate phone
    if (field.name === 'phone' && value) {
        const phoneRegex = /^[0-9+\-\s()]+$/;
        if (!phoneRegex.test(value) || value.length < 10) {
            field.classList.add('is-invalid');
            return false;
        }
    }
    
    // If we get here, field is valid
    if (value) {
        field.classList.add('is-valid');
    }
    return true;
}

// Auto-save form data to localStorage
function autoSaveForm(formId) {
    const form = document.getElementById(formId);
    if (!form) return;
    
    const inputs = form.querySelectorAll('input, select, textarea');
    
    // Load saved data
    inputs.forEach(input => {
        const savedValue = localStorage.getItem(`${formId}_${input.name}`);
        if (savedValue && !input.value) {
            input.value = savedValue;
        }
    });
    
    // Save data on change
    inputs.forEach(input => {
        input.addEventListener('change', function() {
            localStorage.setItem(`${formId}_${this.name}`, this.value);
        });
    });
    
    // Clear saved data on successful submit
    form.addEventListener('submit', function() {
        inputs.forEach(input => {
            localStorage.removeItem(`${formId}_${input.name}`);
        });
    });
}

// Initialize charts (if Chart.js is loaded)
function initializeCharts() {
    if (typeof Chart === 'undefined') return;
    
    // Attendance chart
    const attendanceCtx = document.getElementById('attendanceChart');
    if (attendanceCtx) {
        new Chart(attendanceCtx, {
            type: 'line',
            data: {
                labels: ['জানুয়ারি', 'ফেব্রুয়ারি', 'মার্চ', 'এপ্রিল', 'মে', 'জুন'],
                datasets: [{
                    label: 'উপস্থিতির হার',
                    data: [85, 88, 92, 89, 94, 91],
                    borderColor: '#667eea',
                    backgroundColor: 'rgba(102, 126, 234, 0.1)',
                    tension: 0.4
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 100
                    }
                }
            }
        });
    }
    
    // Results chart
    const resultsCtx = document.getElementById('resultsChart');
    if (resultsCtx) {
        new Chart(resultsCtx, {
            type: 'doughnut',
            data: {
                labels: ['A+', 'A', 'A-', 'B+', 'B', 'C+', 'C', 'D', 'F'],
                datasets: [{
                    data: [15, 25, 20, 18, 12, 8, 5, 3, 2],
                    backgroundColor: [
                        '#28a745', '#20c997', '#17a2b8', '#007bff',
                        '#6f42c1', '#e83e8c', '#fd7e14', '#ffc107', '#dc3545'
                    ]
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });
    }
}

// Initialize on load
window.addEventListener('load', function() {
    initializeCharts();
});

// Export functions for global use
window.SchoolMS = {
    showAlert,
    formatDate,
    formatCurrency,
    validateField,
    autoSaveForm,
    setupPagination,
    loadPage
};