<?php
session_start();

// ✅ تقييد الصفحة على الأدمن فقط
if (!isset($_SESSION['admin_id'])) {
    header("Location: admin_login.php");
    exit();
}
?>
<!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://fonts.googleapis.com/css2?family=Tajawal:wght@400;600;700&display=swap" rel="stylesheet">
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{
    font-family:'AL-BATTAR','Calibri','Tajawal',sans-serif;
    background:radial-gradient(circle at 0% 0%,#1b2540,#050814 70%);
    color:#fff;
    min-height:100vh;
    padding:20px;
}
.container{
    max-width:1280px;
    margin:0 auto;
}
header{
    display:flex;
    justify-content:space-between;
    align-items:center;
    margin-bottom:15px;
    gap:12px;
}
header h1{
    font-size:22px;
    margin-bottom:0;
}
header a{
    text-decoration:none;
    padding:7px 16px;
    border-radius:999px;
    background:linear-gradient(120deg,#00e6ff,#007bff);
    color:#fff;
    font-weight:600;
}
.subtitle{
    color:#a7b3d9;
    margin-bottom:20px;
}
.controls{
    background:rgba(15,23,42,0.9);
    border-radius:16px;
    padding:16px 18px;
    margin-bottom:20px;
    box-shadow:0 10px 30px rgba(0,0,0,0.35);
}
.controls-top{
    display:flex;
    flex-wrap:wrap;
    gap:10px;
    margin-bottom:14px;
}
.action-btn{
    border:none;
    border-radius:999px;
    padding:9px 18px;
    background:linear-gradient(135deg,#3b82f6,#22c55e);
    color:#fff;
    font-weight:700;
    cursor:pointer;
    box-shadow:0 8px 20px rgba(34,197,94,0.35);
}
.action-btn.secondary{
    background:linear-gradient(135deg,#6366f1,#3b82f6);
}
.action-btn.warning{
    background:linear-gradient(135deg,#f59e0b,#d97706);
    box-shadow:0 8px 20px rgba(245,158,11,0.28);
}
.action-btn.danger{
    background:linear-gradient(135deg,#ef4444,#dc2626);
    box-shadow:0 8px 20px rgba(239,68,68,0.28);
}
.fields-grid{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(200px,1fr));
    gap:12px;
}
.field{
    display:flex;
    flex-direction:column;
    gap:6px;
}
.field label{
    font-size:13px;
    color:#dbeafe;
}
.field input,
.field textarea{
    border-radius:10px;
    border:1px solid #323b5a;
    background:#020617;
    color:#e5e7eb;
    padding:9px 12px;
    font-family:inherit;
}
.field textarea{
    min-height:70px;
    resize:vertical;
}
.subjects-box{
    margin-top:14px;
    border-top:1px solid rgba(148,163,184,0.2);
    padding-top:14px;
}
.subjects-actions{
    display:flex;
    flex-wrap:wrap;
    gap:10px;
    margin-top:10px;
}
.note-box{
    color:#cbd5e1;
    font-size:13px;
    margin-top:10px;
    line-height:1.8;
}
.student-card-wrap{
    display:none;
}
.student-card-wrap.show{
    display:block;
}
.student-card{
    background-color:#f3f4f6;
    background-image:url('card-bg.png'), url('كارت برمجة.png');
    background-repeat:no-repeat, no-repeat;
    background-position:center center, center center;
    background-size:100% 100%, 100% 100%;
    color:#0f172a;
    border:1px solid rgba(15,23,42,0.18);
    border-radius:18px;
    box-shadow:0 12px 35px rgba(0,0,0,0.25);
    position:relative;
    overflow:hidden;
    padding:15px 18px 18px;
}
.student-card.compact .grades-table{
    font-size:11.2px;
}
.student-card.compact .grades-table th,
.student-card.compact .grades-table td{
    padding:4px 5px;
}
.student-card.compact .grade-input,
.student-card.compact .summary-input{
    font-size:12px;
}
.student-card.compact .subject-text{
    font-size:12px;
}
.student-card.ultra-compact .grades-table{
    font-size:10.3px;
}
.student-card.ultra-compact .grades-table th,
.student-card.ultra-compact .grades-table td{
    padding:3px 4px;
}
.student-card.ultra-compact .grade-input,
.student-card.ultra-compact .summary-input{
    font-size:11px;
}
.student-card.ultra-compact .subject-text{
    font-size:11px;
}
.student-card-inner{
    position:relative;
    z-index:2;
}
.card-header{
    position:relative;
    display:flex;
    justify-content:center;
    align-items:flex-start;
    min-height:110px;
    margin-bottom:10px;
}
.card-logo{
    position:absolute;
    top:0;
    right:0;
    width:110px;
    text-align:right;
    display:flex;
    justify-content:flex-end;
}
.card-logo img.school-logo{
    max-height:110px;
    max-width:100%;
    display:block;
}
.card-header-center{
    width:100%;
    padding:0 120px;
    text-align:center;
    line-height:1.45;
}
.school-top{
    font-weight:700;
    font-size:14px;
    color:#0f172a;
}
.school-ministry{
    font-weight:700;
    font-size:15px;
    color:#0f172a;
    margin-top:1px;
}
.school-name{
    font-weight:700;
    font-size:19px;
    font-family:'AL-BATTAR','Tajawal',sans-serif;
    letter-spacing:0.5px;
    color:#0f172a;
    margin-top:1px;
}
.card-title{
    font-size:14px;
    color:#c79a07;
    font-weight:700;
    margin-top:4px;
}
.card-meta{
    display:flex;
    flex-wrap:wrap;
    justify-content:center;
    align-items:center;
    gap:10px 26px;
    font-size:14px;
    margin-bottom:14px;
    text-align:center;
}
.meta-line{
    text-align:center;
}
.meta-line span{
    color:#334155;
    display:block;
    margin-bottom:2px;
}
.meta-line strong{
    color:#0f172a;
    font-weight:700;
    display:block;
}
.meta-line input{
    width:230px;
}
.meta-stage input,
.meta-class input{
    width:150px;
}
.card-inline-input,
.grade-input,
.result-input,
.notes-input{
    width:100%;
    border:none;
    outline:none;
    background:transparent;
    color:#0f172a;
    font-family:inherit;
    text-align:center;
    font-weight:700;
}
.card-inline-input{
    font-size:18px;
}
.meta-stage .card-inline-input,
.meta-class .card-inline-input{
    font-size:16px;
}
.grades-box{
    margin-bottom:12px;
}
.grades-table{
    width:100%;
    border-collapse:collapse;
    font-size:12.2px;
    background:rgba(255,255,255,0.96);
    table-layout:fixed;
}
.grades-table th,
.grades-table td{
    border:1px solid rgba(55,65,81,0.25);
    padding:6px 7px;
    text-align:center;
}
.grades-table th{
    background:rgba(2,6,23,0.92);
    font-weight:700;
    color:#ffffff;
}
.grades-table td.subject-col{
    text-align:center;
    font-weight:700;
    color:#0f172a;
}
.subject-text{
    display:block;
    width:100%;
    font-size:13.2px;
    line-height:1.35;
    white-space:normal;
    overflow-wrap:anywhere;
    word-break:break-word;
}
.grades-table .col-sem1,
.grades-table .col-mid,
.grades-table .col-sem2,
.grades-table .col-avg{
    box-shadow:inset 0 0 0 2px rgba(30,64,175,0.95);
}
.grades-table tbody tr:nth-child(odd){
    background:rgba(255,255,255,0.96);
}
.grades-table tbody tr:nth-child(even){
    background:rgba(241,245,249,0.96);
}
.grade-input{
    font-size:13px;
    min-width:48px;
}
.grade-input::placeholder,
.card-inline-input::placeholder,
.result-input::placeholder,
.notes-input::placeholder,
.summary-input::placeholder{
    color:#64748b;
    font-weight:600;
}
.summary-input{
    width:100%;
    border:none;
    outline:none;
    background:transparent;
    color:#0f172a;
    font-family:inherit;
    text-align:center;
    font-weight:700;
    font-size:13px;
}
.sections-row{
    display:flex;
    flex-wrap:wrap;
    gap:12px;
    margin-top:12px;
}
.section-box{
    flex:1 1 250px;
    background:rgba(255,255,255,0.90);
    border-radius:12px;
    padding:10px 12px;
    border:1px solid rgba(15,23,42,0.14);
    text-align:right;
}
.section-box h4{
    font-size:14px;
    margin-bottom:8px;
    color:#0f172a;
    text-align:right;
    padding-right:4px;
}
.section-box.result-box h4{
    border-bottom:2px solid #0f172a;
    display:inline-block;
    padding-bottom:2px;
}
.result-input{
    text-align:right;
    font-size:17px;
    min-height:34px;
}
.notes-input{
    text-align:right;
    min-height:68px;
    resize:none;
    font-size:15px;
}
.signatures-row{
    display:flex;
    justify-content:center;
    align-items:flex-end;
    gap:10px;
    margin-top:40px;
}
.sig-director{
    text-align:center;
    min-width:240px;
    padding-top:4px;
}
.sig-label{
    margin-bottom:1px;
    font-weight:700;
    color:#0f172a;
}
.sig-line{
    min-height:16px;
}
.director-name{
    font-weight:700;
    font-size:15px;
    letter-spacing:0.2px;
    padding-top:0;
    color:#0f172a;
}
.no-print{}

@page{
    size:A4 landscape;
    margin:4mm;
}

@media print{
    html, body{
        width:297mm;
        height:210mm;
    }
    body{
        font-family:'AL-BATTAR','Calibri','Tajawal',sans-serif;
        background:radial-gradient(circle at 10% 0%, #f9fafb 0%, #eef2ff 35%, #e0f2fe 65%, #f9fafb 100%);
        color:#000;
        padding:0;
        margin:0;
        -webkit-print-color-adjust:exact;
        print-color-adjust:exact;
    }
    .no-print{
        display:none !important;
    }
    .container{
        max-width:none !important;
        margin:0 !important;
        width:100% !important;
    }
    .student-card-wrap{
        display:block !important;
    }
    .student-card{
        background-color:#f3f4f6 !important;
        background-image:url('card-bg.png'), url('كارت برمجة.png') !important;
        background-repeat:no-repeat, no-repeat !important;
        background-position:center center, center center !important;
        background-size:100% 100%, 100% 100% !important;
        color:#000 !important;
        box-shadow:none !important;
        border:none !important;
        border-radius:0 !important;
        margin:0 !important;
        width:100% !important;
        height:202mm !important;
        min-height:202mm !important;
        padding:9px 10px !important;
        page-break-after:auto;
        page-break-inside:avoid;
        break-inside:avoid-page;
        position:relative;
        overflow:hidden;
        box-sizing:border-box;
    }
    .student-card-inner{
        min-height:100% !important;
        height:100% !important;
        display:flex !important;
        flex-direction:column !important;
    }
    .card-header{
        position:relative;
        display:flex;
        justify-content:center;
        align-items:flex-start;
        min-height:80px;
        margin-bottom:2px;
        flex:0 0 auto;
    }
    .card-logo{
        position:absolute;
        top:0;
        right:0;
        width:80px;
        text-align:right;
        display:flex;
        justify-content:flex-end;
    }
    .card-logo img.school-logo{
        max-height:80px;
        max-width:100%;
    }
    .card-header-center{
        width:100%;
        padding:0 84px;
        text-align:center;
        line-height:1.15;
    }
    .school-top{
        font-size:12px;
        text-align:center;
        color:#000;
        font-weight:700;
    }
    .school-ministry{
        font-size:13px;
        text-align:center;
        color:#000;
        font-weight:700;
    }
    .school-name{
        font-family:'AL-BATTAR','Tajawal',sans-serif;
        font-size:19px;
        letter-spacing:0.4px;
        text-align:center;
        color:#000;
        font-weight:700;
    }
    .card-title{
        font-size:12px;
        color:#b8860b;
        font-weight:700;
        text-align:center;
        margin-top:2px;
    }
    .card-meta{
        justify-content:center;
        text-align:center;
        gap:4px 16px;
        margin-bottom:3px;
        font-size:12px;
        flex:0 0 auto;
    }
    .meta-line span,
    .meta-line strong,
    .card-inline-input,
    .result-input,
    .notes-input,
    .summary-input,
    .grade-input{
        color:#000 !important;
        font-weight:700;
    }
    .card-inline-input{
        font-size:16px;
    }
    .meta-stage .card-inline-input,
    .meta-class .card-inline-input{
        font-size:14px;
    }
    .grades-box{
        margin-bottom:3px !important;
        flex:0 0 auto;
    }
    .grades-table{
        font-size:11.2px !important;
    }
    .grades-table th,
    .grades-table td{
        border-color:#000;
        padding:3.2px 4.2px !important;
    }
    .subject-text{
        font-size:11.6px;
    }
    .student-card.compact .grades-table{
        font-size:10.5px !important;
    }
    .student-card.compact .grades-table th,
    .student-card.compact .grades-table td{
        padding:2.8px 3.6px !important;
    }
    .student-card.compact .subject-text{
        font-size:10.8px !important;
    }
    .student-card.ultra-compact .grades-table{
        font-size:9.7px !important;
    }
    .student-card.ultra-compact .grades-table th,
    .student-card.ultra-compact .grades-table td{
        padding:2.3px 3px !important;
    }
    .student-card.ultra-compact .subject-text{
        font-size:9.8px !important;
    }
    .sections-row{
        display:flex !important;
        flex-wrap:nowrap !important;
        gap:12px;
        margin-top:6px !important;
        flex:0 0 auto;
    }
    .section-box{
        flex:1 1 0;
        background:rgba(255,255,255,0.90) !important;
        border-radius:12px !important;
        padding:10px 12px !important;
        border:1px solid rgba(15,23,42,0.14) !important;
        min-height:110px;
        box-sizing:border-box;
        box-shadow:none !important;
    }
    .result-input{
        min-height:28px;
        font-size:17px;
    }
    .notes-input{
        min-height:68px;
        font-size:14px;
    }
    .signatures-row{
        display:flex;
        justify-content:center;
        align-items:flex-end;
        gap:6px;
        margin-top:auto;
        padding-top:10px;
        padding-bottom:4px;
        font-size:11px;
        flex:0 0 auto;
    }
    .sig-director{
        min-width:180px;
        padding-top:0;
    }
    .sig-label{
        font-size:12px;
    }
    .sig-line{
        min-height:22px;
    }
    .director-name{
        font-size:13px;
    }
    .card-inline-input,
    .grade-input,
    .result-input,
    .notes-input,
    .summary-input{
        border:none !important;
        background:transparent !important;
        box-shadow:none !important;
    }
}
</style>
</head>
<body>
<header class="no-print">
    <h1>إنشاء كارت طالب يدوي للطباعة</h1>
    <a href="admin_dashboard.php">↩ العودة للوحة التحكم</a>
</header>

<div class="container">
    <div class="subtitle no-print">هذه الصفحة مستقلة للطباعة فقط. لا يوجد بها أي حفظ في قاعدة البيانات أو في أي مكان آخر.</div>

    <div class="controls no-print">
        <div class="controls-top">
            <button type="button" class="action-btn" onclick="showCard()">إنشاء كارت</button>
            <button type="button" class="action-btn warning" onclick="applySubjects()">تحديث المواد</button>
            <button type="button" class="action-btn secondary" onclick="window.print()">طباعة الكارت</button>
            <button type="button" class="action-btn danger" onclick="clearAllFields()">تفريغ الكارت</button>
        </div>

        <div class="fields-grid">
            <div class="field">
                <label for="student_name">اسم الطالب</label>
                <input type="text" id="student_name" placeholder="اكتب اسم الطالب" oninput="syncField('student_name', 'preview_name')">
            </div>
            <div class="field">
                <label for="student_stage">المرحلة</label>
                <input type="text" id="student_stage" placeholder="مثال: الأول المتوسط" oninput="syncField('student_stage', 'preview_stage')">
            </div>
            <div class="field">
                <label for="student_class">الشعبة</label>
                <input type="text" id="student_class" placeholder="مثال: A" oninput="syncField('student_class', 'preview_class')">
            </div>
            <div class="field">
                <label for="result_text">النتيجة</label>
                <input type="text" id="result_text" placeholder="مثال: ناجح" oninput="syncField('result_text', 'preview_result')">
            </div>
            <div class="field" style="grid-column:1/-1;">
                <label for="notes_text">الملاحظات</label>
                <textarea id="notes_text" placeholder="اكتب الملاحظات هنا" oninput="syncField('notes_text', 'preview_notes')"></textarea>
            </div>
        </div>

        <div class="subjects-box">
            <div class="field">
                <label for="subjects_list">المواد (ضع كل مادة في سطر مستقل)</label>
                <textarea id="subjects_list" placeholder="اكتب المواد هنا، كل مادة في سطر">التربية الاسلامية
اللغة العربية
اللغة الانكليزية
الرياضيات
الكيمياء
الاحياء
الفيزياء
الاجتماعيات
الحاسوب
اللغة الفرنسية
الاخلاقية
التربية الرياضية
التربية الفنية</textarea>
            </div>
            <div class="subjects-actions">
                <button type="button" class="action-btn warning" onclick="applySubjects()">إعادة بناء الجدول حسب المواد</button>
            </div>
        </div>

        <div class="note-box">أضف أو احذف المواد من مربع المواد ثم اضغط <strong>تحديث المواد</strong>. الكارت سيضبط نفسه تلقائيًا حسب عدد المواد المضافة، والمجموع والمعدل العام يُحسبان تلقائيًا من عمود المعدل السنوي فقط، بدون أي خزن.</div>
    </div>

    <div class="student-card-wrap" id="cardWrap">
        <div class="student-card" id="studentCard">
            <div class="student-card-inner">
                <div class="card-header">
                    <div class="card-logo">
                        <img src="bookk.png" alt="شعار المدرسة" class="school-logo">
                    </div>
                    <div class="card-header-center">
                        <div class="school-top">جمهورية العراق</div>
                        <div class="school-ministry">وزارة التربية</div>
                        <div class="school-name">ثانوية الأوائل الأهلية للبنين</div>
                        <div class="card-title">كارت الطالب للعام الدراسي 2025-2026</div>
                    </div>
                </div>

                <div class="card-meta">
                    <div class="meta-line meta-name"><span>اسم الطالب:</span><strong><input type="text" id="preview_name" class="card-inline-input" placeholder="اكتب اسم الطالب"></strong></div>
                    <div class="meta-line meta-stage"><span>المرحلة:</span><strong><input type="text" id="preview_stage" class="card-inline-input" placeholder="اكتب المرحلة"></strong></div>
                    <div class="meta-line meta-class"><span>الشعبة:</span><strong><input type="text" id="preview_class" class="card-inline-input" placeholder="اكتب الشعبة"></strong></div>
                </div>

                <div class="grades-box">
                    <table class="grades-table">
                        <thead>
                            <tr>
                                <th style="width:24%;">المادة</th>
                                <th class="col-sem1" style="width:12%;">فصل أول</th>
                                <th class="col-mid" style="width:12%;">نصف السنة</th>
                                <th class="col-sem2" style="width:12%;">فصل ثاني</th>
                                <th class="col-avg" style="width:16%;">المعدل السنوي</th>
                                <th style="width:24%;">النتيجة النهائية</th>
                            </tr>
                        </thead>
                        <tbody id="subjectsBody"></tbody>
                    </table>
                </div>

                <div class="sections-row">
                    <div class="section-box result-box">
                        <h4>النتيجة</h4>
                        <input type="text" id="preview_result" class="result-input" placeholder="اكتب النتيجة هنا">
                    </div>
                    <div class="section-box empty-box">
                        <h4>الملاحظات</h4>
                        <textarea id="preview_notes" class="notes-input" placeholder="اكتب الملاحظات هنا"></textarea>
                    </div>
                </div>

                <div class="signatures-row">
                    <div class="sig-col sig-director">
                        <div class="sig-label">توقيع المدير</div>
                        <div class="sig-line"></div>
                        <div class="director-name">أ. يوسف هيثم ابراهيم</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function showCard(){
    document.getElementById('cardWrap').classList.add('show');
    window.scrollTo({ top: document.getElementById('cardWrap').offsetTop - 10, behavior: 'smooth' });
}

function syncField(sourceId, targetId){
    document.getElementById(targetId).value = document.getElementById(sourceId).value;
}

function stripZeros(value){
    return value.replace(/\.00$/, '').replace(/(\.\d)0$/, '$1');
}

function escapeHtml(text){
    return text
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}

function getSubjectState(){
    var state = {};
    var rows = document.querySelectorAll('#subjectsBody tr.subject-row');
    for (var i = 0; i < rows.length; i++) {
        var key = rows[i].getAttribute('data-subject-key');
        if (!key) continue;
        var inputs = rows[i].querySelectorAll('input[type="text"]');
        state[key] = [];
        for (var j = 0; j < inputs.length; j++) {
            state[key].push(inputs[j].value);
        }
    }
    return state;
}

function createSubjectRow(subjectName, savedValues){
    var values = savedValues || ['', '', '', '', ''];
    return '' +
        '<tr class="subject-row" data-subject-key="' + encodeURIComponent(subjectName) + '">' +
            '<td class="subject-col"><span class="subject-text">' + escapeHtml(subjectName) + '</span></td>' +
            '<td><input type="text" class="grade-input" value="' + escapeHtml(values[0] || '') + '"></td>' +
            '<td><input type="text" class="grade-input" value="' + escapeHtml(values[1] || '') + '"></td>' +
            '<td><input type="text" class="grade-input" value="' + escapeHtml(values[2] || '') + '"></td>' +
            '<td><input type="text" class="grade-input annual-input" value="' + escapeHtml(values[3] || '') + '" oninput="calculateSummary()"></td>' +
            '<td><input type="text" class="grade-input" value="' + escapeHtml(values[4] || '') + '"></td>' +
        '</tr>';
}

function createSummaryRows(){
    return '' +
        '<tr class="sum-row">' +
            '<td class="subject-col"><span class="subject-text">المجموع</span></td>' +
            '<td></td>' +
            '<td></td>' +
            '<td></td>' +
            '<td><input type="text" id="total_annual" class="summary-input" readonly></td>' +
            '<td></td>' +
        '</tr>' +
        '<tr class="avg-row">' +
            '<td class="subject-col"><span class="subject-text">المعدل العام</span></td>' +
            '<td></td>' +
            '<td></td>' +
            '<td></td>' +
            '<td><input type="text" id="overall_average" class="summary-input" readonly></td>' +
            '<td></td>' +
        '</tr>';
}

function applySubjects(){
    var savedState = getSubjectState();
    var raw = document.getElementById('subjects_list').value.split(/\r?\n/);
    var subjects = [];
    var unique = {};

    for (var i = 0; i < raw.length; i++) {
        var item = raw[i].trim();
        if (item === '') continue;
        if (unique[item]) continue;
        unique[item] = true;
        subjects.push(item);
    }

    if (subjects.length === 0) {
        subjects = ['مادة واحدة'];
        document.getElementById('subjects_list').value = 'مادة واحدة';
    }

    var html = '';
    for (var s = 0; s < subjects.length; s++) {
        var key = encodeURIComponent(subjects[s]);
        html += createSubjectRow(subjects[s], savedState[key]);
    }

    html += createSummaryRows();
    document.getElementById('subjectsBody').innerHTML = html;
    adaptCardDensity(subjects.length);
    calculateSummary();
}

function adaptCardDensity(subjectCount){
    var card = document.getElementById('studentCard');
    card.classList.remove('compact');
    card.classList.remove('ultra-compact');

    if (subjectCount >= 15) {
        card.classList.add('compact');
    }
    if (subjectCount >= 19) {
        card.classList.remove('compact');
        card.classList.add('ultra-compact');
    }
}

function calculateSummary(){
    var inputs = document.querySelectorAll('.annual-input');
    var sum = 0;
    var count = 0;

    for (var i = 0; i < inputs.length; i++) {
        var raw = inputs[i].value.trim();
        if (raw === '' || raw === '-') continue;

        var normalized = raw.replace(/,/g, '.');
        var num = parseFloat(normalized);
        if (!isNaN(num)) {
            sum += num;
            count++;
        }
    }

    var totalField = document.getElementById('total_annual');
    var avgField = document.getElementById('overall_average');

    if (totalField) {
        totalField.value = count > 0 ? stripZeros(sum.toFixed(2)) : '';
    }
    if (avgField) {
        avgField.value = count > 0 ? stripZeros((sum / count).toFixed(2)) : '';
    }
}

function clearAllFields(){
    document.getElementById('student_name').value = '';
    document.getElementById('student_stage').value = '';
    document.getElementById('student_class').value = '';
    document.getElementById('result_text').value = '';
    document.getElementById('notes_text').value = '';
    document.getElementById('preview_name').value = '';
    document.getElementById('preview_stage').value = '';
    document.getElementById('preview_class').value = '';
    document.getElementById('preview_result').value = '';
    document.getElementById('preview_notes').value = '';

    var inputs = document.querySelectorAll('#subjectsBody input[type="text"]');
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].id === 'total_annual' || inputs[i].id === 'overall_average') continue;
        inputs[i].value = '';
    }

    var totalField = document.getElementById('total_annual');
    var avgField = document.getElementById('overall_average');
    if (totalField) totalField.value = '';
    if (avgField) avgField.value = '';
}

applySubjects();
</script>
</body>
</html>
