// js/script.js
document.addEventListener('DOMContentLoaded', function() {
    // Form validation
    const form = document.getElementById('studentForm');
    if (form) {
        form.addEventListener('submit', function(e) {
            // Validate phone numbers
            const fatherPhone = document.getElementById('father_phone');
            const motherPhone = document.getElementById('mother_phone');
            
            if (fatherPhone.value && !/^\d{11}$/.test(fatherPhone.value)) {
                e.preventDefault();
                alert('Father\'s phone must be exactly 11 digits');
                fatherPhone.focus();
                return false;
            }
            
            if (motherPhone.value && !/^\d{11}$/.test(motherPhone.value)) {
                e.preventDefault();
                alert('Mother\'s phone must be exactly 11 digits');
                motherPhone.focus();
                return false;
            }
            
            return true;
        });
    }
    
    // Auto-format phone numbers
    const phoneInputs = document.querySelectorAll('input[type="tel"]');
    phoneInputs.forEach(input => {
        input.addEventListener('input', function(e) {
            this.value = this.value.replace(/\D/g, '').substring(0, 11);
        });
    });
    
    // Initialize QR codes on student records page
    const qrElements = document.querySelectorAll('[id^="qrcode-"]');
    qrElements.forEach(element => {
        const studentId = element.id.replace('qrcode-', '');
        const studentData = element.getAttribute('data-student-info');
        
        if (studentData) {
            QRCode.toCanvas(element, studentData, 
                { width: 120, margin: 1 }, function(error) {
                    if (error) console.error(error);
                }
            );
        }
    });
});