<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Exam Performance & Attendance Report</title>
    <style type="text/css">
        .nav-tabs-custom>.nav-tabs>li.active { border-top-color: #faa21c; }

        body { font-family: Arial, sans-serif; margin: 12px; color: #222; }
        h1,h3,h4 { margin: 6px 0; }

        /* Horizontal filter layout */
        .horizontal-filters {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            margin-bottom: 20px;
        }

        .filter-row { display: flex; width: 100%; gap: 15px; }
        .filter-row .form-group { flex: 1; min-width: 200px; }

        label { display:block; margin-bottom:6px; font-weight:600; }
        select.form-control { width:100%; padding:7px; border:1px solid #ccc; border-radius:4px; }

        .search-button-container {
            width: 100%;
            display: flex;
            justify-content: flex-end;
            margin-top: 10px;
        }

        .btn-search {
            background-color: #faa21c;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-weight: bold;
        }
        .btn-search:hover { background-color: #e8910c; }

        .btn-secondary {
            background: #f0f0f0;
            border:1px solid #ddd;
            padding:8px 12px;
            border-radius:4px;
            cursor:pointer;
        }
        .btn-link {
            background:none;
            border:none;
            color:#007bff;
            cursor:pointer;
            text-decoration:underline;
            padding:0;
            font-size:14px;
        }

        .table { width: 100%; border-collapse: collapse; margin-bottom: 10px; }
        .table th, .table td { border: 1px solid #ddd; padding: 8px; }
        .table th { text-align: left; background-color: #f5f5f5; }
        .table tbody td { vertical-align: middle; }
        .table-responsive { overflow-x: auto; margin-top:12px; }

        .center { text-align:center; }
        .right { text-align:right; }

        @media (max-width: 768px) {
            .filter-row { flex-direction: column; }
            .search-button-container { justify-content: center; }
        }
    </style>
</head>
<body>
    <h1>Term Reports</h1>
    <div class="content-wrapper" style="min-height: 200px;">
        <section class="content">
            <div class="box box-primary">
                <div class="box-body">
                    <form id="reportForm" class="form-horizontal" onsubmit="return false;">
                        <div class="horizontal-filters">
                            <div class="filter-row">
                                <div class="form-group">
                                    <label>Education Level</label>
                                    <select id="report_type" name="report_type" class="form-control">
                                        <option value="">Choose Level</option>
                                        <option value="preschool">Pre School</option>
                                        <option value="primary">Primary</option>
                                        <option value="secondary">Secondary</option>
                                    </select>
                                </div>

                                <div class="form-group">
                                    <label>Learner Level</label>
                                    <select name="learner_level" id="learner_level" class="form-control">
                                        <option value="">Select Learner Level</option>
                                    </select>
                                </div>
                            </div>

                            <div class="filter-row">
                                <div class="form-group">
                                    <label>Learner Name</label>
                                    <select name="learner_name" id="learner_name" class="form-control">
                                        <option value="">Select Learner</option>
                                    </select>
                                </div>

                                <div class="form-group">
                                    <label>Term</label>
                                    <select name="exam_type" id="exam_type" class="form-control">
                                        <option value="">Select Term</option>
                                        <option value="term1">First Term</option>
                                        <option value="term2">Second Term</option>
                                        <option value="term3">Third Term</option>
                                    </select>
                                </div>
                            </div>

                            <div class="search-button-container">
                                <button type="button" class="btn-search" id="searchBtn">
                                    <i class="fa fa-search"></i> Search
                                </button>
                            </div>
                        </div>
                    </form>

                    <!-- SUMMARY SECTION (visible after search) -->
                    <div id="summarySection" style="display:none;">
                        <h4>Summary</h4>
                        <div class="table-responsive">
                            <table class="table" id="summary_table">
                                <thead>
                                    <tr>
                                        <th>Subject</th>
                                        <th>Grade</th>
                                        <th style="text-align:right;">Attendance (%)</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr><td colspan="4" class="center">Use Search to view results.</td></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- DETAILED SECTION (hidden by default) -->
                    <div id="detailedSection" style="display:none;">
                        <div style="display:flex; justify-content:space-between; align-items:center;">
                            <h4>Detailed View</h4>
                            <div>
                                <button class="btn-secondary" id="backToSummaryBtn">Back to Summary</button>
                            </div>
                        </div>
                        <div class="table-responsive">
                            <table class="table" id="detailed_table">
                                <thead>
                                    <tr>
                                        <th>Subject</th>
                                        <th style="text-align:right;">Actual Mark</th>
                                        <th style="text-align:right;">Possible Mark</th>
                                        <th style="text-align:right;">Percentage</th>
                                        <th>Grade</th>
                                        <th style="text-align:right;">Actual Attendance (days)</th>
                                        <th style="text-align:right;">Expected Attendance (days)</th>
                                        <th style="text-align:right;">Attendance (%)</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr><td colspan="8" class="center">Select "View Details" from the summary to see full data.</td></tr>
                                </tbody>
                                <tfoot>
                                    <tr style="font-weight:bold;">
                                        <td class="right">Grand Total:</td>
                                        <td id="ft-total-actual-mark" class="right"></td>
                                        <td id="ft-total-possible-mark" class="right"></td>
                                        <td id="ft-overall-percentage" class="right"></td>
                                        <td></td>
                                        <td id="ft-total-actual-att" class="right"></td>
                                        <td id="ft-total-expected-att" class="right"></td>
                                        <td id="ft-total-att-pct" class="right"></td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                    <!-- End of sections -->

                </div>
            </div>
        </section>
    </div>

    <script>
        // ---------- Original data (learners, marks, comments kept as requested) ----------
        const educationLevels = {
            preschool: {
                levels: ["ECD A", "ECD B", "ECD C"],
                learners: {
                    "ECD A": [
                        {value: 'ps_ecda1', text: 'Emma Johnson'},
                        {value: 'ps_ecda2', text: 'Noah Williams'}
                    ],
                    "ECD B": [
                        {value: 'ps_ecdb1', text: 'Olivia Brown'},
                        {value: 'ps_ecdb2', text: 'Liam Jones'}
                    ],
                    "ECD C": [
                        {value: 'ps_ecdc1', text: 'Ava Garcia'},
                        {value: 'ps_ecdc2', text: 'Lucas Martinez'}
                    ]
                }
            },
            primary: {
                levels: ["Level 1", "Level 2", "Level 3"],
                learners: {
                    "Level 1": [
                        {value: 'p_l1_1', text: 'John Doe'},
                        {value: 'p_l1_2', text: 'Jane Smith'}
                    ],
                    "Level 2": [
                        {value: 'p_l2_1', text: 'Mary Johnson'},
                        {value: 'p_l2_2', text: 'Peter Brown'}
                    ],
                    "Level 3": [
                        {value: 'p_l3_1', text: 'Alice White'},
                        {value: 'p_l3_2', text: 'David Black'}
                    ]
                }
            },
            secondary: {
                levels: ["Form 1", "Form 2", "Form 3"],
                learners: {
                    "Form 1": [
                        {value: 's_f1_1', text: 'Sarah Wilson'},
                        {value: 's_f1_2', text: 'Michael Taylor'}
                    ],
                    "Form 2": [
                        {value: 's_f2_1', text: 'Emily Anderson'},
                        {value: 's_f2_2', text: 'James Thomas'}
                    ],
                    "Form 3": [
                        {value: 's_f3_1', text: 'Daniel Jackson'},
                        {value: 's_f3_2', text: 'Sophia Harris'}
                    ]
                }
            }
        };

        const marksByLearner = {
            'ps_ecda1': [
                {subject: 'Coloring', actual: 85, possible: 100, subTeacherComments: 'Excellent coloring skills. Stays within lines well.'},
                {subject: 'Story Time', actual: 90, possible: 100, subTeacherComments: 'Very attentive during story sessions. Good comprehension.'},
                {subject: 'Play Activities', actual: 88, possible: 100, subTeacherComments: 'Participates actively in group play. Good social skills.'}
            ],
            'ps_ecda2': [
                {subject: 'Coloring', actual: 78, possible: 100, subTeacherComments: 'Improving coloring technique. Needs more practice with staying in lines.'},
                {subject: 'Story Time', actual: 82, possible: 100, subTeacherComments: 'Sometimes distracted during stories. Working on attention span.'},
                {subject: 'Play Activities', actual: 80, possible: 100, subTeacherComments: 'Enjoys individual play more than group activities.'}
            ],
            'ps_ecdb1': [
                {subject: 'Numbers', actual: 88, possible: 100, subTeacherComments: 'Quick learner with numbers. Can count to 20 confidently.'},
                {subject: 'Letters', actual: 85, possible: 100, subTeacherComments: 'Recognizes most letters. Good phonetic awareness.'},
                {subject: 'Arts & Crafts', actual: 92, possible: 100, subTeacherComments: 'Very creative. Excellent fine motor skills development.'}
            ],
            'ps_ecdb2': [
                {subject: 'Numbers', actual: 75, possible: 100, subTeacherComments: 'Struggles with number recognition beyond 10. Needs extra practice.'},
                {subject: 'Letters', actual: 80, possible: 100, subTeacherComments: 'Recognizes basic letters. Working on letter sounds.'},
                {subject: 'Arts & Crafts', actual: 78, possible: 100, subTeacherComments: 'Enjoys art activities but needs help with scissor skills.'}
            ],
            'ps_ecdc1': [
                {subject: 'Basic Math', actual: 90, possible: 100, subTeacherComments: 'Excellent addition and subtraction skills for age level.'},
                {subject: 'Reading', actual: 88, possible: 100, subTeacherComments: 'Reading simple sentences fluently. Good comprehension.'},
                {subject: 'Writing', actual: 85, possible: 100, subTeacherComments: 'Good pencil grip. Writing is becoming more legible.'}
            ],
            'ps_ecdc2': [
                {subject: 'Basic Math', actual: 82, possible: 100, subTeacherComments: 'Understands basic math concepts. Needs practice with subtraction.'},
                {subject: 'Reading', actual: 85, possible: 100, subTeacherComments: 'Reading simple words. Working on building vocabulary.'},
                {subject: 'Writing', actual: 80, possible: 100, subTeacherComments: 'Improving letter formation. Needs to work on spacing.'}
            ],
            'p_l1_1': [
                {subject: 'Mathematics', actual: 78, possible: 100, subTeacherComments: 'Good problem-solving skills. Needs to work on multiplication tables.'},
                {subject: 'English', actual: 65, possible: 100, subTeacherComments: 'Struggles with grammar rules. Needs extra reading practice.'},
                {subject: 'Science', actual: 82, possible: 100, subTeacherComments: 'Very curious and asks good questions. Excellent in practical experiments.'}
            ],
            'p_l1_2': [
                {subject: 'Mathematics', actual: 88, possible: 100, subTeacherComments: 'Excellent mathematical reasoning. Ready for advanced concepts.'},
                {subject: 'English', actual: 72, possible: 100, subTeacherComments: 'Good writing skills. Vocabulary is expanding well.'},
                {subject: 'Science', actual: 90, possible: 100, subTeacherComments: 'Shows great interest in science topics. Asks insightful questions.'}
            ],
            'p_l2_1': [
                {subject: 'Mathematics', actual: 55, possible: 100, subTeacherComments: 'Struggles with fractions. Recommend extra tutoring sessions.'},
                {subject: 'English', actual: 68, possible: 100, subTeacherComments: 'Reading comprehension needs improvement. Practice with comprehension exercises.'},
                {subject: 'Science', actual: 75, possible: 100, subTeacherComments: 'Good participation in class. Understands basic concepts well.'}
            ],
            'p_l2_2': [
                {subject: 'Mathematics', actual: 92, possible: 100, subTeacherComments: 'Exceptional mathematical ability. Consider for math competitions.'},
                {subject: 'English', actual: 85, possible: 100, subTeacherComments: 'Excellent creative writing skills. Very imaginative stories.'},
                {subject: 'Science', actual: 78, possible: 100, subTeacherComments: 'Good understanding of scientific method. Careful in experiments.'}
            ],
            'p_l3_1': [
                {subject: 'Mathematics', actual: 60, possible: 100, subTeacherComments: 'Needs to improve in geometry. Basic concepts are understood.'},
                {subject: 'English', actual: 70, possible: 100, subTeacherComments: 'Writing is improving. Working on sentence structure and punctuation.'},
                {subject: 'Science', actual: 65, possible: 100, subTeacherComments: 'Struggles with remembering scientific terms. Use flashcards for practice.'}
            ],
            'p_l3_2': [
                {subject: 'Mathematics', actual: 80, possible: 100, subTeacherComments: 'Consistent performance. Good application of mathematical concepts.'},
                {subject: 'English', actual: 82, possible: 100, subTeacherComments: 'Excellent reading skills. Comprehension at grade level.'},
                {subject: 'Science', actual: 88, possible: 100, subTeacherComments: 'Very good at scientific reasoning. Enjoys hands-on experiments.'}
            ],
            's_f1_1': [
                {subject: 'Mathematics', actual: 85, possible: 100, subTeacherComments: 'Strong algebraic skills. Ready for more complex equations.'},
                {subject: 'English', actual: 78, possible: 100, subTeacherComments: 'Good analytical skills in literature. Essay writing is developing well.'},
                {subject: 'Biology', actual: 82, possible: 100, subTeacherComments: 'Excellent in practical biology. Good understanding of cellular structure.'}
            ],
            's_f1_2': [
                {subject: 'Mathematics', actual: 72, possible: 100, subTeacherComments: 'Understanding basic concepts. Needs more practice with word problems.'},
                {subject: 'English', actual: 80, possible: 100, subTeacherComments: 'Good vocabulary. Working on improving writing fluency.'},
                {subject: 'Biology', actual: 75, possible: 100, subTeacherComments: 'Struggles with memorizing biological terms. Use mnemonics for help.'}
            ],
            's_f2_1': [
                {subject: 'Mathematics', actual: 88, possible: 100, subTeacherComments: 'Excellent in trigonometry. Shows strong mathematical intuition.'},
                {subject: 'English', actual: 85, possible: 100, subTeacherComments: 'Advanced reading comprehension. Critical analysis skills are strong.'},
                {subject: 'Chemistry', actual: 90, possible: 100, subTeacherComments: 'Very good at chemical equations. Safety conscious in lab.'}
            ],
            's_f2_2': [
                {subject: 'Mathematics', actual: 79, possible: 100, subTeacherComments: 'Good understanding of concepts. Needs to check work for careless errors.'},
                {subject: 'English', actual: 82, possible: 100, subTeacherComments: 'Writing style is developing. Working on thesis statements.'},
                {subject: 'Chemistry', actual: 85, possible: 100, subTeacherComments: 'Understands chemical reactions well. Good lab technique.'}
            ],
            's_f3_1': [
                {subject: 'Mathematics', actual: 92, possible: 100, subTeacherComments: 'Exceptional in calculus. Ready for advanced mathematics.'},
                {subject: 'English', actual: 88, possible: 100, subTeacherComments: 'Sophisticated literary analysis. Writing is college-level.'},
                {subject: 'Physics', actual: 90, possible: 100, subTeacherComments: 'Excellent problem-solving in physics. Strong conceptual understanding.'}
            ],
            's_f3_2': [
                {subject: 'Mathematics', actual: 85, possible: 100, subTeacherComments: 'Good performance in advanced math. Consistent effort shown.'},
                {subject: 'English', actual: 80, possible: 100, subTeacherComments: 'Solid writing skills. Working on developing unique voice.'},
                {subject: 'Physics', actual: 82, possible: 100, subTeacherComments: 'Understands physics concepts. Needs practice with complex calculations.'}
            ]
        };

        // Comments data is retained but will not be used/displayed (user asked to remove comments section)
        const commentsData = {
            'ps_ecda1': {
                classTeacher: "Emma is showing excellent progress in social skills and participation. She enjoys group activities and follows instructions well.",
                headTeacher: "Good overall development. Continue encouraging creative expression."
            },
            'ps_ecda2': {
                classTeacher: "Noah is improving in fine motor skills. Needs more practice with coloring within lines.",
                headTeacher: "Steady progress observed. Focus on hand-eye coordination activities."
            },
            'ps_ecdb1': {
                classTeacher: "Olivia shows strong academic readiness. Excellent number and letter recognition.",
                headTeacher: "Advanced for ECD B level. Consider enrichment activities."
            },
            'ps_ecdb2': {
                classTeacher: "Liam is making good progress. Working on building confidence in group settings.",
                headTeacher: "Consistent improvement noted. Continue with current support strategies."
            },
            'p_l1_1': {
                classTeacher: "John is performing well in Science but needs to improve in English comprehension.",
                headTeacher: "Satisfactory performance. Recommend extra reading practice."
            },
            'p_l1_2': {
                classTeacher: "Jane is consistent across all subjects. Shows good analytical skills.",
                headTeacher: "Excellent performance. Consider advanced learning materials."
            },
            's_f1_1': {
                classTeacher: "Sarah shows strong aptitude for Mathematics. Should participate in math competitions.",
                headTeacher: "Outstanding performance. Monitor for scholarship opportunities."
            },
            's_f3_2': {
                classTeacher: "Sophia needs to improve in Physics. Recommend additional tutoring sessions.",
                headTeacher: "Average performance. Focus on weak areas for final exams."
            }
        };

        // ---------- Attendance persistence map ----------
        // Structure: { learnerId: { subjectName: actualAttendance, ... }, ... }
        const attendanceStore = {};

        // ---------- Helper functions ----------
        function populateLearnerLevels() {
            const educationLevel = document.getElementById('report_type').value;
            const learnerLevelSelect = document.getElementById('learner_level');

            learnerLevelSelect.innerHTML = '<option value="">Select Learner Level</option>';
            document.getElementById('learner_name').innerHTML = '<option value="">Select Learner</option>';

            if (educationLevel && educationLevels[educationLevel]) {
                educationLevels[educationLevel].levels.forEach(level => {
                    const option = document.createElement('option');
                    option.value = level;
                    option.text = level;
                    learnerLevelSelect.appendChild(option);
                });
            }
        }

        function populateLearnerName() {
            const educationLevel = document.getElementById('report_type').value;
            const learnerLevel = document.getElementById('learner_level').value;
            const learnerNameSelect = document.getElementById('learner_name');

            learnerNameSelect.innerHTML = '<option value="">Select Learner</option>';

            if (educationLevel && learnerLevel && educationLevels[educationLevel] && educationLevels[educationLevel].learners[learnerLevel]) {
                educationLevels[educationLevel].learners[learnerLevel].forEach(l => {
                    const option = document.createElement('option');
                    option.value = l.value;
                    option.text = l.text;
                    learnerNameSelect.appendChild(option);
                });
            }
        }

        function computeGrade(percentage) {
            if (percentage >= 80) return 'A';
            if (percentage >= 70) return 'B';
            if (percentage >= 60) return 'C';
            if (percentage >= 50) return 'D';
            return 'E';
        }

        // Make or get persisted actual attendance for a specific learner + subject
        function getOrCreateAttendance(learnerId, subject, expected) {
            if (!attendanceStore[learnerId]) attendanceStore[learnerId] = {};
            // if stored, return
            if (attendanceStore[learnerId][subject] !== undefined) return attendanceStore[learnerId][subject];
            // else create random from 0..expected inclusive
            const val = Math.floor(Math.random() * (expected + 1));
            attendanceStore[learnerId][subject] = val;
            return val;
        }

        // Build summary rows for a learner
        function buildSummaryRows(learnerId) {
            const rows = marksByLearner[learnerId];
            if (!rows || !Array.isArray(rows)) return [];

            const subjectsCount = rows.length;
            const EXPECTED_TERM_DAYS = 88;
            const expectedPerSubject = Math.floor(EXPECTED_TERM_DAYS / subjectsCount);

            const summary = rows.map(r => {
                const percentage = (r.possible > 0) ? (r.actual / r.possible) * 100 : 0;
                const grade = computeGrade(percentage);
                const actualAttendance = getOrCreateAttendance(learnerId, r.subject, expectedPerSubject);
                const attendancePct = (expectedPerSubject > 0) ? (actualAttendance / expectedPerSubject) * 100 : 0;
                return {
                    subject: r.subject,
                    grade,
                    attendancePct,
                    actualAttendance,
                    expectedAttendance: expectedPerSubject,
                    marksRow: r
                };
            });

            return summary;
        }

        // Show the summary table
        function showSummary(learnerId) {
            const summarySection = document.getElementById('summarySection');
            const detailedSection = document.getElementById('detailedSection');
            const tbody = document.querySelector('#summary_table tbody');

            tbody.innerHTML = '';

            const summaryRows = buildSummaryRows(learnerId);
            if (summaryRows.length === 0) {
                tbody.innerHTML = '<tr><td colspan="4" class="center">No subjects found for selected learner.</td></tr>';
            } else {
                summaryRows.forEach((s, idx) => {
                    const tr = document.createElement('tr');

                    const tdSubject = document.createElement('td');
                    tdSubject.textContent = s.subject;

                    const tdGrade = document.createElement('td');
                    tdGrade.textContent = s.grade;

                    const tdAttendancePct = document.createElement('td');
                    tdAttendancePct.className = 'right';
                    tdAttendancePct.textContent = s.attendancePct.toFixed(2);

                    const tdAction = document.createElement('td');
                    const viewBtn = document.createElement('button');
                    viewBtn.className = 'btn-link';
                    viewBtn.type = 'button';
                    viewBtn.textContent = 'View Details';
                    viewBtn.dataset.subject = s.subject;
                    viewBtn.dataset.learner = learnerId;
                    viewBtn.addEventListener('click', function() {
                        // when clicked show detailed view for this subject (but requirement said show the table above)
                        // We'll show the full detailed table for the learner (all subjects) and highlight or navigate to the clicked subject.
                        showDetailed(learnerId, s.subject);
                    });
                    tdAction.appendChild(viewBtn);

                    tr.appendChild(tdSubject);
                    tr.appendChild(tdGrade);
                    tr.appendChild(tdAttendancePct);
                    tr.appendChild(tdAction);

                    tbody.appendChild(tr);
                });
            }

            // show summary, hide detailed
            summarySection.style.display = 'block';
            detailedSection.style.display = 'none';
            // clear any footers in detailed
            clearDetailedFooter();
        }

        function clearDetailedFooter() {
            document.getElementById('ft-total-actual-mark').innerText = '';
            document.getElementById('ft-total-possible-mark').innerText = '';
            document.getElementById('ft-overall-percentage').innerText = '';
            document.getElementById('ft-total-actual-att').innerText = '';
            document.getElementById('ft-total-expected-att').innerText = '';
            document.getElementById('ft-total-att-pct').innerText = '';
        }

        // Show detailed table for a learner. If subjectToFocus provided, the table is still full but we scroll to that subject row.
        function showDetailed(learnerId, subjectToFocus) {
            const rows = marksByLearner[learnerId];
            const tbody = document.querySelector('#detailed_table tbody');
            const detailedSection = document.getElementById('detailedSection');
            const summarySection = document.getElementById('summarySection');

            tbody.innerHTML = '';

            if (!rows || rows.length === 0) {
                tbody.innerHTML = '<tr><td colspan="8" class="center">No details available for selected learner.</td></tr>';
                summarySection.style.display = 'none';
                detailedSection.style.display = 'block';
                return;
            }

            const subjectsCount = rows.length;
            const EXPECTED_TERM_DAYS = 88;
            const expectedPerSubject = Math.floor(EXPECTED_TERM_DAYS / subjectsCount);

            let totalActualMark = 0;
            let totalPossibleMark = 0;
            let totalActualAttendance = 0;
            let totalExpectedAttendance = 0;

            rows.forEach(r => {
                const percentage = (r.possible > 0) ? (r.actual / r.possible) * 100 : 0;
                const grade = computeGrade(percentage);
                const actualAttendance = getOrCreateAttendance(learnerId, r.subject, expectedPerSubject);
                const expectedAttendance = expectedPerSubject;
                const attendancePct = (expectedAttendance > 0) ? (actualAttendance / expectedAttendance) * 100 : 0;

                totalActualMark += r.actual;
                totalPossibleMark += r.possible;
                totalActualAttendance += actualAttendance;
                totalExpectedAttendance += expectedAttendance;

                const tr = document.createElement('tr');
                tr.dataset.subject = r.subject;

                tr.innerHTML = `
                    <td>${escapeHtml(r.subject)}</td>
                    <td class="right">${r.actual}</td>
                    <td class="right">${r.possible}</td>
                    <td class="right">${percentage.toFixed(2)}</td>
                    <td>${grade}</td>
                    <td class="right">${actualAttendance}</td>
                    <td class="right">${expectedAttendance}</td>
                    <td class="right">${attendancePct.toFixed(2)}</td>
                `;
                tbody.appendChild(tr);
            });

            const overallMarkPct = (totalPossibleMark > 0) ? (totalActualMark / totalPossibleMark) * 100 : 0;
            const overallAttendancePct = (totalExpectedAttendance > 0) ? (totalActualAttendance / totalExpectedAttendance) * 100 : 0;

            document.getElementById('ft-total-actual-mark').innerText = totalActualMark;
            document.getElementById('ft-total-possible-mark').innerText = totalPossibleMark;
            document.getElementById('ft-overall-percentage').innerText = overallMarkPct.toFixed(2);
            document.getElementById('ft-total-actual-att').innerText = totalActualAttendance;
            document.getElementById('ft-total-expected-att').innerText = totalExpectedAttendance;
            document.getElementById('ft-total-att-pct').innerText = overallAttendancePct.toFixed(2);

            // show detailed, hide summary
            summarySection.style.display = 'none';
            detailedSection.style.display = 'block';

            // if a subject to focus is provided, scroll to it and maybe highlight briefly
            if (subjectToFocus) {
                const row = Array.from(tbody.querySelectorAll('tr')).find(tr => tr.dataset.subject === subjectToFocus);
                if (row) {
                    row.style.backgroundColor = '#fff7d6';
                    row.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    // remove highlight after brief moment
                    setTimeout(() => { row.style.backgroundColor = ''; }, 1400);
                }
            }
        }

        // small HTML escape helper
        function escapeHtml(text) {
            if (text === null || text === undefined) return '';
            return String(text)
                .replace(/&/g, '&amp;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#39;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;');
        }

        // ---------- Event listeners ----------
        document.getElementById('report_type').addEventListener('change', function() {
            populateLearnerLevels();
            document.getElementById('summarySection').style.display = 'none';
            document.getElementById('detailedSection').style.display = 'none';
        });

        document.getElementById('learner_level').addEventListener('change', function() {
            populateLearnerName();
            document.getElementById('summarySection').style.display = 'none';
            document.getElementById('detailedSection').style.display = 'none';
        });

        document.getElementById('learner_name').addEventListener('change', function() {
            document.getElementById('summarySection').style.display = 'none';
            document.getElementById('detailedSection').style.display = 'none';
        });

        document.getElementById('exam_type').addEventListener('change', function() {
            document.getElementById('summarySection').style.display = 'none';
            document.getElementById('detailedSection').style.display = 'none';
        });

        // Search button: show summary table for selected learner
        document.getElementById('searchBtn').addEventListener('click', function() {
            const learner = document.getElementById('learner_name').value;
            const term = document.getElementById('exam_type').value;

            if (!learner || !term) {
                alert('Please select both a learner and a term before searching.');
                return;
            }

            showSummary(learner);
        });

        // Back to summary from detailed
        document.getElementById('backToSummaryBtn').addEventListener('click', function() {
            // find currently selected learner from drop-down and show summary for them
            const learner = document.getElementById('learner_name').value;
            if (learner) showSummary(learner);
            else {
                // fallback
                document.getElementById('detailedSection').style.display = 'none';
                document.getElementById('summarySection').style.display = 'none';
            }
        });

        // Initialize selects
        populateLearnerLevels();
    </script>
</body>
</html>
