<!DOCTYPE html><html lang="ar" dir="rtl"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>وحدة ادخال الأعداد للأساتذة</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"><style>body{font-family:Arial,sans-serif;margin:20px;background-color:#f8f9fa}h1{color:#004085}table{width:100%;border-collapse:collapse;margin-top:20px}td,th{border:1px solid #ccc;padding:10px;text-align:right}th{background-color:#e9ecef}input{width:100%;box-sizing:border-box;padding:5px}input:focus{outline:2px solid #007bff;border-color:#007bff}.button{margin:10px 0}.commentInput{display:none}.file-details{background-color:#fff;padding:10px;border:1px solid #ddd;margin-bottom:20px}.file-details p{margin:0;display:inline-block;margin-right:10px}.modal-body{font-size:16px}.loading{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background-color:rgba(0,0,0,.5);justify-content:center;align-items:center;z-index:1000}.loading img{width:50px;height:50px}.special-values{display:flex;gap:5px;margin-top:5px}.special-value-btn{padding:2px 5px;background-color:#007bff;color:#fff;border:none;border-radius:3px;cursor:pointer}.special-value-btn:hover{background-color:#0056b3}.current-row{--bs-table-bg:#d7d7d7!important;background-color:var(--bs-table-bg)!important}#gradeTable thead th{position:sticky;top:0;background-color:#e9ecef;z-index:1}.container{padding-top:20px}.weight-input{width:50px;margin-left:5px}.weights-and-button{display:flex;align-items:center;gap:10px}.class-average{margin-top:20px;font-weight:700}</style></head><body><div class="container"><h1 class="text-center">وحدة ادخال الأعداد للأساتذة</h1><div class="form-check mb-3"><input class="form-check-input" type="checkbox" id="hideGuardianColumn" checked="checked"><label class="form-check-label" for="hideGuardianColumn">إخفاء عمود ولي الأمر</label></div><div class="form-check mb-3"><input class="form-check-input" type="checkbox" id="autoUpdateComments" checked="checked"><label class="form-check-label" for="autoUpdateComments">تحديث التعليقات تلقائياً أثناء كتابة الدرجات</label></div><button id="directoryButton" class="btn btn-primary mb-3 w-100">اختر المجلد</button><select id="fileSelector" class="form-select mb-3 d-none w-100"></select><div id="fileDetails" class="file-details mb-3 d-none"><p><strong>المؤسسة:</strong><span id="institution"></span></p><p><strong>الأستاذ:</strong><span id="teacher"></span></p><p><strong>فترة الامتحان:</strong><span id="examPeriod"></span></p><p><strong>السنة الدراسية:</strong><span id="academicYear"></span></p><p><strong>المندوبية:</strong><span id="delegation"></span></p><p><strong>اختصاص:</strong><span id="specialization"></span></p><p><strong>الصف:</strong><span id="className"></span></p></div><div id="weightsAndButton" class="mb-3 d-none"><div id="evaluationWeights" class="weights-and-button"></div><button class="btn btn-primary" id="generateCommentsButton">اضافة ملاحظات لجميع التلاميذ بصفة آلية</button></div><table class="table table-bordered d-none" id="gradeTable"><thead id="tableHeader"><tr><th>#</th><th>اسم التلميذ</th><th id="guardianColumn">ولي الأمر</th></tr></thead><tbody></tbody></table><div id="classAverage" class="class-average d-none"></div><button class="btn btn-success mb-3 w-100 d-none" id="saveButton">حفظ التغييرات</button><div class="loading" id="loading"><img src="https://cdnjs.cloudflare.com/ajax/libs/gifs/542/loading/loading-bars.svg" alt="Loading..."></div></div><div class="modal fade" id="errorModal" tabindex="-1" aria-labelledby="errorModalLabel" aria-hidden="true"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h5 class="modal-title" id="errorModalLabel">تصحيح الدرجة</h5><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button></div><div class="modal-body">يرجى إدخال درجة بين 0 و 20 أو استخدام القيم الخاصة كالآتي: "--.--", "معفى", "غ.ش."</div><div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal" id="closeModalBtn">إغلاق</button></div></div></div></div><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script><script>// Constants for repeated strings
        const SPECIAL_VALUES = ['معفى', 'غ.ش.', '--.--'];

        // Ensure getCommentForAverage is defined before it is used
        function getCommentForAverage(average) {
            if (average <= 4.0) return "نتائج هزيلة";
            if (average <= 6.0) return "نتائج ضعيفة جدا";
            if (average <= 8.0) return "نتائج ضعيفة";
            if (average < 10.0) return "دون المطلوب";
            if (average < 12.0) return "نتائج متوسطة";
            if (average < 14.0) return "نتائج مرضية";
            if (average < 15.0) return "نتائج قريبة من الحسن";
            if (average < 17.0) return "نتائج حسنة";
            if (average < 19.0) return "نتائج ممتازة";
            if (average <= 20.0) return "نتائج مشرفة";
            return "";
        }

        const directoryButton = document.getElementById('directoryButton');
        const fileSelector = document.getElementById('fileSelector');
        const fileDetails = document.getElementById('fileDetails');
        const institutionSpan = document.getElementById('institution');
        const teacherSpan = document.getElementById('teacher');
        const examPeriodSpan = document.getElementById('examPeriod');
        const academicYearSpan = document.getElementById('academicYear');
        const delegationSpan = document.getElementById('delegation');
        const specializationSpan = document.getElementById('specialization');
        const classNameSpan = document.getElementById('className');
        const evaluationWeightsContainer = document.getElementById('evaluationWeights');
        const generateCommentsButton = document.getElementById('generateCommentsButton');
        const tableHeader = document.getElementById('tableHeader');
        const gradeTable = document.getElementById('gradeTable').querySelector('tbody');
        const saveButton = document.getElementById('saveButton');
        const errorModal = new bootstrap.Modal(document.getElementById('errorModal'));
        const loading = document.getElementById('loading');
        const hideGuardianColumnCheckbox = document.getElementById('hideGuardianColumn');
        const guardianColumn = document.getElementById('guardianColumn');
        const closeModalBtn = document.getElementById('closeModalBtn');
        const classAverageDiv = document.getElementById('classAverage');
        const autoUpdateCommentsCheckbox = document.getElementById('autoUpdateComments');

        let directoryHandle = null;
        let fileHandles = new Map();
        let currentFileHandle = null;
        let xmlDoc = null;
        let isModalOpen = false;
        let currentRow = null;
        let evaluationWeights = {};
        let studentCommentsModified = {};

        // Ensure calculateStudentAverages is defined before it is used
        function calculateStudentAverages() {
            const rows = gradeTable.querySelectorAll('tr');
            let totalClassScore = 0;
            let totalClassWeight = 0;
            let studentCount = 0;
            let aboveAverageCount = 0;

            rows.forEach(row => {
                const gradeInputs = row.querySelectorAll('.gradeInput');
                let totalWeightedScore = 0;
                let totalWeight = 0;

                gradeInputs.forEach(input => {
                    const value = input.value.trim();
                    if (SPECIAL_VALUES.includes(value)) {
                        return;
                    }
                    const grade = parseFloat(value);
                    if (!isNaN(grade)) {
                        const evalCode = input.dataset.eval;
                        const weight = evaluationWeights[evalCode] || 1;
                        totalWeightedScore += grade * weight;
                        totalWeight += weight;
                    }
                });

                const average = totalWeight > 0 ? totalWeightedScore / totalWeight : 0;
                const averageCell = row.querySelector('.student-average');
                averageCell.textContent = isNaN(average) ? '--.--' : formatGrade(average);

                const studentId = row.querySelector('.summaryCommentInput').dataset.id;
                const summaryInput = row.querySelector('.summaryCommentInput');
                if (!studentCommentsModified[studentId]) {
                    summaryInput.value = getCommentForAverage(average);
                }

                if (average >= 10) {
                    aboveAverageCount++;
                }

                totalClassScore += totalWeightedScore;
                totalClassWeight += totalWeight;
                studentCount++;
            });

            const classAverage = totalClassWeight > 0 ? totalClassScore / totalClassWeight : 0;
            const aboveAveragePercentage = studentCount > 0 ? (aboveAverageCount / studentCount) * 100 : 0;

            classAverageDiv.textContent = `معدل الصف: ${formatGrade(classAverage)} - نسبة الطلاب فوق المعدل (10): ${aboveAveragePercentage.toFixed(2)}%`;
        }

        function updateStudentAverageAndComment(studentId) {
            const row = gradeTable.querySelector(`tr[data-id="${studentId}"]`);
            if (!row) return;

            const gradeInputs = row.querySelectorAll('.gradeInput');
            let totalWeightedScore = 0;
            let totalWeight = 0;

            gradeInputs.forEach(input => {
                const value = input.value.trim();
                if (SPECIAL_VALUES.includes(value)) {
                    return;
                }
                const grade = parseFloat(value);
                if (!isNaN(grade)) {
                    const evalCode = input.dataset.eval;
                    const weight = evaluationWeights[evalCode] || 1;
                    totalWeightedScore += grade * weight;
                    totalWeight += weight;
                }
            });

            const average = totalWeight > 0 ? totalWeightedScore / totalWeight : 0;
            const averageCell = row.querySelector('.student-average');
            averageCell.textContent = isNaN(average) ? '--.--' : formatGrade(average);

            const summaryInput = row.querySelector('.summaryCommentInput');
            if (!studentCommentsModified[studentId]) {
                summaryInput.value = getCommentForAverage(average);
            }

            calculateClassAverage();
        }

        function formatGrade(grade) {
            if (typeof grade === 'string' && SPECIAL_VALUES.includes(grade)) {
                return grade;
            }
            return isNaN(grade) ? '--.--' : parseFloat(grade).toFixed(2).padStart(5, '0');
        }

        directoryButton.addEventListener('click', async () => {
            try {
                directoryHandle = await window.showDirectoryPicker();
                showLoading();
                await loadXMLFiles();
                hideLoading();
            } catch (err) {
                hideLoading();
                console.error('خطأ في الوصول إلى المجلد:', err);
                alert('خطأ في الوصول إلى المجلد. يرجى المحاولة مرة أخرى.');
            }
        });

        async function loadXMLFiles() {
            fileHandles.clear();
            fileSelector.innerHTML = '<option value="">اختر صف</option>';
            
            for await (const entry of directoryHandle.values()) {
                if (entry.kind === 'file' && entry.name.endsWith('.xml')) {
                    try {
                        const file = await entry.getFile();
                        const text = await file.text();
                        const parser = new DOMParser();
                        const xmlDoc = parser.parseFromString(text, 'application/xml');
                        const className = xmlDoc.getElementsByTagName('libeclass')[0]?.textContent || entry.name;
                        const studentNumber = xmlDoc.getElementsByTagName('nbrEleve')[0]?.textContent || 'غير معروف';
                        fileHandles.set(entry.name, { handle: entry, className: className, studentNumber: studentNumber });
                        const option = document.createElement('option');
                        option.value = entry.name;
                        option.textContent = `${className} (${studentNumber} طالب)`;
                        fileSelector.appendChild(option);
                    } catch (err) {
                        console.error('خطأ في قراءة الملف:', entry.name, err);
                        alert(`خطأ في قراءة الملف ${entry.name}. يرجى التحقق منه.`);
                    }
                }
            }
            
            fileSelector.classList.remove('d-none');
            fileSelector.focus();
        }

        fileSelector.addEventListener('change', async function() {
            const fileName = fileSelector.value;
            if (fileName && fileHandles.has(fileName)) {
                currentFileHandle = fileHandles.get(fileName).handle;
                showLoading();
                try {
                    await loadFile(currentFileHandle);
                } catch (err) {
                    console.error('خطأ في تحميل الملف:', err);
                    alert('خطأ في تحميل الملف. يرجى المحاولة مرة أخرى.');
                } finally {
                    hideLoading();
                }
            }
        });

        async function loadFile(fileHandle) {
            const file = await fileHandle.getFile();
            const text = await file.text();
            const parser = new DOMParser();
            xmlDoc = parser.parseFromString(text, 'application/xml');

            // Check for parsing errors
            const parseError = xmlDoc.getElementsByTagName('parsererror')[0];
            if (parseError) {
                throw new Error('خطأ في تحليل ملف XML.');
            }

            displayFileDetails(xmlDoc);
            resetTable();
            displayGrades(xmlDoc);
            focusFirstInput();
            showUIElements();
        }

        function showUIElements() {
            fileDetails.classList.remove('d-none');
            evaluationWeightsContainer.classList.remove('d-none');
            generateCommentsButton.classList.remove('d-none');
            weightsAndButton.classList.remove('d-none');
            gradeTable.closest('table').classList.remove('d-none');
            classAverageDiv.classList.remove('d-none');
            saveButton.classList.remove('d-none');
        }

        saveButton.addEventListener('click', async function() {
            if (!currentFileHandle || !xmlDoc) {
                return;
            }

            try {
                showLoading();
                const students = xmlDoc.getElementsByTagName('noteelev');
                const gradeInputs = document.querySelectorAll('.gradeInput');
                
                gradeInputs.forEach(input => {
                    const studentId = input.dataset.id;
                    const evalCode = input.dataset.eval;
                    const newGrade = input.value.trim();
                    const formattedGrade = formatGrade(newGrade);
                    
                    for (const student of students) {
                        const id = student.getElementsByTagName('IDENELEV')[0].textContent;
                        const code = student.getElementsByTagName('CODETYPEEPRE')[0].textContent;
                        
                        if (id === studentId && code === evalCode) {
                            const noteElement = student.getElementsByTagName('NOTEEPRE')[0];
                            if (noteElement) {
                                noteElement.textContent = formattedGrade;
                            }
                            break;
                        }
                    }
                });

                const summaryInputs = document.querySelectorAll('.summaryCommentInput');
                summaryInputs.forEach(input => {
                    const studentId = input.dataset.id;
                    const newComment = input.value.trim();
                    
                    for (const student of students) {
                        const id = student.getElementsByTagName('IDENELEV')[0].textContent;
                        if (id === studentId) {
                            const commentElement = student.getElementsByTagName('obseprof')[0];
                            if (commentElement) {
                                commentElement.textContent = newComment;
                            }
                            break;
                        }
                    }
                });

                const writable = await currentFileHandle.createWritable();
                const serializer = new XMLSerializer();
                const updatedXML = serializer.serializeToString(xmlDoc);
                
                await writable.write(updatedXML);
                await writable.close();
                alert('تم حفظ الملف بنجاح!');
            } catch (err) {
                console.error('خطأ في حفظ الملف:', err);
                alert('خطأ في حفظ الملف. يرجى المحاولة مرة أخرى.');
            } finally {
                hideLoading();
            }
        });

        function displayFileDetails(xmlDoc) {
            const institution = xmlDoc.getElementsByTagName('libeetab')[0]?.textContent || 'غير متاح';
            const teacher = xmlDoc.getElementsByTagName('libens')[0]?.textContent || 'غير متاح';
            const examPeriod = xmlDoc.getElementsByTagName('libperiodexam')[0]?.textContent || 'غير متاح';
            const academicYear = xmlDoc.getElementsByTagName('nbrclass')[0]?.textContent || 'غير متاح';
            const delegation = xmlDoc.getElementsByTagName('drear')[0]?.textContent || 'غير متاح';
            const specialization = xmlDoc.getElementsByTagName('libedisc')[0]?.textContent || 'غير متاح';
            const className = xmlDoc.getElementsByTagName('libeclass')[0]?.textContent || 'غير متاح';

            institutionSpan.textContent = institution;
            teacherSpan.textContent = teacher;
            examPeriodSpan.textContent = examPeriod;
            academicYearSpan.textContent = academicYear;
            delegationSpan.textContent = delegation;
            specializationSpan.textContent = specialization;
            classNameSpan.textContent = className;

            fileDetails.classList.remove('d-none');
        }

        function resetTable() {
            const headerRow = tableHeader.rows[0];
            while (headerRow.cells.length > 3) {
                headerRow.deleteCell(3);
            }
            gradeTable.innerHTML = '';
            studentCommentsModified = {};
        }

        function displayGrades(xmlDoc) {
            const students = xmlDoc.getElementsByTagName('noteelev');
            const evaluations = xmlDoc.getElementsByTagName('typeepr');

            const evaluationTypes = [];
            for (const evalType of evaluations) {
                const code = evalType.getElementsByTagName('CODETYPEEPRE')[0].textContent;
                const label = evalType.getElementsByTagName('libTypeEpr')[0].textContent;
                evaluationTypes.push({ code, label });
            }

            const headerRow = tableHeader.rows[0];
            evaluationTypes.forEach(evalType => {
                const th = document.createElement('th');
                th.textContent = evalType.label;
                th.innerHTML += `
                    <div class="special-values">
                        <button class="special-value-btn" onclick="setGradeInCurrentRow('${evalType.code}', '--.--')">--.--</button>
                        <button class="special-value-btn" onclick="setGradeInCurrentRow('${evalType.code}', 'معفى')">معفى</button>
                        <button class="special-value-btn" onclick="setGradeInCurrentRow('${evalType.code}', 'غ.ش.')">غ.ش.</button>
                    </div>
                `;
                headerRow.appendChild(th);
            });

            const averageTh = document.createElement('th');
            averageTh.textContent = 'معدل الطالب';
            headerRow.appendChild(averageTh);

            const th = document.createElement('th');
            th.textContent = 'ملاحظات';
            headerRow.appendChild(th);

            const studentMap = {};
            for (const student of students) {
                const id = student.getElementsByTagName('IDENELEV')[0].textContent;
                if (!studentMap[id]) {
                    studentMap[id] = {
                        numOrdre: student.getElementsByTagName('numOrdre')[0].textContent,
                        prenomnom: student.getElementsByTagName('prenomnom')[0].textContent,
                        prenomtute: student.getElementsByTagName('prenomtute')[0].textContent,
                        grades: {},
                        summaryComment: ''
                    };
                }

                const evalCode = student.getElementsByTagName('CODETYPEEPRE')[0].textContent;
                studentMap[id].grades[evalCode] = {
                    grade: student.getElementsByTagName('NOTEEPRE')[0]?.textContent || '--.--',
                    comment: student.getElementsByTagName('obseprof')[0]?.textContent || ''
                };
            }

            for (const studentId in studentMap) {
                const student = studentMap[studentId];
                const row = document.createElement('tr');
                row.dataset.id = studentId;

                row.innerHTML = `
                    <td>${student.numOrdre}</td>
                    <td>${student.prenomnom}</td>
                    <td id="guardian-${studentId}">${student.prenomtute}</td>
                `;

                evaluationTypes.forEach(evalType => {
                    const evalData = student.grades[evalType.code] || { grade: '--.--', comment: '' };
                    const inputId = `gradeInput-${studentId}-${evalType.code}`;
                    const cell = document.createElement('td');
                    const formattedGrade = formatGrade(evalData.grade);
                    cell.innerHTML = `
                        <div>
                            <input type="text" id="${inputId}" value="${formattedGrade}" class="gradeInput" data-id="${studentId}" data-eval="${evalType.code}" maxlength="5" aria-label="${evalType.label} لطالب ${student.prenomnom}">
                        </div>
                    `;
                    row.appendChild(cell);
                });

                const averageCell = document.createElement('td');
                averageCell.classList.add('student-average');
                averageCell.textContent = '--.--';
                row.appendChild(averageCell);

                const summaryCell = document.createElement('td');
                const summaryInput = document.createElement('input');
                summaryInput.type = 'text';
                summaryInput.value = student.summaryComment;
                summaryInput.className = 'summaryCommentInput';
                summaryInput.dataset.id = studentId;
                summaryInput.placeholder = 'ملاحظات';
                summaryInput.addEventListener('input', function() {
                    studentCommentsModified[studentId] = true;
                });
                summaryCell.appendChild(summaryInput);
                row.appendChild(summaryCell);

                gradeTable.appendChild(row);
            }

            attachInputListeners();
            toggleGuardianColumn();
            initializeWeights(evaluationTypes);
            calculateStudentAverages();
        }

        function initializeWeights(evaluationTypes) {
            evaluationWeightsContainer.innerHTML = '';
            evaluationTypes.forEach(evalType => {
                const weightInput = document.createElement('input');
                weightInput.type = 'number';
                weightInput.className = 'weight-input';
                weightInput.value = '1';
                weightInput.min = '0';
                weightInput.step = '0.1';
                weightInput.dataset.code = evalType.code;
                weightInput.placeholder = 'وزن';
                weightInput.ariaLabel = `وزن ${evalType.label}`;

                const weightLabel = document.createElement('label');
                weightLabel.textContent = `${evalType.label}:`;

                evaluationWeightsContainer.appendChild(weightLabel);
                evaluationWeightsContainer.appendChild(weightInput);
                evaluationWeights[evalType.code] = 1;

                weightInput.addEventListener('input', function() {
                    evaluationWeights[evalType.code] = parseFloat(this.value) || 1;
                    calculateStudentAverages();
                });
            });
        }

        function focusFirstInput() {
            const firstInput = gradeTable.querySelector('input.gradeInput');
            if (firstInput) {
                firstInput.focus();
            }
        }

        function attachInputListeners() {
            const gradeInputs = gradeTable.querySelectorAll('.gradeInput');

            gradeInputs.forEach(input => {
                input.addEventListener('focus', function () {
                    input.select();
                    // Highlight the current row
                    const row = input.closest('tr');
                    currentRow = row;
                    row.classList.add('current-row');
                });

                input.addEventListener('blur', function () {
                    const row = input.closest('tr');
                    row.classList.remove('current-row');

                    const value = input.value.trim();

                    // Validate input
                    if (
                        value !== '' &&
                        (isNaN(parseFloat(value)) && !SPECIAL_VALUES.includes(value)) ||
                        parseFloat(value) < 0 ||
                        parseFloat(value) > 20
                    ) {
                        if (!isModalOpen) {
                            isModalOpen = true;
                            errorModal.show();
                            errorModal._element.addEventListener('hidden.bs.modal', () => {
                                isModalOpen = false;
                                input.focus();
                            }, { once: true });
                        }
                    } else {
                        const formattedGrade = formatGrade(value);
                        input.value = formattedGrade;
                        const studentId = input.dataset.id;
                        if (autoUpdateCommentsCheckbox.checked) {
                            updateStudentAverageAndComment(studentId);
                        }
                    }
                });

                input.addEventListener('input', function() {
                    if (autoUpdateCommentsCheckbox.checked) {
                        const studentId = input.dataset.id;
                        updateStudentAverageAndComment(studentId);
                    }
                });
            });

            gradeTable.addEventListener('keydown', function (event) {
                if (event.key === 'Enter') {
                    const currentInput = event.target;
                    if (currentInput.tagName === 'INPUT') {
                        const inputs = Array.from(gradeTable.querySelectorAll('input.gradeInput'));
                        const currentIndex = inputs.indexOf(currentInput);
                        const nextInput = inputs[currentIndex + 1];

                        if (nextInput) {
                            nextInput.focus();
                            event.preventDefault();
                        }
                    }
                }
            });

            closeModalBtn.addEventListener('keydown', function (event) {
                if (event.key === 'Enter') {
                    errorModal.hide();
                }
            });
        }

        function setGradeInCurrentRow(evalCode, value) {
            if (currentRow) {
                const input = currentRow.querySelector(`.gradeInput[data-eval="${evalCode}"]`);
                if (input) {
                    input.value = formatGrade(value);
                    if (value === 'معفى') {
                        setAllGradesToExempt(input.dataset.id);
                    }
                }
            }
        }

        function setAllGradesToExempt(studentId) {
            const gradeInputs = gradeTable.querySelectorAll(`.gradeInput[data-id="${studentId}"]`);
            gradeInputs.forEach(input => {
                input.value = 'معفى';
            });
            const summaryInput = gradeTable.querySelector(`.summaryCommentInput[data-id="${studentId}"]`);
            if (summaryInput) {
                summaryInput.value = 'معفى';
                studentCommentsModified[studentId] = true;
            }
            if (autoUpdateCommentsCheckbox.checked) {
                updateStudentAverageAndComment(studentId);
            }
        }

        generateCommentsButton.addEventListener('click', function() {
            const rows = gradeTable.querySelectorAll('tr');
            rows.forEach(row => {
                const studentId = row.querySelector('.summaryCommentInput').dataset.id;
                updateStudentAverageAndComment(studentId);
            });
        });

        function calculateClassAverage() {
            const rows = gradeTable.querySelectorAll('tr');
            let totalClassScore = 0;
            let totalClassWeight = 0;
            let studentCount = 0;
            let aboveAverageCount = 0;

            rows.forEach(row => {
                const gradeInputs = row.querySelectorAll('.gradeInput');
                let totalWeightedScore = 0;
                let totalWeight = 0;

                gradeInputs.forEach(input => {
                    const value = input.value.trim();
                    if (SPECIAL_VALUES.includes(value)) {
                        return;
                    }
                    const grade = parseFloat(value);
                    if (!isNaN(grade)) {
                        const evalCode = input.dataset.eval;
                        const weight = evaluationWeights[evalCode] || 1;
                        totalWeightedScore += grade * weight;
                        totalWeight += weight;
                    }
                });

                const average = totalWeight > 0 ? totalWeightedScore / totalWeight : 0;

                if (average >= 10) {
                    aboveAverageCount++;
                }

                totalClassScore += totalWeightedScore;
                totalClassWeight += totalWeight;
                studentCount++;
            });

            const classAverage = totalClassWeight > 0 ? totalClassScore / totalClassWeight : 0;
            const aboveAveragePercentage = studentCount > 0 ? (aboveAverageCount / studentCount) * 100 : 0;

            classAverageDiv.textContent = `معدل الصف: ${formatGrade(classAverage)} - نسبة الطلاب فوق المعدل (10): ${aboveAveragePercentage.toFixed(2)}%`;
        }

        function showLoading() {
            loading.style.display = 'flex';
        }

        function hideLoading() {
            loading.style.display = 'none';
        }

        hideGuardianColumnCheckbox.addEventListener('change', toggleGuardianColumn);

        function toggleGuardianColumn() {
            const guardianCells = gradeTable.querySelectorAll('td[id^="guardian-"]');
            guardianCells.forEach(cell => {
                cell.style.display = hideGuardianColumnCheckbox.checked ? 'none' : 'table-cell';
            });
            guardianColumn.style.display = hideGuardianColumnCheckbox.checked ? 'none' : 'table-cell';
        }

        autoUpdateCommentsCheckbox.addEventListener('change', function() {
            if (this.checked) {
                calculateStudentAverages();
            }
        });</script></body></html>