<!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">
        /* All previous CSS styles remain the same */
        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: #1cfa5fff;
            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> 
                Healthy Rating vs Average Score Report
                <small>Track and analyze student health and 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 Health and 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 health and 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> Healthy Rating vs Average Score 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>Healthy Rating</th>
                                                            <th style="text-align:right;">Average Score (%)</th>
                                                            <th>Health Status</th>
                                                            <th>Performance Level</th>
                                                            <th>Health Comments</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <tr><td colspan="5" 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;">Overall Average:</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>Healthy Rating</th>
                                                                <th style="text-align:right;">Average Score (%)</th>
                                                                <th>Health Status</th>
                                                                <th>Performance Level</th>
                                                                <th>Health Comments</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <tr><td colspan="5" style="text-align:center;">No data available.</td></tr>
                                                        </tbody>
                                                        <tfoot>
                                                            <tr style="font-weight:bold;">
                                                                <td style="text-align:right;">Overall Average:</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>Healthy Rating</th>
                                                                <th style="text-align:right;">Average Score (%)</th>
                                                                <th>Health Status</th>
                                                                <th>Performance Level</th>
                                                                <th>Health Comments</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <tr><td colspan="5" style="text-align:center;">No data available.</td></tr>
                                                        </tbody>
                                                        <tfoot>
                                                            <tr style="font-weight:bold;">
                                                                <td style="text-align:right;">Overall Average:</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>Healthy Rating</th>
                                                                <th style="text-align:right;">Average Score (%)</th>
                                                                <th>Health Status</th>
                                                                <th>Performance Level</th>
                                                                <th>Health Comments</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <tr><td colspan="5" style="text-align:center;">No data available.</td></tr>
                                                        </tbody>
                                                        <tfoot>
                                                            <tr style="font-weight:bold;">
                                                                <td style="text-align:right;">Overall Average:</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>Healthy Rating</th>
                                                                <th>Average Score (%)</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>Health Assessment Comments</h5>
                                    <p id="classTeacherComment">No health assessment comment available.</p>
                                    
                                    <h5>Recommendations</h5>
                                    <p id="headTeacherComment">No recommendations 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']
        };

        // Health rating data per student with health comments for each term
        const healthByLearner = {
            // Pre School students - ECD A
            'ps_ecda1': {
                term1: [
                    {rating: 'Excellent', avgScore: 87.7, healthStatus: 'Very Healthy', performance: 'Excellent', healthComments: 'Regular attendance, active participation, good nutrition.'},
                ],
                term2: [
                    {rating: 'Excellent', avgScore: 90.0, healthStatus: 'Very Healthy', performance: 'Excellent', healthComments: 'Maintaining excellent health and activity levels.'},
                ],
                term3: [
                    {rating: 'Excellent', avgScore: 93.3, healthStatus: 'Very Healthy', performance: 'Excellent', healthComments: 'Consistently healthy with strong performance.'},
                ]
            },
            'ps_ecda2': {
                term1: [
                    {rating: 'Good', avgScore: 80.0, healthStatus: 'Healthy', performance: 'Good', healthComments: 'Occasional absences due to minor illnesses.'},
                ],
                term2: [
                    {rating: 'Good', avgScore: 83.3, healthStatus: 'Healthy', performance: 'Good', healthComments: 'Health improving with better attendance.'},
                ],
                term3: [
                    {rating: 'Good', avgScore: 86.3, healthStatus: 'Healthy', performance: 'Good', healthComments: 'Good health maintenance with steady improvement.'},
                ]
            },
            // Primary students
            'p_l1_1': {
                term1: [
                    {rating: 'Fair', avgScore: 75.0, healthStatus: 'Moderately Healthy', performance: 'Fair', healthComments: 'Frequent colds affecting attendance and performance.'},
                ],
                term2: [
                    {rating: 'Good', avgScore: 79.0, healthStatus: 'Healthy', performance: 'Good', healthComments: 'Health improving with fewer absences.'},
                ],
                term3: [
                    {rating: 'Good', avgScore: 82.7, healthStatus: 'Healthy', performance: 'Good', healthComments: 'Better health leading to improved performance.'},
                ]
            },
            'p_l1_2': {
                term1: [
                    {rating: 'Excellent', avgScore: 83.3, healthStatus: 'Very Healthy', performance: 'Excellent', healthComments: 'Excellent health with perfect attendance.'},
                ],
                term2: [
                    {rating: 'Excellent', avgScore: 87.7, healthStatus: 'Very Healthy', performance: 'Excellent', healthComments: 'Maintaining excellent health and performance.'},
                ],
                term3: [
                    {rating: 'Excellent', avgScore: 92.0, healthStatus: 'Very Healthy', performance: 'Excellent', healthComments: 'Outstanding health and academic performance.'},
                ]
            },
            // Secondary students
            's_f1_1': {
                term1: [
                    {rating: 'Good', avgScore: 81.7, healthStatus: 'Healthy', performance: 'Good', healthComments: 'Good overall health with occasional sports injuries.'},
                ],
                term2: [
                    {rating: 'Excellent', avgScore: 85.0, healthStatus: 'Very Healthy', performance: 'Excellent', healthComments: 'Improved health with regular exercise.'},
                ],
                term3: [
                    {rating: 'Excellent', avgScore: 88.3, healthStatus: 'Very Healthy', performance: 'Excellent', healthComments: 'Excellent health supporting strong performance.'},
                ]
            },
            's_f1_2': {
                term1: [
                    {rating: 'Fair', avgScore: 75.7, healthStatus: 'Moderately Healthy', performance: 'Fair', healthComments: 'Allergies affecting concentration during certain seasons.'},
                ],
                term2: [
                    {rating: 'Good', avgScore: 80.3, healthStatus: 'Healthy', performance: 'Good', healthComments: 'Better management of allergy symptoms.'},
                ],
                term3: [
                    {rating: 'Good', avgScore: 83.3, healthStatus: 'Healthy', performance: 'Good', healthComments: 'Good health maintenance with improved performance.'},
                ]
            }
        };

        // Comments data
        const commentsData = {
            'ps_ecda1': {
                classTeacher: "Emma maintains excellent health with regular attendance and active participation in all activities.",
                headTeacher: "Continue current health practices. Excellent role model for peers."
            },
            'ps_ecda2': {
                classTeacher: "Noah's health has improved significantly this year with better attendance.",
                headTeacher: "Good progress. Focus on nutrition and sleep routines."
            },
            'p_l1_1': {
                classTeacher: "John's health has improved, leading to better academic performance.",
                headTeacher: "Continue health monitoring. Consider nutritional assessment."
            },
            'p_l1_2': {
                classTeacher: "Jane maintains excellent health which supports her strong academic performance.",
                headTeacher: "Excellent health habits. Consider leadership in health awareness activities."
            },
            's_f1_1': {
                classTeacher: "Sarah's improved physical activity has enhanced both health and academic performance.",
                headTeacher: "Outstanding progress. Consider sports leadership opportunities."
            },
            's_f1_2': {
                classTeacher: "Michael has better managed his allergies, improving both health and concentration.",
                headTeacher: "Good improvement. Continue monitoring during allergy seasons."
            }
        };

        // 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 || !healthByLearner[learner] || !healthByLearner[learner][term]) {
                tableBody.innerHTML = '<tr><td colspan="5" style="text-align:center;">No data available for selected term.</td></tr>';
                tableFoot.cells[1].innerText = '';
                return;
            }

            let totalAvgScore = 0;
            let rowCount = 0;
            
            healthByLearner[learner][term].forEach(row => {
                totalAvgScore += row.avgScore;
                rowCount++;

                tableBody.innerHTML += `<tr>
                    <td>${row.rating}</td>
                    <td style='text-align:right;'>${row.avgScore.toFixed(2)}</td>
                    <td>${row.healthStatus}</td>
                    <td>${row.performance}</td>
                    <td>${row.healthComments}</td>
                </tr>`;
            });

            tableFoot.cells[1].innerText = rowCount > 0 ? (totalAvgScore / rowCount).toFixed(2) + '%' : '';
        }

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

            let totalAvgScore = 0;
            let rowCount = 0;
            
            healthByLearner[learner][term].forEach(row => {
                totalAvgScore += row.avgScore;
                rowCount++;

                tableBody.innerHTML += `<tr>
                    <td>${row.rating}</td>
                    <td style='text-align:right;'>${row.avgScore.toFixed(2)}</td>
                    <td>${row.healthStatus}</td>
                    <td>${row.performance}</td>
                    <td>${row.healthComments}</td>
                </tr>`;
            });

            tableFoot.cells[1].innerText = rowCount > 0 ? (totalAvgScore / rowCount).toFixed(2) + '%' : '';
        }

        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 health rating and average score for the selected term(s)
                let healthRating = 'N/A';
                let avgScore = 0;
                let termCount = 0;
                
                if (showAllTerms) {
                    // Calculate average across all terms
                    ['term1', 'term2', 'term3'].forEach(term => {
                        if (healthByLearner[learner.value] && healthByLearner[learner.value][term]) {
                            healthByLearner[learner.value][term].forEach(health => {
                                avgScore += health.avgScore;
                                termCount++;
                            });
                        }
                    });
                } else if (term && healthByLearner[learner.value] && healthByLearner[learner.value][term]) {
                    // Calculate for specific term
                    healthByLearner[learner.value][term].forEach(health => {
                        avgScore += health.avgScore;
                        termCount++;
                    });
                }
                
                const finalAvgScore = termCount > 0 ? (avgScore / termCount) : 0;
                
                // Determine health rating based on average score
                if (finalAvgScore >= 85) healthRating = 'Excellent';
                else if (finalAvgScore >= 75) healthRating = 'Good';
                else if (finalAvgScore >= 65) healthRating = 'Fair';
                else healthRating = 'Needs Improvement';
                
                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>${healthRating}</td>
                    <td>${finalAvgScore > 0 ? finalAvgScore.toFixed(2) + '%' : 'N/A'}</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 health assessment comment available.';
                headTeacherComment.textContent = 'No recommendations 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 health assessment comment available.';
                    headTeacherComment.textContent = 'No recommendations 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>