<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exam Performance Report</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css">
    <style type="text/css">
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f7fa;
            color: #333;
            padding: 20px;
        }
        .content-wrapper {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 20px;
            margin-bottom: 30px;
        }
        .content-header h1 {
            color: #2c3e50;
            border-bottom: 2px solid #faa21c;
            padding-bottom: 10px;
            margin-top: 0;
        }
        .box {
            border: none;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            border-radius: 8px;
        }
        .box-header {
            background-color: #f8f9fa;
            border-bottom: 1px solid #eee;
            padding: 15px 20px;
            border-radius: 8px 8px 0 0;
        }
        .box-header h3 {
            margin: 0;
            color: #2c3e50;
        }
        .box-body {
            padding: 20px;
        }
        
        /* Improved horizontal filter layout */
        .horizontal-filters {
            display: flex;
            flex-direction: column;
            gap: 15px;
            margin-bottom: 20px;
        }
        
        .filter-group {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            width: 100%;
            padding: 15px;
            background-color: #f9f9f9;
            border-radius: 5px;
            margin-bottom: 10px;
            border: 1px solid #eaeaea;
        }
        
        .filter-group-title {
            width: 100%;
            font-weight: bold;
            margin-bottom: 10px;
            color: #2c3e50;
            border-bottom: 1px solid #ddd;
            padding-bottom: 5px;
            font-size: 16px;
        }
        
        .filter-row {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            width: 100%;
        }
        
        .filter-row .form-group {
            flex: 1;
            min-width: 200px;
        }
        
        .form-group label {
            font-weight: 600;
            margin-bottom: 5px;
            color: #495057;
        }
        
        .form-control {
            border-radius: 4px;
            border: 1px solid #ced4da;
            padding: 8px 12px;
            transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
        }
        
        .form-control:focus {
            border-color: #faa21c;
            box-shadow: 0 0 0 0.2rem rgba(250, 162, 28, 0.25);
        }
        
        .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;
            transition: background-color 0.2s;
        }
        
        .btn-search:hover {
            background-color: #e8910c;
        }
        
        .comments-section {
            margin-top: 20px;
            padding: 15px;
            background-color: #f9f9f9;
            border-radius: 4px;
            border: 1px solid #ddd;
        }
        
        .comments-section h5 {
            margin-top: 0;
            color: #333;
            border-bottom: 1px solid #ddd;
            padding-bottom: 5px;
        }
        
        .comments-section p {
            margin: 10px 0;
            padding: 8px;
            background-color: white;
            border-radius: 3px;
            border-left: 3px solid #faa21c;
        }
        
        .term-section {
            margin-bottom: 30px;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 15px;
            background-color: #f9f9f9;
        }
        
        .term-header {
            background-color: #faa21c;
            color: white;
            padding: 10px 15px;
            margin: -15px -15px 15px -15px;
            border-radius: 5px 5px 0 0;
            font-weight: bold;
        }
        
        .show-all-terms-container {
            display: flex;
            align-items: center;
            margin-top: 10px;
            gap: 8px;
        }
        
        .show-all-terms-container input[type="checkbox"] {
            width: 18px;
            height: 18px;
        }
        
        .filter-by-container {
            margin-top: 10px;
        }
        
        .filter-value-container {
            display: none;
            margin-top: 10px;
        }
        
        .filter-value-container select {
            min-width: 200px;
        }
        
        .multi-select-container {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 5px;
        }
        
        .filter-checkbox {
            display: flex;
            align-items: center;
            gap: 5px;
            background-color: #f5f5f5;
            padding: 5px 10px;
            border-radius: 4px;
            border: 1px solid #ddd;
        }
        
        .filter-checkbox input[type="checkbox"] {
            width: 16px;
            height: 16px;
        }
        
        .filter-checkbox.disabled {
            background-color: #e9ecef;
            opacity: 0.6;
            cursor: not-allowed;
        }
        
        .filter-checkbox.disabled input[type="checkbox"] {
            cursor: not-allowed;
        }
        
        .selected-filters {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-top: 10px;
        }
        
        .selected-filter-tag {
            background-color: #faa21c;
            color: white;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .remove-filter {
            cursor: pointer;
            font-weight: bold;
        }
        
        .all-learners-table {
            margin-top: 20px;
        }
        
        .all-learners-table th {
            background-color: #f5f5f5;
            font-weight: bold;
        }
        
        .learner-row {
            cursor: pointer;
            transition: background-color 0.2s;
        }
        
        .learner-row:hover {
            background-color: #f9f9f9;
        }
        
        .table {
            border-radius: 4px;
            overflow: hidden;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        
        .table th {
            background-color: #f8f9fa;
            border-bottom: 2px solid #dee2e6;
        }
        
        .table-striped tbody tr:nth-of-type(odd) {
            background-color: rgba(0,0,0,.02);
        }
        
        .table-bordered {
            border: 1px solid #dee2e6;
        }
        
        .table-bordered th,
        .table-bordered td {
            border: 1px solid #dee2e6;
        }
        
        .table-responsive {
            border-radius: 4px;
        }
        
        .alert-info {
            background-color: #d9edf7;
            border-color: #bce8f1;
            color: #31708f;
            padding: 10px 15px;
            border-radius: 4px;
            margin-bottom: 15px;
        }
        
        @media (max-width: 768px) {
            .filter-row {
                flex-direction: column;
            }
            
            .multi-select-container {
                flex-direction: column;
            }
            
            .filter-group {
                padding: 10px;
            }
        }
    </style>
</head>
<body>
    <div class="content-wrapper" style="min-height: 946px;">
        <section class="content-header">
            <h1>
                <i class="fa fa-line-chart"></i> 
                Exam Performance Report
                <small>Track and analyze student performance</small>
            </h1>
        </section>

        <section class="content">
            <div class="row">
                <div class="col-md-12">
                    <div class="box box-primary">
                        <div class="box-header with-border">
                            <h3 class="box-title">
                                <i class="fa fa-balance-scale"></i> 
                                Student Performance Dashboard
                            </h3>
                        </div>
                        <div class="box-body">
                            <div class="alert alert-info">
                                <i class="fa fa-info-circle"></i> Select filters below to view student performance data. Filters are grouped for easier navigation.
                            </div>
                            
                            <form id="reportForm" class="form-horizontal">
                                <!-- Improved horizontal filter layout -->
                                <div class="horizontal-filters">
                                    <!-- Group 1: Academic Level Selection -->
                                    <div class="filter-group">
                                        <div class="filter-group-title">Academic Level Selection</div>
                                        <!-- Education Level -->
                                        <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>

                                        <!-- Learner Level -->
                                        <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>

                                        <!-- Learner Class -->
                                        <div class="form-group">
                                            <label>Learner Class</label>
                                            <select name="learner_class" id="learner_class" class="form-control">
                                                <option value="">Select Class</option>
                                            </select>
                                        </div>
                                    </div>
                                    
                                    <!-- Group 2: Term Selection -->
                                    <div class="filter-group">
                                        <div class="filter-group-title">Term Selection</div>
                                        <!-- Term -->
                                        <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>
                                        
                                        <!-- Show All Terms Checkbox -->
                                        <div class="form-group show-all-terms-container">
                                            <label>&nbsp;</label>
                                            <div class="show-all-terms-checkbox">
                                                <input type="checkbox" id="show_all_terms">
                                                <label for="show_all_terms">Show all Terms</label>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Group 3: Filter Options -->
                                    <div class="filter-group">
                                        <div class="filter-group-title">Filter Options</div>
                                        <div class="filter-by-container">
                                            <label>Filter By</label>
                                            <div class="multi-select-container">
                                                <div class="filter-checkbox" id="learner_name_checkbox">
                                                    <input type="checkbox" id="filter_learner_name" value="learner_name">
                                                    <label for="filter_learner_name">Learner Name</label>
                                                </div>
                                                <div class="filter-checkbox" id="age_checkbox">
                                                    <input type="checkbox" id="filter_age" value="age">
                                                    <label for="filter_age">Age</label>
                                                </div>
                                                <div class="filter-checkbox" id="gender_checkbox">
                                                    <input type="checkbox" id="filter_gender" value="gender">
                                                    <label for="filter_gender">Gender</label>
                                                </div>
                                                <div class="filter-checkbox" id="grade_checkbox">
                                                    <input type="checkbox" id="filter_grade" value="grade">
                                                    <label for="filter_grade">Grade</label>
                                                </div>
                                                <div class="filter-checkbox" id="subject_checkbox">
                                                    <input type="checkbox" id="filter_subject" value="subject">
                                                    <label for="filter_subject">Subject</label>
                                                </div>
                                            </div>
                                            
                                            <!-- Selected Filters Display -->
                                            <div class="selected-filters" id="selected_filters"></div>
                                        </div>
                                        
                                        <!-- Filter Value Rows (dynamically shown based on selected filters) -->
                                        <div id="filter_value_rows"></div>
                                    </div>
                                    
                                    <!-- Search Button -->
                                    <div class="search-button-container">
                                        <button type="button" class="btn-search" id="searchBtn">
                                            <i class="fa fa-search"></i> Generate Report
                                        </button>
                                    </div>
                                </div>
                            </form>

                            <!-- Dynamic Exam Table (Initially hidden) -->
                            <div id="resultsSection" style="display: none;">
                                <div class="row" style="margin-top:30px;">
                                    <div class="col-md-12">
                                        <h4><i class="fa fa-table"></i> Exam Performance Summary</h4>
                                        
                                        <!-- Single Term Table -->
                                        <div id="singleTermTable">
                                            <div class="table-responsive">
                                                <table class="table table-bordered table-striped" id="exam_table">
                                                    <thead style="background-color:#f5f5f5;">
                                                        <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>Sub Teacher Comments</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <tr><td colspan="6" style="text-align:center;">Please use the search button to view results.</td></tr>
                                                    </tbody>
                                                    <tfoot>
                                                        <tr style="font-weight:bold;">
                                                            <td style="text-align:right;">Grand Total:</td>
                                                            <td style="text-align:right;"></td>
                                                            <td style="text-align:right;"></td>
                                                            <td colspan="3"></td>
                                                        </tr>
                                                    </tfoot>
                                                </table>
                                            </div>
                                        </div>
                                        
                                        <!-- All Terms Tables -->
                                        <div id="allTermsTables" style="display: none;">
                                            <!-- First Term Table -->
                                            <div class="term-section">
                                                <div class="term-header">First Term Results</div>
                                                <div class="table-responsive">
                                                    <table class="table table-bordered table-striped term-table" id="term1_table">
                                                        <thead style="background-color:#f5f5f5;">
                                                            <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>Sub Teacher Comments</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <tr><td colspan="6" style="text-align:center;">No data available.</td></tr>
                                                        </tbody>
                                                        <tfoot>
                                                            <tr style="font-weight:bold;">
                                                                <td style="text-align:right;">Grand Total:</td>
                                                                <td style="text-align:right;"></td>
                                                                <td style="text-align:right;"></td>
                                                                <td colspan="3"></td>
                                                            </tr>
                                                        </tfoot>
                                                    </table>
                                                </div>
                                            </div>
                                            
                                            <!-- Second Term Table -->
                                            <div class="term-section">
                                                <div class="term-header">Second Term Results</div>
                                                <div class="table-responsive">
                                                    <table class="table table-bordered table-striped term-table" id="term2_table">
                                                        <thead style="background-color:#f5f5f5;">
                                                            <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>Sub Teacher Comments</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <tr><td colspan="6" style="text-align:center;">No data available.</td></tr>
                                                        </tbody>
                                                        <tfoot>
                                                            <tr style="font-weight:bold;">
                                                                <td style="text-align:right;">Grand Total:</td>
                                                                <td style="text-align:right;"></td>
                                                                <td style="text-align:right;"></td>
                                                                <td colspan="3"></td>
                                                            </tr>
                                                        </tfoot>
                                                    </table>
                                                </div>
                                            </div>
                                            
                                            <!-- Third Term Table -->
                                            <div class="term-section">
                                                <div class="term-header">Third Term Results</div>
                                                <div class="table-responsive">
                                                    <table class="table table-bordered table-striped term-table" id="term3_table">
                                                        <thead style="background-color:#f5f5f5;">
                                                            <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>Sub Teacher Comments</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <tr><td colspan="6" style="text-align:center;">No data available.</td></tr>
                                                        </tbody>
                                                        <tfoot>
                                                            <tr style="font-weight:bold;">
                                                                <td style="text-align:right;">Grand Total:</td>
                                                                <td style="text-align:right;"></td>
                                                                <td style="text-align:right;"></td>
                                                                <td colspan="3"></td>
                                                            </tr>
                                                        </tfoot>
                                                    </table>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- All Learners Table -->
                                        <div id="allLearnersTable" style="display: none;">
                                            <div class="term-section">
                                                <div class="term-header">All Learners Summary</div>
                                                <div class="table-responsive all-learners-table">
                                                    <table class="table table-bordered table-striped" id="all_learners_table">
                                                        <thead style="background-color:#f5f5f5;">
                                                            <tr>
                                                                <th>Learner Name</th>
                                                                <th>Age</th>
                                                                <th>Gender</th>
                                                                <th>Class</th>
                                                                <th>Average Percentage</th>
                                                                <th>Overall Grade</th>
                                                                <th>Action</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody id="all_learners_tbody">
                                                            <tr><td colspan="7" style="text-align:center;">No data available.</td></tr>
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Comments Section -->
                                <div class="comments-section">
                                    <h5>Comments from Class Teacher</h5>
                                    <p id="classTeacherComment">No comment available.</p>
                                    
                                    <h5>Comments from Head/Deputy</h5>
                                    <p id="headTeacherComment">No comment available.</p>
                                </div>
                            </div>
                            <!-- End Table and Comments -->

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

    <script>
        // Define learners and levels based on education level
        const educationLevels = {
            preschool: {
                levels: ["ECD A", "ECD B", "ECD C"],
                classes: {
                    "ECD A": ["Red Class", "Blue Class"],
                    "ECD B": ["Green Class", "Yellow Class"],
                    "ECD C": ["Orange Class", "Purple Class"]
                },
                learners: {
                    "ECD A": {
                        "Red Class": [
                            {value: 'ps_ecda1', text: 'Emma Johnson', age: '4', gender: 'Female', grade: 'A'},
                            {value: 'ps_ecda2', text: 'Noah Williams', age: '5', gender: 'Male', grade: 'B'},
                            {value: 'ps_ecda3', text: 'Olivia Brown', age: '4', gender: 'Female', grade: 'A'},
                            {value: 'ps_ecda4', text: 'Liam Jones', age: '5', gender: 'Male', grade: 'C'},
                            {value: 'ps_ecda5', text: 'Ava Garcia', age: '4', gender: 'Female', grade: 'B'},
                            {value: 'ps_ecda6', text: 'Lucas Martinez', age: '5', gender: 'Male', grade: 'A'}
                        ],
                        "Blue Class": [
                            {value: 'ps_ecda7', text: 'Mia Anderson', age: '4', gender: 'Female', grade: 'B'},
                            {value: 'ps_ecda8', text: 'Ethan Taylor', age: '5', gender: 'Male', grade: 'A'},
                            {value: 'ps_ecda9', text: 'Sophia Thomas', age: '4', gender: 'Female', grade: 'C'},
                            {value: 'ps_ecda10', text: 'Mason Hernandez', age: '5', gender: 'Male', grade: 'B'},
                            {value: 'ps_ecda11', text: 'Isabella Moore', age: '4', gender: 'Female', grade: 'A'},
                            {value: 'ps_ecda12', text: 'Logan Martin', age: '5', gender: 'Male', grade: 'B'}
                        ]
                    },
                    "ECD B": {
                        "Green Class": [
                            {value: 'ps_ecdb1', text: 'Amelia Lee', age: '5', gender: 'Female', grade: 'A'},
                            {value: 'ps_ecdb2', text: 'James Perez', age: '6', gender: 'Male', grade: 'B'},
                            {value: 'ps_ecdb3', text: 'Charlotte Thompson', age: '5', gender: 'Female', grade: 'C'},
                            {value: 'ps_ecdb4', text: 'Benjamin White', age: '6', gender: 'Male', grade: 'A'},
                            {value: 'ps_ecdb5', text: 'Harper Harris', age: '5', gender: 'Female', grade: 'B'},
                            {value: 'ps_ecdb6', text: 'Elijah Sanchez', age: '6', gender: 'Male', grade: 'A'}
                        ],
                        "Yellow Class": [
                            {value: 'ps_ecdb7', text: 'Evelyn Clark', age: '5', gender: 'Female', grade: 'B'},
                            {value: 'ps_ecdb8', text: 'Daniel Ramirez', age: '6', gender: 'Male', grade: 'C'},
                            {value: 'ps_ecdb9', text: 'Abigail Lewis', age: '5', gender: 'Female', grade: 'A'},
                            {value: 'ps_ecdb10', text: 'Henry Robinson', age: '6', gender: 'Male', grade: 'B'},
                            {value: 'ps_ecdb11', text: 'Emily Walker', age: '5', gender: 'Female', grade: 'A'},
                            {value: 'ps_ecdb12', text: 'Alexander Young', age: '6', gender: 'Male', grade: 'C'}
                        ]
                    },
                    "ECD C": {
                        "Orange Class": [
                            {value: 'ps_ecdc1', text: 'Sofia King', age: '6', gender: 'Female', grade: 'A'},
                            {value: 'ps_ecdc2', text: 'Sebastian Wright', age: '7', gender: 'Male', grade: 'B'},
                            {value: 'ps_ecdc3', text: 'Avery Lopez', age: '6', gender: 'Female', grade: 'C'},
                            {value: 'ps_ecdc4', text: 'Jack Hill', age: '7', gender: 'Male', grade: 'A'},
                            {value: 'ps_ecdc5', text: 'Ella Scott', age: '6', gender: 'Female', grade: 'B'},
                            {value: 'ps_ecdc6', text: 'Owen Green', age: '7', gender: 'Male', grade: 'A'}
                        ],
                        "Purple Class": [
                            {value: 'ps_ecdc7', text: 'Scarlett Adams', age: '6', gender: 'Female', grade: 'B'},
                            {value: 'ps_ecdc8', text: 'Samuel Baker', age: '7', gender: 'Male', grade: 'C'},
                            {value: 'ps_ecdc9', text: 'Grace Nelson', age: '6', gender: 'Female', grade: 'A'},
                            {value: 'ps_ecdc10', text: 'David Carter', age: '7', gender: 'Male', grade: 'B'},
                            {value: 'ps_ecdc11', text: 'Chloe Mitchell', age: '6', gender: 'Female', grade: 'A'},
                            {value: 'ps_ecdc12', text: 'Joseph Perez', age: '7', gender: 'Male', grade: 'C'}
                        ]
                    }
                }
            },
            primary: {
                levels: ["Level 1", "Level 2", "Level 3"],
                classes: {
                    "Level 1": ["Class 1A", "Class 1B"],
                    "Level 2": ["Class 2A", "Class 2B"],
                    "Level 3": ["Class 3A", "Class 3B"]
                },
                learners: {
                    "Level 1": {
                        "Class 1A": [
                            {value: 'p_l1_1', text: 'John Doe', age: '7', gender: 'Male', grade: 'C'},
                            {value: 'p_l1_2', text: 'Jane Smith', age: '7', gender: 'Female', grade: 'A'},
                            {value: 'p_l1_3', text: 'Robert Johnson', age: '7', gender: 'Male', grade: 'B'},
                            {value: 'p_l1_4', text: 'Lisa Davis', age: '7', gender: 'Female', grade: 'A'},
                            {value: 'p_l1_5', text: 'Michael Wilson', age: '7', gender: 'Male', grade: 'D'},
                            {value: 'p_l1_6', text: 'Sarah Miller', age: '7', gender: 'Female', grade: 'B'}
                        ],
                        "Class 1B": [
                            {value: 'p_l1_7', text: 'David Brown', age: '7', gender: 'Male', grade: 'A'},
                            {value: 'p_l1_8', text: 'Jennifer Taylor', age: '7', gender: 'Female', grade: 'C'},
                            {value: 'p_l1_9', text: 'Richard Moore', age: '7', gender: 'Male', grade: 'B'},
                            {value: 'p_l1_10', text: 'Jessica Anderson', age: '7', gender: 'Female', grade: 'A'},
                            {value: 'p_l1_11', text: 'Charles Thomas', age: '7', gender: 'Male', grade: 'B'},
                            {value: 'p_l1_12', text: 'Susan Jackson', age: '7', gender: 'Female', grade: 'C'}
                        ]
                    },
                    "Level 2": {
                        "Class 2A": [
                            {value: 'p_l2_1', text: 'Mary Johnson', age: '8', gender: 'Female', grade: 'D'},
                            {value: 'p_l2_2', text: 'Peter Brown', age: '8', gender: 'Male', grade: 'A'},
                            {value: 'p_l2_3', text: 'Linda Davis', age: '8', gender: 'Female', grade: 'B'},
                            {value: 'p_l2_4', text: 'James Miller', age: '8', gender: 'Male', grade: 'C'},
                            {value: 'p_l2_5', text: 'Patricia Wilson', age: '8', gender: 'Female', grade: 'A'},
                            {value: 'p_l2_6', text: 'Christopher Moore', age: '8', gender: 'Male', grade: 'B'}
                        ],
                        "Class 2B": [
                            {value: 'p_l2_7', text: 'Barbara Taylor', age: '8', gender: 'Female', grade: 'C'},
                            {value: 'p_l2_8', text: 'Daniel Anderson', age: '8', gender: 'Male', grade: 'A'},
                            {value: 'p_l2_9', text: 'Elizabeth Thomas', age: '8', gender: 'Female', grade: 'B'},
                            {value: 'p_l2_10', text: 'Matthew Jackson', age: '8', gender: 'Male', grade: 'D'},
                            {value: 'p_l2_11', text: 'Helen White', age: '8', gender: 'Female', grade: 'A'},
                            {value: 'p_l2_12', text: 'Anthony Harris', age: '8', gender: 'Male', grade: 'B'}
                        ]
                    },
                    "Level 3": {
                        "Class 3A": [
                            {value: 'p_l3_1', text: 'Alice White', age: '9', gender: 'Female', grade: 'C'},
                            {value: 'p_l3_2', text: 'David Black', age: '9', gender: 'Male', grade: 'B'},
                            {value: 'p_l3_3', text: 'Margaret Martin', age: '9', gender: 'Female', grade: 'A'},
                            {value: 'p_l3_4', text: 'Paul Thompson', age: '9', gender: 'Male', grade: 'B'},
                            {value: 'p_l3_5', text: 'Dorothy Garcia', age: '9', gender: 'Female', grade: 'C'},
                            {value: 'p_l3_6', text: 'Mark Martinez', age: '9', gender: 'Male', grade: 'A'}
                        ],
                        "Class 3B": [
                            {value: 'p_l3_7', text: 'Betty Robinson', age: '9', gender: 'Female', grade: 'B'},
                            {value: 'p_l3_8', text: 'Donald Clark', age: '9', gender: 'Male', grade: 'A'},
                            {value: 'p_l3_9', text: 'Sandra Rodriguez', age: '9', gender: 'Female', grade: 'C'},
                            {value: 'p_l3_10', text: 'George Lewis', age: '9', gender: 'Male', grade: 'B'},
                            {value: 'p_l3_11', text: 'Carol Lee', age: '9', gender: 'Female', grade: 'A'},
                            {value: 'p_l3_12', text: 'Kenneth Walker', age: '9', gender: 'Male', grade: 'B'}
                        ]
                    }
                }
            },
            secondary: {
                levels: ["Form 1", "Form 2", "Form 3"],
                classes: {
                    "Form 1": ["Science Stream", "Arts Stream"],
                    "Form 2": ["Science Stream", "Arts Stream"],
                    "Form 3": ["Science Stream", "Arts Stream"]
                },
                learners: {
                    "Form 1": {
                        "Science Stream": [
                            {value: 's_f1_1', text: 'Sarah Wilson', age: '14', gender: 'Female', grade: 'A'},
                            {value: 's_f1_2', text: 'Michael Taylor', age: '14', gender: 'Male', grade: 'B'},
                            {value: 's_f1_3', text: 'Nancy Young', age: '14', gender: 'Female', grade: 'C'},
                            {value: 's_f1_4', text: 'Steven King', age: '14', gender: 'Male', grade: 'A'},
                            {value: 's_f1_5', text: 'Karen Wright', age: '14', gender: 'Female', grade: 'B'},
                            {value: 's_f1_6', text: 'Edward Lopez', age: '14', gender: 'Male', grade: 'A'}
                        ],
                        "Arts Stream": [
                            {value: 's_f1_7', text: 'Donna Hill', age: '14', gender: 'Female', grade: 'C'},
                            {value: 's_f1_8', text: 'Brian Scott', age: '14', gender: 'Male', grade: 'B'},
                            {value: 's_f1_9', text: 'Michelle Green', age: '14', gender: 'Female', grade: 'A'},
                            {value: 's_f1_10', text: 'Ronald Adams', age: '14', gender: 'Male', grade: 'B'},
                            {value: 's_f1_11', text: 'Laura Baker', age: '14', gender: 'Female', grade: 'C'},
                            {value: 's_f1_12', text: 'Jason Nelson', age: '14', gender: 'Male', grade: 'A'}
                        ]
                    },
                    "Form 2": {
                        "Science Stream": [
                            {value: 's_f2_1', text: 'Emily Anderson', age: '15', gender: 'Female', grade: 'A'},
                            {value: 's_f2_2', text: 'James Thomas', age: '15', gender: 'Male', grade: 'C'},
                            {value: 's_f2_3', text: 'Angela Carter', age: '15', gender: 'Female', grade: 'B'},
                            {value: 's_f2_4', text: 'Kevin Mitchell', age: '15', gender: 'Male', grade: 'A'},
                            {value: 's_f2_5', text: 'Ruth Perez', age: '15', gender: 'Female', grade: 'C'},
                            {value: 's_f2_6', text: 'Timothy Roberts', age: '15', gender: 'Male', grade: 'B'}
                        ],
                        "Arts Stream": [
                            {value: 's_f2_7', text: 'Sharon Turner', age: '15', gender: 'Female', grade: 'A'},
                            {value: 's_f2_8', text: 'Jeffrey Phillips', age: '15', gender: 'Male', grade: 'B'},
                            {value: 's_f2_9', text: 'Cynthia Campbell', age: '15', gender: 'Female', grade: 'C'},
                            {value: 's_f2_10', text: 'Ryan Parker', age: '15', gender: 'Male', grade: 'A'},
                            {value: 's_f2_11', text: 'Kathleen Evans', age: '15', gender: 'Female', grade: 'B'},
                            {value: 's_f2_12', text: 'Gary Edwards', age: '15', gender: 'Male', grade: 'C'}
                        ]
                    },
                    "Form 3": {
                        "Science Stream": [
                            {value: 's_f3_1', text: 'Daniel Jackson', age: '16', gender: 'Male', grade: 'A'},
                            {value: 's_f3_2', text: 'Sophia Harris', age: '16', gender: 'Female', grade: 'B'},
                            {value: 's_f3_3', text: 'Joshua Collins', age: '16', gender: 'Male', grade: 'C'},
                            {value: 's_f3_4', text: 'Amanda Stewart', age: '16', gender: 'Female', grade: 'A'},
                            {value: 's_f3_5', text: 'Eric Morris', age: '16', gender: 'Male', grade: 'B'},
                            {value: 's_f3_6', text: 'Stephanie Rogers', age: '16', gender: 'Female', grade: 'A'}
                        ],
                        "Arts Stream": [
                            {value: 's_f3_7', text: 'Jacob Reed', age: '16', gender: 'Male', grade: 'C'},
                            {value: 's_f3_8', text: 'Deborah Cook', age: '16', gender: 'Female', grade: 'B'},
                            {value: 's_f3_9', text: 'Nicholas Morgan', age: '16', gender: 'Male', grade: 'A'},
                            {value: 's_f3_10', text: 'Rachel Bell', age: '16', gender: 'Female', grade: 'B'},
                            {value: 's_f3_11', text: 'Jonathan Murphy', age: '16', gender: 'Male', grade: 'C'},
                            {value: 's_f3_12', text: 'Heather Bailey', age: '16', gender: 'Female', grade: 'A'}
                        ]
                    }
                }
            }
        };

        // Filter options data
        const filterOptions = {
            learner_name: [],
            age: {
                preschool: ['4', '5', '6', '7'],
                primary: ['7', '8', '9'],
                secondary: ['14', '15', '16']
            },
            gender: ['Male', 'Female'],
            grade: ['A', 'B', 'C', 'D', 'E'],
            subject: ['Mathematics', 'English', 'Science', 'Biology', 'Chemistry', 'Physics', 'Coloring', 'Story Time', 'Play Activities', 'Numbers', 'Letters', 'Arts & Crafts', 'Basic Math', 'Reading', 'Writing']
        };

        // Dummy marks per student with sub teacher comments for each term
        const marksByLearner = {
            // Pre School students - ECD A
            'ps_ecda1': {
                term1: [
                    {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.'}
                ],
                term2: [
                    {subject: 'Coloring', actual: 88, possible: 100, subTeacherComments: 'Continued improvement in coloring skills.'},
                    {subject: 'Story Time', actual: 92, possible: 100, subTeacherComments: 'Excellent comprehension and recall of stories.'},
                    {subject: 'Play Activities', actual: 90, possible: 100, subTeacherComments: 'Shows leadership in group activities.'}
                ],
                term3: [
                    {subject: 'Coloring', actual: 92, possible: 100, subTeacherComments: 'Mastered coloring skills. Very creative.'},
                    {subject: 'Story Time', actual: 95, possible: 100, subTeacherComments: 'Exceptional listening and comprehension skills.'},
                    {subject: 'Play Activities', actual: 93, possible: 100, subTeacherComments: 'Excellent social skills and teamwork.'}
                ]
            },
            'ps_ecda2': {
                term1: [
                    {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.'}
                ],
                term2: [
                    {subject: 'Coloring', actual: 82, possible: 100, subTeacherComments: 'Showing improvement in fine motor skills.'},
                    {subject: 'Story Time', actual: 85, possible: 100, subTeacherComments: 'Attention span has improved significantly.'},
                    {subject: 'Play Activities', actual: 83, possible: 100, subTeacherComments: 'Starting to participate more in group activities.'}
                ],
                term3: [
                    {subject: 'Coloring', actual: 85, possible: 100, subTeacherComments: 'Good progress in coloring skills.'},
                    {subject: 'Story Time', actual: 88, possible: 100, subTeacherComments: 'Much better focus during story time.'},
                    {subject: 'Play Activities', actual: 86, possible: 100, subTeacherComments: 'Participates well in both individual and group play.'}
                ]
            },
            // Primary students
            'p_l1_1': {
                term1: [
                    {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.'}
                ],
                term2: [
                    {subject: 'Mathematics', actual: 82, possible: 100, subTeacherComments: 'Multiplication skills have improved significantly.'},
                    {subject: 'English', actual: 70, possible: 100, subTeacherComments: 'Grammar is improving with practice.'},
                    {subject: 'Science', actual: 85, possible: 100, subTeacherComments: 'Continues to excel in hands-on experiments.'}
                ],
                term3: [
                    {subject: 'Mathematics', actual: 85, possible: 100, subTeacherComments: 'Good progress in all mathematical areas.'},
                    {subject: 'English', actual: 75, possible: 100, subTeacherComments: 'Reading comprehension has improved.'},
                    {subject: 'Science', actual: 88, possible: 100, subTeacherComments: 'Excellent scientific reasoning skills.'}
                ]
            },
            'p_l1_2': {
                term1: [
                    {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.'}
                ],
                term2: [
                    {subject: 'Mathematics', actual: 92, possible: 100, subTeacherComments: 'Excelling in advanced mathematical concepts.'},
                    {subject: 'English', actual: 78, possible: 100, subTeacherComments: 'Writing skills continue to develop nicely.'},
                    {subject: 'Science', actual: 93, possible: 100, subTeacherComments: 'Exceptional curiosity and scientific thinking.'}
                ],
                term3: [
                    {subject: 'Mathematics', actual: 95, possible: 100, subTeacherComments: 'Outstanding mathematical ability.'},
                    {subject: 'English', actual: 85, possible: 100, subTeacherComments: 'Excellent writing and comprehension skills.'},
                    {subject: 'Science', actual: 96, possible: 100, subTeacherComments: 'Exceptional performance across all science topics.'}
                ]
            },
            // Secondary students
            's_f1_1': {
                term1: [
                    {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.'}
                ],
                term2: [
                    {subject: 'Mathematics', actual: 88, possible: 100, subTeacherComments: 'Excellent progress in advanced algebra.'},
                    {subject: 'English', actual: 82, possible: 100, subTeacherComments: 'Essay writing skills have improved significantly.'},
                    {subject: 'Biology', actual: 85, possible: 100, subTeacherComments: 'Strong performance in genetics unit.'}
                ],
                term3: [
                    {subject: 'Mathematics', actual: 92, possible: 100, subTeacherComments: 'Mastered all mathematical concepts for the year.'},
                    {subject: 'English', actual: 85, possible: 100, subTeacherComments: 'Excellent critical analysis of literature.'},
                    {subject: 'Biology', actual: 88, possible: 100, subTeacherComments: 'Outstanding performance in all biology topics.'}
                ]
            },
            's_f1_2': {
                term1: [
                    {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.'}
                ],
                term2: [
                    {subject: 'Mathematics', actual: 78, possible: 100, subTeacherComments: 'Word problem skills are improving with practice.'},
                    {subject: 'English', actual: 83, possible: 100, subTeacherComments: 'Writing fluency has improved significantly.'},
                    {subject: 'Biology', actual: 80, possible: 100, subTeacherComments: 'Better retention of biological terminology.'}
                ],
                term3: [
                    {subject: 'Mathematics', actual: 82, possible: 100, subTeacherComments: 'Good progress in mathematical reasoning.'},
                    {subject: 'English', actual: 85, possible: 100, subTeacherComments: 'Writing skills at grade level now.'},
                    {subject: 'Biology', actual: 83, possible: 100, subTeacherComments: 'Solid understanding of biological concepts.'}
                ]
            }
        };

        // Comments data
        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."
            },
            '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_f1_2': {
                classTeacher: "Michael needs to improve in Biology. Recommend additional tutoring sessions.",
                headTeacher: "Average performance. Focus on weak areas for final exams."
            }
        };

        // Track selected filters
        let selectedFilters = [];
        let specificLearnerSelected = false;

        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_class').innerHTML = '<option value="">Select Class</option>';
            
            if (educationLevel && educationLevels[educationLevel]) {
                educationLevels[educationLevel].levels.forEach(level => {
                    const option = document.createElement('option');
                    option.value = level;
                    option.text = level;
                    learnerLevelSelect.appendChild(option);
                });
            }
            
            // Update filter values if learner_name is selected
            updateFilterValueRows();
        }

        function populateLearnerClass() {
            const educationLevel = document.getElementById('report_type').value;
            const learnerLevel = document.getElementById('learner_level').value;
            const learnerClassSelect = document.getElementById('learner_class');

            learnerClassSelect.innerHTML = '<option value="">Select Class</option>';

            if (educationLevel && learnerLevel && educationLevels[educationLevel] && educationLevels[educationLevel].classes[learnerLevel]) {
                educationLevels[educationLevel].classes[learnerLevel].forEach(classItem => {
                    const option = document.createElement('option');
                    option.value = classItem;
                    option.text = classItem;
                    learnerClassSelect.appendChild(option);
                });
            }
            
            // Update filter values if learner_name is selected
            updateFilterValueRows();
        }

        function updateSelectedFilters() {
            selectedFilters = [];
            const checkboxes = document.querySelectorAll('.filter-checkbox input[type="checkbox"]:checked');
            
            checkboxes.forEach(checkbox => {
                selectedFilters.push(checkbox.value);
            });
            
            updateSelectedFiltersDisplay();
            updateFilterValueRows();
            updateFilterCheckboxStates();
        }

        function updateSelectedFiltersDisplay() {
            const selectedFiltersContainer = document.getElementById('selected_filters');
            selectedFiltersContainer.innerHTML = '';
            
            selectedFilters.forEach(filter => {
                const filterTag = document.createElement('div');
                filterTag.className = 'selected-filter-tag';
                filterTag.innerHTML = `
                    ${filter.replace('_', ' ')}
                    <span class="remove-filter" data-filter="${filter}">×</span>
                `;
                selectedFiltersContainer.appendChild(filterTag);
            });
            
            // Add event listeners to remove buttons
            document.querySelectorAll('.remove-filter').forEach(button => {
                button.addEventListener('click', function() {
                    const filterToRemove = this.getAttribute('data-filter');
                    document.getElementById(`filter_${filterToRemove}`).checked = false;
                    updateSelectedFilters();
                });
            });
        }

        function updateFilterCheckboxStates() {
            const learnerNameCheckbox = document.getElementById('filter_learner_name');
            const learnerNameValue = document.getElementById('filter_learner_name_value');
            
            // Check if a specific learner is selected (not "Select All")
            specificLearnerSelected = learnerNameCheckbox.checked && 
                                     learnerNameValue && 
                                     learnerNameValue.value && 
                                     learnerNameValue.value !== 'all';
            
            // Enable/disable other filter checkboxes based on whether a specific learner is selected
            const otherFilterCheckboxes = [
                document.getElementById('filter_age'),
                document.getElementById('filter_gender'),
                document.getElementById('filter_grade'),
                document.getElementById('filter_subject')
            ];
            
            const otherFilterContainers = [
                document.getElementById('age_checkbox'),
                document.getElementById('gender_checkbox'),
                document.getElementById('grade_checkbox'),
                document.getElementById('subject_checkbox')
            ];
            
            otherFilterCheckboxes.forEach((checkbox, index) => {
                if (specificLearnerSelected) {
                    // If specific learner is selected, disable and uncheck other filters
                    checkbox.checked = false;
                    checkbox.disabled = true;
                    otherFilterContainers[index].classList.add('disabled');
                } else {
                    // If no specific learner is selected, enable other filters
                    checkbox.disabled = false;
                    otherFilterContainers[index].classList.remove('disabled');
                }
            });
            
            // Update selected filters array to remove other filters if specific learner is selected
            if (specificLearnerSelected) {
                selectedFilters = selectedFilters.filter(filter => 
                    filter === 'learner_name' || 
                    (otherFilterCheckboxes.find(cb => cb.value === filter) && cb.checked)
                );
                updateSelectedFiltersDisplay();
            }
        }

        function updateFilterValueRows() {
            const filterValueRowsContainer = document.getElementById('filter_value_rows');
            filterValueRowsContainer.innerHTML = '';
            
            selectedFilters.forEach(filter => {
                const row = document.createElement('div');
                row.className = 'filter-row';
                row.innerHTML = `
                    <div class="form-group">
                        <label>${filter.replace('_', ' ')}</label>
                        <select name="filter_${filter}_value" id="filter_${filter}_value" class="form-control">
                            <option value="">Select ${filter.replace('_', ' ')}</option>
                        </select>
                    </div>
                `;
                filterValueRowsContainer.appendChild(row);
                
                // Populate the filter values
                populateFilterValues(filter);
                
                // Add event listener for learner name changes
                if (filter === 'learner_name') {
                    document.getElementById('filter_learner_name_value').addEventListener('change', function() {
                        updateFilterCheckboxStates();
                        document.getElementById('resultsSection').style.display = 'none';
                    });
                }
            });
        }

        function populateFilterValues(filterType) {
            const educationLevel = document.getElementById('report_type').value;
            const learnerLevel = document.getElementById('learner_level').value;
            const learnerClass = document.getElementById('learner_class').value;
            const filterValueSelect = document.getElementById(`filter_${filterType}_value`);
            
            if (!filterValueSelect) return;
            
            filterValueSelect.innerHTML = '<option value="">Select Value</option>';
            
            if (filterType && filterOptions[filterType]) {
                let options = [];
                
                if (filterType === 'learner_name') {
                    // Add "Select All" option
                    options.push({value: 'all', text: 'All Learners'});
                    
                    // Populate with learners based on selected education level, learner level, and class
                    if (educationLevel && learnerLevel && learnerClass && 
                        educationLevels[educationLevel] && 
                        educationLevels[educationLevel].learners[learnerLevel] && 
                        educationLevels[educationLevel].learners[learnerLevel][learnerClass]) {
                        
                        educationLevels[educationLevel].learners[learnerLevel][learnerClass].forEach(l => {
                            options.push({value: l.value, text: l.text});
                        });
                    }
                } else if (filterType === 'age' && educationLevel) {
                    options = filterOptions.age[educationLevel] || [];
                } else {
                    options = filterOptions[filterType];
                }
                
                options.forEach(value => {
                    const option = document.createElement('option');
                    if (typeof value === 'object') {
                        option.value = value.value;
                        option.text = value.text;
                    } else {
                        option.value = value;
                        option.text = value;
                    }
                    filterValueSelect.appendChild(option);
                });
            }
        }

        function updateTable(learner, term) {
            const tableBody = document.querySelector(`#${term}_table tbody`);
            const tableFoot = document.querySelector(`#${term}_table tfoot tr`);
            
            tableBody.innerHTML = '';
            
            if (!learner || !marksByLearner[learner] || !marksByLearner[learner][term]) {
                tableBody.innerHTML = '<tr><td colspan="6" style="text-align:center;">No data available for selected term.</td></tr>';
                tableFoot.cells[1].innerText = '';
                tableFoot.cells[2].innerText = '';
                return;
            }

            let totalActual = 0;
            let totalPossible = 0;
            
            marksByLearner[learner][term].forEach(row => {
                const percentage = (row.possible > 0) ? (row.actual / row.possible) * 100 : 0;
                let grade = '';
                if (percentage >= 80) grade = 'A';
                else if (percentage >= 70) grade = 'B';
                else if (percentage >= 60) grade = 'C';
                else if (percentage >= 50) grade = 'D';
                else grade = 'E';

                totalActual += row.actual;
                totalPossible += row.possible;

                tableBody.innerHTML += `<tr>
                    <td>${row.subject}</td>
                    <td style='text-align:right;'>${row.actual}</td>
                    <td style='text-align:right;'>${row.possible}</td>
                    <td style='text-align:right;'>${percentage.toFixed(2)}</td>
                    <td>${grade}</td>
                    <td>${row.subTeacherComments}</td>
                </tr>`;
            });

            tableFoot.cells[1].innerText = totalActual;
            tableFoot.cells[2].innerText = totalPossible;
        }

        function updateSingleTable(learner, term) {
            const tableBody = document.querySelector('#exam_table tbody');
            const tableFoot = document.querySelector('#exam_table tfoot tr');
            
            tableBody.innerHTML = '';
            
            if (!learner || !marksByLearner[learner] || !marksByLearner[learner][term]) {
                tableBody.innerHTML = '<tr><td colspan="6" style="text-align:center;">No data available for selected student and term.</td></tr>';
                tableFoot.cells[1].innerText = '';
                tableFoot.cells[2].innerText = '';
                return;
            }

            let totalActual = 0;
            let totalPossible = 0;
            
            marksByLearner[learner][term].forEach(row => {
                const percentage = (row.possible > 0) ? (row.actual / row.possible) * 100 : 0;
                let grade = '';
                if (percentage >= 80) grade = 'A';
                else if (percentage >= 70) grade = 'B';
                else if (percentage >= 60) grade = 'C';
                else if (percentage >= 50) grade = 'D';
                else grade = 'E';

                totalActual += row.actual;
                totalPossible += row.possible;

                tableBody.innerHTML += `<tr>
                    <td>${row.subject}</td>
                    <td style='text-align:right;'>${row.actual}</td>
                    <td style='text-align:right;'>${row.possible}</td>
                    <td style='text-align:right;'>${percentage.toFixed(2)}</td>
                    <td>${grade}</td>
                    <td>${row.subTeacherComments}</td>
                </tr>`;
            });

            tableFoot.cells[1].innerText = totalActual;
            tableFoot.cells[2].innerText = totalPossible;
        }

        function updateAllLearnersTable() {
            const educationLevel = document.getElementById('report_type').value;
            const learnerLevel = document.getElementById('learner_level').value;
            const learnerClass = document.getElementById('learner_class').value;
            const term = document.getElementById('exam_type').value;
            const showAllTerms = document.getElementById('show_all_terms').checked;
            
            const tableBody = document.getElementById('all_learners_tbody');
            tableBody.innerHTML = '';
            
            if (!educationLevel || !learnerLevel || !learnerClass) {
                tableBody.innerHTML = '<tr><td colspan="7" style="text-align:center;">Please select Education Level, Learner Level, and Class first.</td></tr>';
                return;
            }
            
            // Get all learners for the selected class
            const learners = educationLevels[educationLevel].learners[learnerLevel][learnerClass];
            
            if (!learners || learners.length === 0) {
                tableBody.innerHTML = '<tr><td colspan="7" style="text-align:center;">No learners found for the selected class.</td></tr>';
                return;
            }
            
            learners.forEach(learner => {
                // Calculate average percentage for the selected term(s)
                let totalPercentage = 0;
                let subjectCount = 0;
                let overallGrade = 'N/A';
                
                if (showAllTerms) {
                    // Calculate average across all terms
                    ['term1', 'term2', 'term3'].forEach(term => {
                        if (marksByLearner[learner.value] && marksByLearner[learner.value][term]) {
                            marksByLearner[learner.value][term].forEach(subject => {
                                const percentage = (subject.actual / subject.possible) * 100;
                                totalPercentage += percentage;
                                subjectCount++;
                            });
                        }
                    });
                } else if (term && marksByLearner[learner.value] && marksByLearner[learner.value][term]) {
                    // Calculate for specific term
                    marksByLearner[learner.value][term].forEach(subject => {
                        const percentage = (subject.actual / subject.possible) * 100;
                        totalPercentage += percentage;
                        subjectCount++;
                    });
                }
                
                const averagePercentage = subjectCount > 0 ? (totalPercentage / subjectCount) : 0;
                
                // Determine overall grade
                if (averagePercentage >= 80) overallGrade = 'A';
                else if (averagePercentage >= 70) overallGrade = 'B';
                else if (averagePercentage >= 60) overallGrade = 'C';
                else if (averagePercentage >= 50) overallGrade = 'D';
                else overallGrade = 'E';
                
                const row = document.createElement('tr');
                row.className = 'learner-row';
                row.innerHTML = `
                    <td>${learner.text}</td>
                    <td>${learner.age}</td>
                    <td>${learner.gender}</td>
                    <td>${learnerClass}</td>
                    <td>${averagePercentage > 0 ? averagePercentage.toFixed(2) + '%' : 'N/A'}</td>
                    <td>${overallGrade}</td>
                    <td>
                        <button class="btn-search" style="padding: 5px 10px; font-size: 12px;" onclick="viewLearnerDetails('${learner.value}')">
                            View Details
                        </button>
                    </td>
                `;
                tableBody.appendChild(row);
            });
        }

        function viewLearnerDetails(learnerId) {
            // Set the learner name filter to the selected learner
            document.getElementById('filter_learner_name').checked = true;
            document.getElementById('filter_learner_name_value').value = learnerId;
            
            // Update the interface
            updateSelectedFilters();
            updateFilterCheckboxStates();
            
            // Hide all learners table and show single learner table
            document.getElementById('allLearnersTable').style.display = 'none';
            document.getElementById('singleTermTable').style.display = 'block';
            document.getElementById('allTermsTables').style.display = 'none';
            
            // Update the single learner table
            const term = document.getElementById('exam_type').value;
            const showAllTerms = document.getElementById('show_all_terms').checked;
            
            if (showAllTerms) {
                document.getElementById('singleTermTable').style.display = 'none';
                document.getElementById('allTermsTables').style.display = 'block';
                updateTable(learnerId, 'term1');
                updateTable(learnerId, 'term2');
                updateTable(learnerId, 'term3');
            } else {
                document.getElementById('singleTermTable').style.display = 'block';
                document.getElementById('allTermsTables').style.display = 'none';
                updateSingleTable(learnerId, term);
            }
            
            // Update comments
            const classTeacherComment = document.getElementById('classTeacherComment');
            const headTeacherComment = document.getElementById('headTeacherComment');
            
            if (commentsData[learnerId]) {
                classTeacherComment.textContent = commentsData[learnerId].classTeacher;
                headTeacherComment.textContent = commentsData[learnerId].headTeacher;
            } else {
                classTeacherComment.textContent = 'No comment available.';
                headTeacherComment.textContent = 'No comment available.';
            }
        }

        // Event listeners for filter checkboxes
        document.querySelectorAll('.filter-checkbox input[type="checkbox"]').forEach(checkbox => {
            checkbox.addEventListener('change', updateSelectedFilters);
        });

        // Other event listeners
        document.getElementById('report_type').addEventListener('change', function() {
            populateLearnerLevels();
            document.getElementById('resultsSection').style.display = 'none';
        });
        
        document.getElementById('learner_level').addEventListener('change', function() {
            populateLearnerClass();
            document.getElementById('resultsSection').style.display = 'none';
        });
        
        document.getElementById('learner_class').addEventListener('change', function() {
            updateFilterValueRows();
            document.getElementById('resultsSection').style.display = 'none';
        });
        
        document.getElementById('exam_type').addEventListener('change', function() {
            document.getElementById('resultsSection').style.display = 'none';
        });

        document.getElementById('show_all_terms').addEventListener('change', function() {
            document.getElementById('resultsSection').style.display = 'none';
        });

        document.getElementById('searchBtn').addEventListener('click', function() {
            const term = document.getElementById('exam_type').value;
            const showAllTerms = document.getElementById('show_all_terms').checked;
            
            if (selectedFilters.length === 0) {
                alert('Please select at least one filter before searching.');
                return;
            }
            
            // Check if all selected filters have values
            let allFiltersHaveValues = true;
            selectedFilters.forEach(filter => {
                const filterValue = document.getElementById(`filter_${filter}_value`).value;
                if (!filterValue) {
                    allFiltersHaveValues = false;
                }
            });
            
            if (!allFiltersHaveValues) {
                alert('Please select values for all selected filters before searching.');
                return;
            }
            
            if (!showAllTerms && !term) {
                alert('Please select a term or check "Show all Terms" before searching.');
                return;
            }
            
            const resultsSection = document.getElementById('resultsSection');
            const classTeacherComment = document.getElementById('classTeacherComment');
            const headTeacherComment = document.getElementById('headTeacherComment');
            
            // For learner_name filter, use the selected learner
            let learner = '';
            let showAllLearners = false;
            
            if (selectedFilters.includes('learner_name')) {
                const learnerValue = document.getElementById('filter_learner_name_value').value;
                if (learnerValue === 'all') {
                    showAllLearners = true;
                } else {
                    learner = learnerValue;
                }
            }
            
            // Show/hide appropriate tables
            if (showAllLearners) {
                // Show all learners table
                document.getElementById('singleTermTable').style.display = 'none';
                document.getElementById('allTermsTables').style.display = 'none';
                document.getElementById('allLearnersTable').style.display = 'block';
                
                // Update all learners table
                updateAllLearnersTable();
                
                // Hide comments section for all learners view
                document.querySelector('.comments-section').style.display = 'none';
            } else {
                // Show single learner tables
                document.getElementById('allLearnersTable').style.display = 'none';
                document.querySelector('.comments-section').style.display = 'block';
                
                // Update comments
                if (learner && commentsData[learner]) {
                    classTeacherComment.textContent = commentsData[learner].classTeacher;
                    headTeacherComment.textContent = commentsData[learner].headTeacher;
                } else {
                    classTeacherComment.textContent = 'No comment available.';
                    headTeacherComment.textContent = 'No comment available.';
                }
                
                if (showAllTerms) {
                    // Show all terms tables
                    document.getElementById('singleTermTable').style.display = 'none';
                    document.getElementById('allTermsTables').style.display = 'block';
                    
                    // Update each term table
                    updateTable(learner, 'term1');
                    updateTable(learner, 'term2');
                    updateTable(learner, 'term3');
                } else {
                    // Show single term table
                    document.getElementById('singleTermTable').style.display = 'block';
                    document.getElementById('allTermsTables').style.display = 'none';
                    
                    // Update single table
                    updateSingleTable(learner, term);
                }
            }
            
            resultsSection.style.display = 'block';
        });

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