<?php
session_name('super_admin_session');
if (!is_dir(dirname(__DIR__) . '/session_data/super')) {
    mkdir(dirname(__DIR__) . '/session_data/super', 0700, true);
}
session_save_path(dirname(__DIR__) . '/session_data/super');
session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);
session_start();
error_reporting(0);
ini_set('display_errors', 1);
include('includes/dbconnection.php');
require_once 'includes/session_term_helper.php';
$stResult = resolveCurrentSessionTerm($con);
$currentSessionName = $stResult['session_name'];
$currentTermName = $stResult['term_name'];

?>

<!DOCTYPE html>
<html>
<?php @include("includes/head.php"); ?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.25/jspdf.plugin.autotable.min.js"></script>
<style>
    /* ── Design tokens ─────────────────────────────────────── */
    :root {
        --primary: #4a6fdc;
        --primary-dark: #3a5fc8;
        --primary-light: #eef2ff;
        --success: #22c55e;
        --success-light: #dcfce7;
        --danger: #ef4444;
        --danger-light: #fee2e2;
        --warning: #f59e0b;
        --warning-light: #fef3c7;
        --info: #06b6d4;
        --info-light: #cffafe;
        --purple: #8b5cf6;
        --purple-light: #ede9fe;
        --secondary: #64748b;
        --light: #f8fafc;
        --dark: #1e293b;
        --border: #e2e8f0;
        --radius: 12px;
        --radius-sm: 8px;
        --shadow: 0 1px 3px rgba(0, 0, 0, .08), 0 4px 16px rgba(0, 0, 0, .06);
        --shadow-md: 0 4px 6px rgba(0, 0, 0, .07), 0 10px 30px rgba(0, 0, 0, .08);
        --transition: .2s ease;
    }

    /* ── Reset ─────────────────────────────────────────────── */
    *,
    *::before,
    *::after {
        box-sizing: border-box;
    }

    /* ── Filter card ───────────────────────────────────────── */
    .rpt-filter-card {
        background: #fff;
        border-radius: var(--radius);
        border: 1px solid var(--border);
        padding: 24px;
        margin-bottom: 24px;
        box-shadow: var(--shadow);
    }

    .rpt-filter-card .form-group label {
        font-size: 12px;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: .05em;
        color: var(--secondary);
        margin-bottom: 6px;
    }

    .rpt-filter-card .form-control {
        border-radius: var(--radius-sm);
        border-color: var(--border);
        font-size: 14px;
        height: 42px;
        transition: border-color var(--transition), box-shadow var(--transition);
    }

    .rpt-filter-card .form-control:focus {
        border-color: var(--primary);
        box-shadow: 0 0 0 3px rgba(74, 111, 220, .15);
    }

    .btn-generate {
        background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%);
        color: #fff;
        border: none;
        padding: 11px 32px;
        border-radius: var(--radius-sm);
        font-size: 14px;
        font-weight: 600;
        letter-spacing: .02em;
        cursor: pointer;
        transition: opacity var(--transition), transform var(--transition), box-shadow var(--transition);
        box-shadow: 0 4px 14px rgba(74, 111, 220, .35);
    }

    .btn-generate:hover {
        opacity: .92;
        transform: translateY(-1px);
        box-shadow: 0 6px 20px rgba(74, 111, 220, .4);
    }

    .btn-generate:active {
        transform: translateY(0);
    }

    .btn-generate i {
        margin-right: 6px;
    }

    /* ── Tabs ──────────────────────────────────────────────── */
    .rpt-tabs {
        display: flex;
        flex-wrap: wrap;
        gap: 6px;
        margin-bottom: 24px;
        padding: 6px;
        background: var(--light);
        border-radius: var(--radius);
        border: 1px solid var(--border);
    }

    .rpt-tab {
        display: flex;
        align-items: center;
        gap: 6px;
        padding: 8px 16px;
        border-radius: var(--radius-sm);
        cursor: pointer;
        font-size: 13px;
        font-weight: 600;
        color: var(--secondary);
        border: none;
        background: transparent;
        transition: background var(--transition), color var(--transition), box-shadow var(--transition);
        white-space: nowrap;
    }

    .rpt-tab i {
        font-size: 12px;
    }

    .rpt-tab:hover {
        background: #fff;
        color: var(--primary);
        box-shadow: var(--shadow);
    }

    .rpt-tab.active {
        background: #fff;
        color: var(--primary);
        box-shadow: var(--shadow);
    }

    .rpt-tab.active i {
        color: var(--primary);
    }

    .tab-content {
        display: none;
    }

    .tab-content.active {
        display: block;
        animation: fadeIn .25s ease;
    }

    @keyframes fadeIn {
        from {
            opacity: 0;
            transform: translateY(6px);
        }

        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    /* ── Report section wrapper ────────────────────────────── */
    .report-section {
        background: #fff;
        border-radius: var(--radius);
        border: 1px solid var(--border);
        padding: 24px;
        margin-bottom: 24px;
        box-shadow: var(--shadow);
    }

    .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 14px;
        border-bottom: 2px solid var(--border);
    }

    .section-header h5 {
        font-size: 16px;
        font-weight: 700;
        color: var(--dark);
        margin: 0;
    }

    .btn-download {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        background: linear-gradient(135deg, var(--success) 0%, #16a34a 100%);
        color: #fff;
        border: none;
        padding: 8px 18px;
        border-radius: var(--radius-sm);
        font-size: 13px;
        font-weight: 600;
        cursor: pointer;
        transition: opacity var(--transition), transform var(--transition);
        box-shadow: 0 3px 10px rgba(34, 197, 94, .3);
    }

    .btn-download:hover {
        opacity: .9;
        transform: translateY(-1px);
    }

    .btn-download:active {
        transform: translateY(0);
    }

    /* ── Stat cards ────────────────────────────────────────── */
    .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));
        gap: 16px;
        margin-bottom: 28px;
    }

    .stat-card {
        background: #fff;
        border-radius: var(--radius);
        border: 1px solid var(--border);
        padding: 20px 16px;
        text-align: center;
        box-shadow: var(--shadow);
        transition: transform var(--transition), box-shadow var(--transition);
        position: relative;
        overflow: hidden;
    }

    .stat-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 3px;
        background: var(--card-accent, var(--primary));
        border-radius: var(--radius) var(--radius) 0 0;
    }

    .stat-card:hover {
        transform: translateY(-3px);
        box-shadow: var(--shadow-md);
    }

    .stat-card .stat-icon {
        width: 44px;
        height: 44px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 10px;
        font-size: 18px;
    }

    .stat-card h5 {
        font-size: 11px;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: .06em;
        color: var(--secondary);
        margin: 0 0 6px;
    }

    .stat-value {
        font-size: 22px;
        font-weight: 800;
        color: var(--dark);
        margin: 0 0 4px;
        line-height: 1.2;
    }

    .stat-card p {
        font-size: 11px;
        color: var(--secondary);
        margin: 0;
    }

    /* ── Tables ────────────────────────────────────────────── */
    .rpt-table-wrap {
        overflow-x: auto;
        border-radius: var(--radius-sm);
        border: 1px solid var(--border);
        margin-bottom: 20px;
    }

    table {
        width: 100%;
        border-collapse: collapse;
        font-size: 13px;
    }

    thead tr {
        background: var(--light);
    }

    th {
        padding: 11px 14px;
        text-align: left;
        font-size: 11px;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: .05em;
        color: var(--secondary);
        border-bottom: 2px solid var(--border);
        white-space: nowrap;
    }

    td {
        padding: 11px 14px;
        border-bottom: 1px solid var(--border);
        color: var(--dark);
        vertical-align: middle;
    }

    tbody tr:last-child td {
        border-bottom: none;
    }

    tbody tr:hover {
        background: var(--primary-light);
    }

    .highlight {
        background: #eff6ff !important;
    }

    .highlight td:first-child {
        border-left: 3px solid var(--primary);
    }

    /* rank medal */
    .rank-medal {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 26px;
        height: 26px;
        border-radius: 50%;
        font-size: 11px;
        font-weight: 800;
    }

    .rank-1 {
        background: #fef3c7;
        color: #b45309;
    }

    .rank-2 {
        background: #f1f5f9;
        color: #475569;
    }

    .rank-3 {
        background: #fce7f3;
        color: #9d174d;
    }

    /* ── Badges ────────────────────────────────────────────── */
    .performance-badge {
        display: inline-flex;
        align-items: center;
        gap: 4px;
        padding: 3px 10px;
        border-radius: 20px;
        font-size: 11px;
        font-weight: 700;
        letter-spacing: .02em;
    }

    .badge-high {
        background: var(--success-light);
        color: #15803d;
    }

    .badge-medium {
        background: var(--warning-light);
        color: #92400e;
    }

    .badge-low {
        background: var(--danger-light);
        color: #b91c1c;
    }

    .top-performer {
        color: #15803d;
        font-weight: 700;
    }

    .weak-performer {
        color: #b91c1c;
        font-weight: 700;
    }

    .subject-best {
        background: #fffbeb !important;
    }

    /* ── Loading / empty state ─────────────────────────────── */
    .rpt-empty {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 48px 20px;
        color: var(--secondary);
        text-align: center;
    }

    .rpt-empty i {
        font-size: 40px;
        margin-bottom: 12px;
        opacity: .35;
    }

    .rpt-empty p {
        font-size: 14px;
        margin: 0;
    }

    .rpt-spinner {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;
        padding: 32px;
        color: var(--primary);
        font-size: 14px;
        font-weight: 600;
    }

    .rpt-spinner::before {
        content: '';
        width: 22px;
        height: 22px;
        border: 3px solid var(--primary-light);
        border-top-color: var(--primary);
        border-radius: 50%;
        animation: spin .7s linear infinite;
    }

    @keyframes spin {
        to {
            transform: rotate(360deg);
        }
    }

    /* keep legacy .loading working */
    .loading {
        display: none;
    }

    /* ── Error banner ──────────────────────────────────────── */
    .error {
        display: flex;
        align-items: center;
        gap: 10px;
        color: #b91c1c;
        padding: 12px 16px;
        background: var(--danger-light);
        border: 1px solid #fca5a5;
        border-radius: var(--radius-sm);
        margin-bottom: 16px;
        font-size: 13px;
        font-weight: 600;
    }

    .error::before {
        content: '\f071';
        font-family: 'Font Awesome 5 Free';
        font-weight: 900;
    }

    /* ── Section sub-title ─────────────────────────────────── */
    .rpt-section-title {
        font-size: 14px;
        font-weight: 700;
        color: var(--dark);
        margin: 24px 0 12px;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .rpt-section-title::after {
        content: '';
        flex: 1;
        height: 1px;
        background: var(--border);
    }

    /* ── Responsive ────────────────────────────────────────── */
    @media (max-width: 768px) {
        .stats-grid {
            grid-template-columns: repeat(2, 1fr);
        }

        .section-header {
            flex-direction: column;
            align-items: flex-start;
            gap: 10px;
        }

        .rpt-tabs {
            gap: 4px;
        }

        .rpt-tab {
            padding: 7px 12px;
            font-size: 12px;
        }
    }

    @media (max-width: 480px) {
        .stats-grid {
            grid-template-columns: 1fr;
        }
    }
</style>

<body class="hold-transition sidebar-mini layout-fixed">
    <div class="wrapper">
        <!-- Navbar -->
        <?php @include("includes/header.php"); ?>
        <!-- /.navbar -->

        <!-- Main Sidebar Container -->
        <?php @include("includes/sidebar.php"); ?>

        <!-- Content Wrapper. Contains page content -->
        <div class="content-wrapper">
            <!-- Content Header (Page header) -->
            <section class="content-header premium-header">
                <div class="container-fluid">
                    <div class="header-glass-card">
                        <div class="row align-items-center">
                            <div class="col-md-8">
                                <div class="title-section">
                                    <div class="icon-box bg-primary-gradient shadow-sm">
                                        <i class="fas fa-user-graduate"></i>
                                    </div>
                                    <div>
                                        <h1 class="premium-title text-primary">
                                            Student Performance Report
                                            <span class="premium-subtitle text-secondary">Performance • Ranking </span>
                                        </h1>
                                        <div class="mt-1">
                                            <?php if ($currentSessionName): ?>
                                                <span class="badge badge-primary mr-1">
                                                    <i class="fas fa-calendar-alt"></i>
                                                    <?= htmlspecialchars($currentSessionName) ?>
                                                </span>
                                            <?php endif; ?>
                                            <?php if ($currentTermName): ?>
                                                <span class="badge badge-success">
                                                    <i class="fas fa-bookmark"></i>
                                                    <?= htmlspecialchars($currentTermName) ?>
                                                </span>
                                            <?php else: ?>
                                                <span class="badge badge-warning">
                                                    <i class="fas fa-exclamation-triangle"></i> No active term
                                                </span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <nav aria-label="breadcrumb">
                                    <ol class="breadcrumb premium-breadcrumb">
                                        <li class="breadcrumb-item"><a href="dashboard.php"
                                                class="text-primary">Home</a></li>
                                        <li class="breadcrumb-item active" aria-current="page">Performance Reports</li>
                                    </ol>
                                </nav>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

            <section class="content">
                <div class="container-fluid">
                    <div class="card shadow-sm border-0">
                        <div class="card-header bg-primary text-white">
                            <h3 class="card-title font-weight-bold">
                                <i class="fas fa-filter"></i> Report Filters
                            </h3>
                            <div class="card-tools">
                            </div>
                        </div>
                        <div class="card-body">

                            <div class="rpt-filter-card">
                                <form id="report-filters" method="POST">
                                    <div class="row">
                                        <div class="form-group col-md-4">
                                            <label for="session"><i class="fas fa-calendar-alt mr-1"></i>Academic
                                                Session</label>
                                            <select id="session" name="session" required class="form-control">
                                                <option value="">Loading sessions...</option>
                                            </select>
                                        </div>
                                        <div class="form-group col-md-4">
                                            <label for="term"><i class="fas fa-bookmark mr-1"></i>Term</label>
                                            <select id="term" name="term" class="form-control">
                                                <option value="">--- Select term ---</option>
                                            </select>
                                        </div>
                                        <div class="form-group col-md-4">
                                            <label for="class"><i class="fas fa-school mr-1"></i>Class</label>
                                            <select id="class" name="class" class="form-control">
                                                <option value="">-- Select Class --</option>
                                                <option value="all">All Classes</option>
                                                <?php
                                                $classResult = $con->query("SELECT DISTINCT class FROM class_section ORDER BY class");
                                                while ($row = $classResult->fetch_assoc()) {
                                                    echo "<option value='{$row['class']}'>{$row['class']}</option>";
                                                }
                                                ?>
                                            </select>
                                        </div>
                                        <div class="form-group col-md-4">
                                            <label for="section"><i class="fas fa-layer-group mr-1"></i>Arm</label>
                                            <select id="section" name="section" class="form-control">
                                                <option value="">-- Select Arm --</option>
                                                <option value="all">All Arms</option>
                                                <?php
                                                $secResult = $con->query("SELECT DISTINCT section FROM class_section ORDER BY section");
                                                while ($rowsec = $secResult->fetch_assoc()) {
                                                    echo "<option value='{$rowsec['section']}'>{$rowsec['section']}</option>";
                                                }
                                                ?>
                                            </select>
                                        </div>
                                        <div class="form-group col-md-4">
                                            <label for="subject"><i class="fas fa-book mr-1"></i>Subject</label>
                                            <select id="subject" name="subject" class="form-control">
                                                <option value="all">All Subjects</option>
                                                <?php
                                                $query = "SELECT name FROM subject_name ORDER BY name DESC";
                                                $stmt1 = $con->prepare($query);
                                                $stmt1->execute();
                                                $result1 = $stmt1->get_result();
                                                while ($row1 = $result1->fetch_assoc()) {
                                                    echo "<option value='{$row1['name']}'>{$row1['name']}</option>";
                                                }
                                                ?>
                                            </select>
                                        </div>
                                        <div class="form-group col-md-12 text-center mt-2">
                                            <button type="submit" id="generate-btn" class="btn-generate">
                                                <i class="fas fa-chart-line"></i> Generate Report
                                            </button>
                                        </div>
                                    </div>
                                </form>
                            </div>

                            <div id="error-message" class="error" style="display: none;"></div>

                            <div class="rpt-tabs">
                                <div class="rpt-tab tab active" data-tab="overview"><i
                                        class="fas fa-tachometer-alt"></i> Overview</div>
                                <div class="rpt-tab tab" data-tab="class-performance"><i class="fas fa-users"></i> Class
                                    Performance</div>
                                <div class="rpt-tab tab" data-tab="class-performance-overall"><i
                                        class="fas fa-layer-group"></i> Overall Class</div>
                                <div class="rpt-tab tab" data-tab="class-performance-top3"><i class="fas fa-medal"></i>
                                    Top 3 Per Class</div>
                                <div class="rpt-tab tab" data-tab="subject-performance"><i class="fas fa-book-open"></i>
                                    Subjects</div>
                                <div class="rpt-tab tab" data-tab="weak-students"><i
                                        class="fas fa-exclamation-circle"></i> Weak Students</div>
                                <div class="rpt-tab tab" data-tab="results"><i class="fas fa-list-ol"></i> Results</div>
                                <div class="rpt-tab tab" data-tab="ai-insights"><i class="fas fa-robot"></i> AI Insights
                                </div>
                            </div>


                            <div class="tab-content active" id="overview">
                                <div class="report-section">
                                    <div class="section-header">
                                        <h5><i class="fas fa-tachometer-alt mr-2 text-primary"></i>Overall Performance
                                            Summary</h5>
                                        <button class="btn-download" onclick="downloadPDF('overview')"><i
                                                class="fas fa-download"></i> Download Overview</button>
                                    </div>

                                    <div id="overview-stats" class="stats-grid">
                                        <div class="rpt-empty" style="grid-column:1/-1">
                                            <i class="fas fa-chart-bar"></i>
                                            <p>Select filters above and generate a report to view data</p>
                                        </div>
                                    </div>

                                    <div class="rpt-section-title"><i class="fas fa-trophy text-warning"></i> Top 10
                                        Students Overall</div>
                                    <div class="rpt-table-wrap">
                                        <table id="overall-table">
                                            <thead>
                                                <tr>
                                                    <th>Rank</th>
                                                    <th>Admission No</th>
                                                    <th>Student Name</th>
                                                    <th>Class</th>
                                                    <th>Arm</th>
                                                    <th>Average (%)</th>
                                                    <th>Performance</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <tr>
                                                    <td colspan="7">
                                                        <div class="rpt-empty"><i class="fas fa-inbox"></i>
                                                            <p>No data available. Please generate a report.</p>
                                                        </div>
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>

                            <div class="tab-content" id="class-performance-overall">
                                <div class="report-section">
                                    <div class="section-header">
                                        <h5><i class="fas fa-layer-group mr-2 text-primary"></i>Overall Class
                                            Performance Ranking</h5>
                                        <button class="btn-download"
                                            onclick="downloadPDF('class-performance-overall')"><i
                                                class="fas fa-download"></i> Download</button>
                                    </div>
                                    <div id="class-performance-overall-content">
                                        <div class="rpt-empty"><i class="fas fa-chart-bar"></i>
                                            <p>Select filters and generate report to view data</p>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="tab-content" id="class-performance-top3">
                                <div class="report-section">
                                    <div class="section-header">
                                        <h5><i class="fas fa-medal mr-2 text-warning"></i>Overall Class Performance —
                                            Top 3</h5>
                                        <button class="btn-download" onclick="downloadPDF('class-performance-top3')"><i
                                                class="fas fa-download"></i> Download</button>
                                    </div>
                                    <div id="class-performance-top3-content">
                                        <div class="rpt-empty"><i class="fas fa-chart-bar"></i>
                                            <p>Select filters and generate report to view data</p>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="tab-content" id="class-performance">
                                <div class="report-section">
                                    <div class="section-header">
                                        <h5><i class="fas fa-users mr-2 text-primary"></i>Class Performance Ranking</h5>
                                        <button class="btn-download" onclick="downloadPDF('class-performance')"><i
                                                class="fas fa-download"></i> Download</button>
                                    </div>
                                    <div id="class-performance-content">
                                        <div class="rpt-empty"><i class="fas fa-chart-bar"></i>
                                            <p>Select filters and generate report to view data</p>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="tab-content" id="subject-performance">
                                <div class="report-section">
                                    <div class="section-header">
                                        <h5><i class="fas fa-book-open mr-2 text-info"></i>Subject Performance</h5>
                                        <button class="btn-download" onclick="downloadPDF('subject-performance')"><i
                                                class="fas fa-download"></i> Download</button>
                                    </div>
                                    <div id="subject-performance-content">
                                        <div class="rpt-empty"><i class="fas fa-chart-bar"></i>
                                            <p>Select filters and generate report to view data</p>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="tab-content" id="weak-students">
                                <div class="report-section">
                                    <div class="section-header">
                                        <h5><i class="fas fa-exclamation-circle mr-2 text-danger"></i>Students Needing
                                            Improvement</h5>
                                        <button class="btn-download" onclick="downloadPDF('weak-students')"><i
                                                class="fas fa-download"></i> Download</button>
                                    </div>
                                    <div id="weak-students-content">
                                        <div class="rpt-empty"><i class="fas fa-chart-bar"></i>
                                            <p>Select filters and generate report to view data</p>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="tab-content" id="results">
                                <div class="report-section">
                                    <div class="section-header">
                                        <h5><i class="fas fa-list-ol mr-2 text-primary"></i>Student Results Summary</h5>
                                        <button class="btn-download" onclick="downloadPDF('results')"><i
                                                class="fas fa-download"></i> Download</button>
                                    </div>
                                    <div id="results-content">
                                        <div class="rpt-empty"><i class="fas fa-chart-bar"></i>
                                            <p>Select filters and generate report to view results</p>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- AI Insights Tab -->
                            <div class="tab-content" id="ai-insights">
                                <div class="report-section">
                                    <div class="section-header">
                                        <h5><i class="fas fa-robot mr-2" style="color:var(--purple)"></i>AI Performance
                                            Insights</h5>
                                        <button class="btn-download" onclick="downloadAIPDF()"><i
                                                class="fas fa-download"></i> Download AI Report</button>
                                    </div>
                                    <div id="ai-error-message" class="error" style="display:none;"></div>
                                    <div id="ai-loading" class="rpt-spinner" style="display:none;">Generating AI
                                        insights, please wait…</div>

                                    <div id="ai-school-insights" style="margin-bottom:25px;">
                                        <div class="rpt-empty"><i class="fas fa-robot"></i>
                                            <p>Select filters and generate report to view AI insights</p>
                                        </div>
                                    </div>
                                    <div id="ai-rankings-section" style="margin-bottom:25px;"></div>
                                    <div id="ai-at-risk-section" style="margin-bottom:25px;"></div>
                                    <div id="ai-class-insights-section" style="margin-bottom:25px;"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </div>

        <?php @include("includes/foot.php"); ?>
        <?php @include("includes/footer.php"); ?>
    </div>
    <script>
        $(document).ready(function () {
            // Apply Select2 to ALL select elements
            $('select').select2({
            });
        });
    </script>

    <script>
        // Global variables to store report data
        let reportData = {};
        let aiReportData = {};

        // Tab functionality
        document.querySelectorAll('.tab').forEach(tab => {
            tab.addEventListener('click', () => {
                // Remove active class from all tabs and contents
                document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
                document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));

                // Add active class to clicked tab and corresponding content
                tab.classList.add('active');
                document.getElementById(tab.dataset.tab).classList.add('active');
            });
        });

        // Load sessions and terms on page load
        document.addEventListener('DOMContentLoaded', function () {
            loadSessions();
            loadTerms();
            // Clear any stale AI error from previous session
            const aiErr = document.getElementById('ai-error-message');
            if (aiErr) aiErr.style.display = 'none';
        });

        // Function to load sessions from database
        function loadSessions() {
            fetch('api/load_sessions.php')
                .then(response => response.json())
                .then(data => {
                    const sessionSelect = document.getElementById('session');
                    sessionSelect.innerHTML = '<option value="">Select session...</option>';

                    data.forEach(session => {
                        const option = document.createElement('option');
                        option.value = session.id;
                        option.textContent = session.session_name;
                        sessionSelect.appendChild(option);
                    });
                })
                .catch(error => {
                    console.error('Error loading sessions:', error);
                    document.getElementById('session').innerHTML = '<option value="">Error loading sessions</option>';
                });
        }

        // Function to load terms from database
        function loadTerms() {
            fetch('api/load_terms.php')
                .then(response => response.json())
                .then(data => {
                    const termSelect = document.getElementById('term');
                    termSelect.innerHTML = '<option value="">Select term...</option>';

                    data.forEach(term => {
                        const option = document.createElement('option');
                        option.value = term.id;
                        option.textContent = term.term_name;
                        termSelect.appendChild(option);
                    });
                })
                .catch(error => {
                    console.error('Error loading terms:', error);
                    document.getElementById('term').innerHTML = '<option value="">Error loading terms</option>';
                });
        }

        // Form submission handler
        document.getElementById('report-filters').addEventListener('submit', function (e) {
            e.preventDefault();

            const formData = new FormData(this);

            // Show loading state
            document.querySelectorAll('[id$="-content"]').forEach(el => {
                el.innerHTML = '<div class="rpt-spinner">Loading data, please wait…</div>';
            });
            document.getElementById('overview-stats').innerHTML = '<div class="rpt-spinner" style="grid-column:1/-1">Loading…</div>';

            document.getElementById('error-message').style.display = 'none';

            // Send request to server
            fetch('api/generate_report.php', {
                method: 'POST',
                body: formData
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        reportData = data.data;
                        displayReports(data.data);
                    } else {
                        throw new Error(data.message || 'Error generating report');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    const errorDiv = document.getElementById('error-message');
                    errorDiv.textContent = error.message;
                    errorDiv.style.display = 'block';
                });

            // Fire AI report in parallel
            const aiLoading = document.getElementById('ai-loading');
            const aiError = document.getElementById('ai-error-message');
            aiLoading.style.display = 'block';
            aiError.style.display = 'none';
            document.getElementById('ai-school-insights').innerHTML = '';
            document.getElementById('ai-rankings-section').innerHTML = '';
            document.getElementById('ai-at-risk-section').innerHTML = '';
            document.getElementById('ai-class-insights-section').innerHTML = '';

            fetch('api/generate_ai_report.php', {
                method: 'POST',
                body: new FormData(document.getElementById('report-filters')),
                signal: AbortSignal.timeout(120000) // 2 minute timeout
            })
                .then(response => {
                    const clone = response.clone();
                    return response.json().catch(() =>
                        clone.text().then(text => {
                            console.error('AI report raw response (not JSON):', text);
                            // Try to extract data from partial output if rankings are present
                            return { success: false, message: 'Server error. Check browser console.', _raw: text };
                        })
                    );
                })
                .then(aiData => {
                    aiLoading.style.display = 'none';
                    aiError.style.display = 'none';
                    const d = aiData.data || {};
                    // Always render whatever data came back
                    if (d.rankings && d.rankings.length > 0) {
                        aiReportData = d;
                        displaySchoolInsights(d.schoolInsights);
                        displayAIRankings(d.rankings);
                        displayAtRiskStudents(d.atRiskStudents);
                        displayClassInsights(d.classInsights);
                    } else if (!aiData.success) {
                        // Truly failed — no data at all
                        aiError.textContent = aiData.message || 'Error generating AI insights.';
                        aiError.style.display = 'block';
                    }
                })
                .catch(err => {
                    aiLoading.style.display = 'none';
                    // Don't show error if data already rendered
                    if (!aiReportData || !aiReportData.rankings || aiReportData.rankings.length === 0) {
                        aiError.textContent = 'Could not load AI insights. Please try again.';
                        aiError.style.display = 'block';
                    }
                    console.error('AI report error:', err);
                });
        });

        // Function to display reports
        function displayReports(data) {
            displayOverview(data.overview);
            displayClassPerformance(data.classPerformance);
            displayClassPerformanceOverall(data.classPerformanceOverall); // <-- add this
            displayClassPerformanceTop3(data.classPerformanceTop3);
            displaySubjectPerformance(data.subjectPerformance);
            displayWeakStudents(data.weakStudents);
            displayStudentResults(data.studentResults);
        }


        // Function to display overview data
        function displayOverview(data) {
            const statsGrid = document.getElementById('overview-stats');
            statsGrid.innerHTML = '';

            // Create stat cards
            const stats = [
                { title: 'Total Students', value: data.totalStudents, desc: 'All enrolled classes', icon: 'fas fa-users', accent: '#4a6fdc', bg: '#eef2ff' },
                { title: 'Overall Average', value: data.overallAverage + '%', desc: 'School-wide performance', icon: 'fas fa-chart-line', accent: '#06b6d4', bg: '#cffafe' },
                { title: 'Top Class', value: data.topClass, desc: 'Avg: ' + data.topClassAverage + '%', icon: 'fas fa-school', accent: '#22c55e', bg: '#dcfce7' },
                { title: 'Top Subject', value: data.bestSubject, desc: 'Avg: ' + data.bestSubjectAverage + '%', icon: 'fas fa-book-open', accent: '#8b5cf6', bg: '#ede9fe' },
                { title: 'Weakest Class', value: data.worstClass, desc: 'Avg: ' + data.worstClassAverage + '%', icon: 'fas fa-exclamation-triangle', accent: '#ef4444', bg: '#fee2e2' },
                { title: 'Weakest Subject', value: data.worstSubject, desc: 'Avg: ' + data.worstSubjectAverage + '%', icon: 'fas fa-book', accent: '#f59e0b', bg: '#fef3c7' }
            ];

            stats.forEach(stat => {
                const card = document.createElement('div');
                card.className = 'stat-card';
                card.style.setProperty('--card-accent', stat.accent);
                card.innerHTML = `
                    <div class="stat-icon" style="background:${stat.bg};color:${stat.accent}">
                        <i class="${stat.icon}"></i>
                    </div>
                    <h5>${stat.title}</h5>
                    <div class="stat-value" style="color:${stat.accent}">${stat.value}</div>
                    <p>${stat.desc}</p>
                `;
                statsGrid.appendChild(card);
            });

            // Display top students table
            const tableBody = document.querySelector('#overall-table tbody');
            tableBody.innerHTML = '';

            if (data.topStudents && data.topStudents.length > 0) {
                data.topStudents.forEach((student, index) => {
                    const row = document.createElement('tr');
                    if (index < 3) row.className = 'highlight';

                    const rank = index + 1;
                    const medalClass = rank === 1 ? 'rank-1' : rank === 2 ? 'rank-2' : rank === 3 ? 'rank-3' : '';
                    const rankHtml = medalClass
                        ? `<span class="rank-medal ${medalClass}">${rank}</span>`
                        : rank;
                    row.innerHTML = `
                        <td>${rankHtml}</td>
                        <td>${student.studentno}</td>
                        <td><strong>${student.studentName}</strong></td>
                        <td>${student.class}</td>
                        <td>${student.section}</td>
                        <td class="top-performer">${student.average_score}%</td>
                        <td><span class="performance-badge badge-high"><i class="fas fa-star"></i> Excellent</span></td>
                    `;
                    tableBody.appendChild(row);
                });
            } else {
                tableBody.innerHTML = '<tr><td colspan="7"><div class="rpt-empty"><i class="fas fa-inbox"></i><p>No data available</p></div></td></tr>';
            }
        }

        // Function to display class performance data WITH STATISTICS
        function displayClassPerformance(data) {
            const contentDiv = document.getElementById('class-performance-content');
            contentDiv.innerHTML = '';

            if (data && data.length > 0) {
                data.forEach(classData => {
                    const classTitle = document.createElement('div');
                    classTitle.className = 'rpt-section-title';
                    classTitle.innerHTML = `<i class="fas fa-users text-primary"></i> ${classData.class} — ${classData.section} Arm`;
                    contentDiv.appendChild(classTitle);

                    const totalStudents = classData.students.length;
                    const classAverage = totalStudents > 0 ? classData.students.reduce((s, st) => s + parseFloat(st.average_score), 0) / totalStudents : 0;
                    const topStudent = totalStudents > 0 ? classData.students[0] : null;
                    const passRate = totalStudents > 0 ? (classData.students.filter(s => parseFloat(s.average_score) >= 50).length / totalStudents * 100).toFixed(1) : 0;

                    const statsDiv = document.createElement('div');
                    statsDiv.className = 'stats-grid';
                    statsDiv.style.marginBottom = '16px';
                    statsDiv.innerHTML = `
                        <div class="stat-card" style="--card-accent:#4a6fdc"><div class="stat-icon" style="background:#eef2ff;color:#4a6fdc"><i class="fas fa-users"></i></div><h5>Total Students</h5><div class="stat-value" style="color:#4a6fdc">${totalStudents}</div><p>In this class-arm</p></div>
                        <div class="stat-card" style="--card-accent:#06b6d4"><div class="stat-icon" style="background:#cffafe;color:#06b6d4"><i class="fas fa-chart-line"></i></div><h5>Class Average</h5><div class="stat-value" style="color:#06b6d4">${classAverage.toFixed(2)}%</div><p>Overall performance</p></div>
                        <div class="stat-card" style="--card-accent:#22c55e"><div class="stat-icon" style="background:#dcfce7;color:#22c55e"><i class="fas fa-check-circle"></i></div><h5>Pass Rate</h5><div class="stat-value" style="color:#22c55e">${passRate}%</div><p>Students with ≥50%</p></div>
                        <div class="stat-card" style="--card-accent:#f59e0b"><div class="stat-icon" style="background:#fef3c7;color:#f59e0b"><i class="fas fa-trophy"></i></div><h5>Top Student</h5><div class="stat-value" style="color:#f59e0b">${topStudent ? topStudent.average_score + '%' : 'N/A'}</div><p>${topStudent ? topStudent.studentName : 'No data'}</p></div>
                    `;
                    contentDiv.appendChild(statsDiv);

                    const wrap = document.createElement('div');
                    wrap.className = 'rpt-table-wrap';
                    const table = document.createElement('table');
                    table.innerHTML = `<thead><tr><th>Rank</th><th>Admission No</th><th>Student Name</th><th>Average (%)</th><th>Position</th><th>Status</th></tr></thead><tbody></tbody>`;
                    const tbody = table.querySelector('tbody');

                    if (classData.students && classData.students.length > 0) {
                        classData.students.forEach((student, index) => {
                            const row = document.createElement('tr');
                            if (index < 3) row.className = 'highlight';
                            const rank = index + 1;
                            const medalClass = rank <= 3 ? `rank-${rank}` : '';
                            row.innerHTML = `
                                <td>${medalClass ? `<span class="rank-medal ${medalClass}">${rank}</span>` : rank}</td>
                                <td>${student.studentno}</td>
                                <td><strong>${student.studentName}</strong></td>
                                <td class="${parseFloat(student.average_score) >= 80 ? 'top-performer' : parseFloat(student.average_score) < 40 ? 'weak-performer' : ''}">${student.average_score}%</td>
                                <td>${rank}${getOrdinalSuffix(rank)}</td>
                                <td>${parseFloat(student.average_score) >= 50 ? '<span class="performance-badge badge-high"><i class="fas fa-check"></i> Promoted</span>' : '<span class="performance-badge badge-low"><i class="fas fa-clock"></i> Review</span>'}</td>
                            `;
                            tbody.appendChild(row);
                        });
                    } else {
                        tbody.innerHTML = '<tr><td colspan="6"><div class="rpt-empty"><i class="fas fa-inbox"></i><p>No students found</p></div></td></tr>';
                    }
                    wrap.appendChild(table);
                    contentDiv.appendChild(wrap);
                });
            } else {
                contentDiv.innerHTML = '<div class="rpt-empty"><i class="fas fa-chart-bar"></i><p>No class performance data available</p></div>';
            }
        }           // Function to display overall class performance WITH STATISTICS
        function displayClassPerformanceOverall(data) {
            const contentDiv = document.getElementById('class-performance-overall-content');
            contentDiv.innerHTML = '';

            if (data && data.length > 0) {
                data.forEach(classData => {
                    const classTitle = document.createElement('div');
                    classTitle.className = 'rpt-section-title';
                    classTitle.innerHTML = `<i class="fas fa-layer-group text-primary"></i> ${classData.class} — All Arms`;
                    contentDiv.appendChild(classTitle);

                    const totalStudents = classData.students.length;
                    const classAverage = totalStudents > 0 ? classData.students.reduce((s, st) => s + parseFloat(st.average_score), 0) / totalStudents : 0;
                    const topStudent = totalStudents > 0 ? classData.students[0] : null;
                    const passRate = totalStudents > 0 ? (classData.students.filter(s => parseFloat(s.average_score) >= 50).length / totalStudents * 100).toFixed(1) : 0;

                    const statsDiv = document.createElement('div');
                    statsDiv.className = 'stats-grid';
                    statsDiv.style.marginBottom = '16px';
                    statsDiv.innerHTML = `
                        <div class="stat-card" style="--card-accent:#4a6fdc"><div class="stat-icon" style="background:#eef2ff;color:#4a6fdc"><i class="fas fa-users"></i></div><h5>Total Students</h5><div class="stat-value" style="color:#4a6fdc">${totalStudents}</div><p>All arms combined</p></div>
                        <div class="stat-card" style="--card-accent:#06b6d4"><div class="stat-icon" style="background:#cffafe;color:#06b6d4"><i class="fas fa-chart-line"></i></div><h5>Class Average</h5><div class="stat-value" style="color:#06b6d4">${classAverage.toFixed(2)}%</div><p>Overall performance</p></div>
                        <div class="stat-card" style="--card-accent:#22c55e"><div class="stat-icon" style="background:#dcfce7;color:#22c55e"><i class="fas fa-check-circle"></i></div><h5>Pass Rate</h5><div class="stat-value" style="color:#22c55e">${passRate}%</div><p>Students with ≥50%</p></div>
                        <div class="stat-card" style="--card-accent:#f59e0b"><div class="stat-icon" style="background:#fef3c7;color:#f59e0b"><i class="fas fa-trophy"></i></div><h5>Top Student</h5><div class="stat-value" style="color:#f59e0b">${topStudent ? topStudent.average_score + '%' : 'N/A'}</div><p>${topStudent ? topStudent.studentName : 'No data'}</p></div>
                    `;
                    contentDiv.appendChild(statsDiv);

                    const wrap = document.createElement('div');
                    wrap.className = 'rpt-table-wrap';
                    const table = document.createElement('table');
                    table.innerHTML = `<thead><tr><th>Rank</th><th>Admission No</th><th>Student Name</th><th>Arm</th><th>Average (%)</th><th>Position</th><th>Status</th></tr></thead><tbody></tbody>`;
                    const tbody = table.querySelector('tbody');

                    if (classData.students && classData.students.length > 0) {
                        classData.students.forEach((student, index) => {
                            const row = document.createElement('tr');
                            if (index < 3) row.className = 'highlight';
                            const rank = index + 1;
                            const medalClass = rank <= 3 ? `rank-${rank}` : '';
                            row.innerHTML = `
                                <td>${medalClass ? `<span class="rank-medal ${medalClass}">${rank}</span>` : rank}</td>
                                <td>${student.studentno}</td>
                                <td><strong>${student.studentName}</strong></td>
                                <td>${student.section}</td>
                                <td class="${parseFloat(student.average_score) >= 80 ? 'top-performer' : parseFloat(student.average_score) < 40 ? 'weak-performer' : ''}">${student.average_score}%</td>
                                <td>${rank}${getOrdinalSuffix(rank)}</td>
                                <td>${parseFloat(student.average_score) >= 50 ? '<span class="performance-badge badge-high"><i class="fas fa-check"></i> Promoted</span>' : '<span class="performance-badge badge-low"><i class="fas fa-clock"></i> Review</span>'}</td>
                            `;
                            tbody.appendChild(row);
                        });
                    } else {
                        tbody.innerHTML = '<tr><td colspan="7"><div class="rpt-empty"><i class="fas fa-inbox"></i><p>No students found</p></div></td></tr>';
                    }
                    wrap.appendChild(table);
                    contentDiv.appendChild(wrap);
                });
            } else {
                contentDiv.innerHTML = '<div class="rpt-empty"><i class="fas fa-chart-bar"></i><p>No overall class performance data available</p></div>';
            }
        }           // Function to display top 3 students per class (all arms combined)
        function displayClassPerformanceTop3(data) {
            const contentDiv = document.getElementById('class-performance-top3-content');
            contentDiv.innerHTML = '';

            if (data && data.length > 0) {
                data.forEach(classData => {
                    const classTitle = document.createElement('div');
                    classTitle.className = 'rpt-section-title';
                    classTitle.innerHTML = `<i class="fas fa-medal text-warning"></i> ${classData.class} — Top 3 Students (All Arms)`;
                    contentDiv.appendChild(classTitle);

                    const wrap = document.createElement('div');
                    wrap.className = 'rpt-table-wrap';
                    const table = document.createElement('table');
                    table.innerHTML = `<thead><tr><th>Rank</th><th>Admission No</th><th>Student Name</th><th>Arm</th><th>Average (%)</th><th>Position</th></tr></thead><tbody></tbody>`;
                    const tbody = table.querySelector('tbody');

                    if (classData.students && classData.students.length > 0) {
                        classData.students.forEach((student, index) => {
                            const row = document.createElement('tr');
                            row.className = 'highlight';
                            const rank = index + 1;
                            row.innerHTML = `
                                <td><span class="rank-medal rank-${rank}">${rank}</span></td>
                                <td>${student.studentno}</td>
                                <td><strong>${student.studentName}</strong></td>
                                <td>${student.section}</td>
                                <td class="top-performer">${student.average_score}%</td>
                                <td>${rank}${getOrdinalSuffix(rank)}</td>
                            `;
                            tbody.appendChild(row);
                        });
                    } else {
                        tbody.innerHTML = '<tr><td colspan="6"><div class="rpt-empty"><i class="fas fa-inbox"></i><p>No students found</p></div></td></tr>';
                    }
                    wrap.appendChild(table);
                    contentDiv.appendChild(wrap);
                });
            } else {
                contentDiv.innerHTML = '<div class="rpt-empty"><i class="fas fa-chart-bar"></i><p>No top 3 class data available</p></div>';
            }
        }

        // Function to display subject performance data WITH STATISTICS
        function displaySubjectPerformance(data) {
            const contentDiv = document.getElementById('subject-performance-content');
            contentDiv.innerHTML = '';

            if (data && data.length > 0) {
                // First, show overall subject statistics
                const overallStatsDiv = document.createElement('div');
                overallStatsDiv.className = 'stats-grid';
                overallStatsDiv.style.marginBottom = '30px';

                // Calculate overall subject statistics
                const totalSubjects = data.length;
                const subjectAverages = data.map(subject =>
                    subject.topPerformers.reduce((sum, perf) => sum + parseFloat(perf.score), 0) / subject.topPerformers.length
                );
                const overallSubjectAverage = subjectAverages.reduce((sum, avg) => sum + avg, 0) / totalSubjects;
                const bestSubject = data.reduce((best, current) => {
                    const currentAvg = current.topPerformers.reduce((sum, perf) => sum + parseFloat(perf.score), 0) / current.topPerformers.length;
                    const bestAvg = best.topPerformers.reduce((sum, perf) => sum + parseFloat(perf.score), 0) / best.topPerformers.length;
                    return currentAvg > bestAvg ? current : best;
                }, data[0]);

                overallStatsDiv.innerHTML = `
            <div class="stat-card">
                <h5>Total Subjects</h5>
                <div class="stat-value">${totalSubjects}</div>
                <p>Subjects analyzed</p>
            </div>
            <div class="stat-card">
                <h5>Overall Subject Average</h5>
                <div class="stat-value">${overallSubjectAverage.toFixed(2)}%</div>
                <p>Across all subjects</p>
            </div>
            <div class="stat-card">
                <h5>Best Subject</h5>
                <div class="stat-value">${bestSubject.subject}</div>
                <p>${bestSubject.topPerformers.length > 0 ?
                        'Avg: ' + (bestSubject.topPerformers.reduce((sum, perf) => sum + parseFloat(perf.score), 0) / bestSubject.topPerformers.length).toFixed(2) + '%' :
                        'No data'}</p>
            </div>
            <div class="stat-card">
                <h5>Top Performers</h5>
                <div class="stat-value">${data.reduce((sum, subject) => sum + subject.topPerformers.length, 0)}</div>
                <p>Total students recognized</p>
            </div>
        `;

                contentDiv.appendChild(overallStatsDiv);

                // Then show each subject's details
                data.forEach(subjectData => {
                    const subjectTitle = document.createElement('h5');
                    subjectTitle.textContent = `${subjectData.subject} - Top Performers by Class`;
                    contentDiv.appendChild(subjectTitle);

                    // Add subject-specific statistics
                    const subjectStatsDiv = document.createElement('div');
                    subjectStatsDiv.className = 'stats-grid';
                    subjectStatsDiv.style.marginBottom = '15px';

                    const subjectAvg = subjectData.topPerformers.length > 0 ?
                        subjectData.topPerformers.reduce((sum, perf) => sum + parseFloat(perf.score), 0) / subjectData.topPerformers.length : 0;
                    const uniqueClasses = [...new Set(subjectData.topPerformers.map(p => p.class))].length;
                    const topPerformer = subjectData.topPerformers.length > 0 ?
                        subjectData.topPerformers.reduce((best, current) =>
                            parseFloat(current.score) > parseFloat(best.score) ? current : best
                        ) : null;

                    subjectStatsDiv.innerHTML = `
                <div class="stat-card">
                    <h5>Subject Average</h5>
                    <div class="stat-value">${subjectAvg.toFixed(2)}%</div>
                    <p>Among top performers</p>
                </div>
                <div class="stat-card">
                    <h5>Classes Represented</h5>
                    <div class="stat-value">${uniqueClasses}</div>
                    <p>Number of classes</p>
                </div>
                <div class="stat-card">
                    <h5>Top Performer</h5>
                    <div class="stat-value">${topPerformer ? topPerformer.score + '%' : 'N/A'}</div>
                    <p>${topPerformer ? topPerformer.studentName : 'No data'}</p>
                </div>
                <div class="stat-card">
                    <h5>Total Awardees</h5>
                    <div class="stat-value">${subjectData.topPerformers.length}</div>
                    <p>Number of students</p>
                </div>
            `;

                    contentDiv.appendChild(subjectStatsDiv);

                    const table = document.createElement('table');
                    table.innerHTML = `
                <thead>
                    <tr>
                        <th>Class</th>
                        <th>Admission No</th>
                        <th>Student Name</th>
                        <th>Average (%)</th>
                        <th>Award</th>
                    </tr>
                </thead>
                <tbody></tbody>
            `;

                    const tbody = table.querySelector('tbody');

                    if (subjectData.topPerformers && subjectData.topPerformers.length > 0) {
                        subjectData.topPerformers.forEach(performer => {
                            const row = document.createElement('tr');
                            row.className = 'subject-best';
                            row.innerHTML = `
                        <td>${performer.class}</td>
                        <td>${performer.studentno}</td>
                        <td><strong>${performer.studentName}</strong></td>
                        <td class="top-performer">${performer.score}%</td>
                        <td><span class="performance-badge badge-high"><i class="fas fa-star"></i> Best in ${subjectData.subject}</span></td>
                    `;
                            tbody.appendChild(row);
                        });
                    } else {
                        tbody.innerHTML = '<tr><td colspan="5"><div class="rpt-empty"><i class="fas fa-inbox"></i><p>No top performers found</p></div></td></tr>';
                    }

                    contentDiv.appendChild(table);
                });
            } else {
                contentDiv.innerHTML = '<div class="rpt-empty"><i class="fas fa-book-open"></i><p>No subject performance data available</p></div>';
            }
        }

        // Function to display weak students data WITH STATISTICS
        function displayWeakStudents(data) {
            const contentDiv = document.getElementById('weak-students-content');
            contentDiv.innerHTML = '';

            if (data && data.length > 0) {
                // Overall weak students statistics
                const overallStatsDiv = document.createElement('div');
                overallStatsDiv.className = 'stats-grid';
                overallStatsDiv.style.marginBottom = '30px';
                const below50Count = data.filter(student => parseFloat(student.average_score) < 50).length;
                const below40Count = data.filter(student => parseFloat(student.average_score) < 40).length;
                const below30Count = data.filter(student => parseFloat(student.average_score) < 30).length;
                const totalWeakStudents = data.length;
                const avgWeakScore = totalWeakStudents > 0 ?
                    data.reduce((sum, student) => sum + parseFloat(student.average_score), 0) / totalWeakStudents : 0;

                overallStatsDiv.innerHTML = `
            <div class="stat-card">
                <h5>Total Weak Students</h5>
                <div class="stat-value">${totalWeakStudents}</div>
                <p>Students below 50%</p>
            </div>
            <div class="stat-card">
                <h5>Average Score</h5>
                <div class="stat-value">${avgWeakScore.toFixed(2)}%</div>
                <p>Among weak students</p>
            </div>
            <div class="stat-card">
                <h5>Critical Cases</h5>
                <div class="stat-value">${below30Count}</div>
                <p>Students below 30%</p>
            </div>
            <div class="stat-card">
                <h5>At Risk</h5>
                <div class="stat-value">${below40Count}</div>
                <p>Needs intervention</p>
            </div>
            <div class="stat-card">
                <h5>Under Monitoring</h5>
                <div class="stat-value">${below50Count}</div>
                <p>Needs Monitoring</p>
            </div>
            `;

                contentDiv.appendChild(overallStatsDiv);

                // Class-wise weak student distribution
                const classDistribution = {};
                data.forEach(student => {
                    const classKey = `${student.class} - ${student.section}`;
                    if (!classDistribution[classKey]) {
                        classDistribution[classKey] = {
                            class: student.class,
                            section: student.section,
                            count: 0,
                            totalScore: 0
                        };
                    }
                    classDistribution[classKey].count++;
                    classDistribution[classKey].totalScore += parseFloat(student.average_score);
                });

                // Show class distribution if we have multiple classes
                if (Object.keys(classDistribution).length > 1) {
                    const distributionTitle = document.createElement('h5');
                    distributionTitle.textContent = 'Weak Students by Class';
                    contentDiv.appendChild(distributionTitle);

                    const distributionTable = document.createElement('table');
                    distributionTable.innerHTML = `
                <thead>
                    <tr>
                        <th>Class</th>
                        <th>Arm</th>
                        <th>Weak Students</th>
                        <th>Average Score</th>
                        <th>% of Class</th>
                    </tr>
                </thead>
                <tbody></tbody>
            `;

                    const distTbody = distributionTable.querySelector('tbody');

                    Object.values(classDistribution).forEach(classData => {
                        const row = document.createElement('tr');
                        const classAvg = classData.totalScore / classData.count;

                        row.innerHTML = `
                    <td>${classData.class}</td>
                    <td>${classData.section}</td>
                    <td class="weak-performer">${classData.count}</td>
                    <td>${classAvg.toFixed(2)}%</td>
                    <td>${classData.count > 5 ? 'High' : classData.count > 2 ? 'Medium' : 'Low'}</td>
                `;
                        distTbody.appendChild(row);
                    });

                    contentDiv.appendChild(distributionTable);
                }

                // Students below 40%
                const below40Title = document.createElement('h5');
                below40Title.textContent = 'Students Below 50% Average';
                contentDiv.appendChild(below40Title);

                const below40Table = document.createElement('table');
                below40Table.innerHTML = `
            <thead>
                <tr>
                    <th>Admission No</th>
                    <th>Student Name</th>
                    <th>Class</th>
                    <th>Arm</th>
                    <th>Average (%)</th>
                    <th>Intervention Needed</th>
                </tr>
            </thead>
            <tbody></tbody>
        `;

                const below40Tbody = below40Table.querySelector('tbody');

                const below40Students = data.filter(student => parseFloat(student.average_score) < 50)
                    .sort((a, b) => parseFloat(a.average_score) - parseFloat(b.average_score));

                below40Students.forEach(student => {
                    const row = document.createElement('tr');

                    // Determine intervention level based on score
                    let intervention = '';
                    if (parseFloat(student.average_score) < 20) {
                        intervention = 'Immediate parent meeting + Extra classes';
                    } else if (parseFloat(student.average_score) < 30) {
                        intervention = 'Parent meeting + Extra classes';
                    } else if (parseFloat(student.average_score) < 40) {
                        intervention = 'Extra classes + Monitoring';
                    }
                    else {
                        intervention = 'Monitoring';
                    }

                    row.innerHTML = `
                <td>${student.studentno}</td>
                <td>${student.studentName}</td>
                <td>${student.class}</td>
                <td>${student.section}</td>
                <td class="weak-performer">${student.average_score}%</td>
                <td>${intervention}</td>
            `;
                    below40Tbody.appendChild(row);
                });

                if (below40Tbody.children.length === 0) {
                    below40Tbody.innerHTML = '<tr><td colspan="6"><div class="rpt-empty"><i class="fas fa-check-circle" style="color:#22c55e"></i><p>No students below 50% average</p></div></td></tr>';
                }

                contentDiv.appendChild(below40Table);




                // At-risk students (below 30%)
                if (below30Count > 0) {
                    const atRiskTitle = document.createElement('h5');
                    atRiskTitle.textContent = 'Critical Cases - Students Below 30% Average';
                    contentDiv.appendChild(atRiskTitle);

                    const atRiskTable = document.createElement('table');
                    atRiskTable.innerHTML = `
                <thead>
                    <tr>
                        <th>Admission No</th>
                        <th>Student Name</th>
                        <th>Class</th>
                        <th>Arm</th>
                        <th>Average (%)</th>
                        <th>Urgent Action Required</th>
                    </tr>
                </thead>
                <tbody></tbody>
            `;

                    const atRiskTbody = atRiskTable.querySelector('tbody');

                    const atRiskStudents = data.filter(student => parseFloat(student.average_score) < 30)
                        .sort((a, b) => parseFloat(a.average_score) - parseFloat(b.average_score));

                    atRiskStudents.forEach(student => {
                        const row = document.createElement('tr');
                        row.style.backgroundColor = '#ffebee';

                        row.innerHTML = `
                    <td><strong>${student.studentno}</strong></td>
                    <td><strong>${student.studentName}</strong></td>
                    <td>${student.class}</td>
                    <td>${student.section}</td>
                    <td class="weak-performer"><strong>${student.average_score}%</strong></td>
                    <td><strong>Immediate intervention required</strong></td>
                `;
                        atRiskTbody.appendChild(row);
                    });

                    contentDiv.appendChild(atRiskTable);
                }
            } else {
                contentDiv.innerHTML = '<div class="rpt-empty"><i class="fas fa-exclamation-circle"></i><p>No weak students data available</p></div>';
            }
        }
        // Function to display student results data
        function displayStudentResults(data) {
            const contentDiv = document.getElementById('results-content');
            contentDiv.innerHTML = '';

            if (data && data.length > 0) {
                // Group results by class
                const resultsByClass = {};

                data.forEach(student => {
                    const classKey = student.class + '|' + student.section;
                    if (!resultsByClass[classKey]) {
                        resultsByClass[classKey] = {
                            class: student.class,
                            section: student.section,
                            students: []
                        };
                    }
                    resultsByClass[classKey].students.push(student);
                });

                // Sort students within each class by percentage (descending)
                Object.keys(resultsByClass).forEach(key => {
                    resultsByClass[key].students.sort((a, b) => b.percentage - a.percentage);

                    // Assign positions
                    resultsByClass[key].students.forEach((student, index) => {
                        student.position = index + 1;
                    });
                });

                // Display each class results
                Object.keys(resultsByClass).forEach(key => {
                    const classData = resultsByClass[key];

                    const classTitle = document.createElement('div');
                    classTitle.className = 'rpt-section-title';
                    classTitle.innerHTML = `<i class="fas fa-list-ol text-primary"></i> ${classData.class} — ${classData.section} Arm`;
                    contentDiv.appendChild(classTitle);

                    const wrap = document.createElement('div');
                    wrap.className = 'rpt-table-wrap';
                    const table = document.createElement('table');
                    table.innerHTML = `
                        <thead>
                            <tr>
                                <th>Position</th>
                                <th>Student Name</th>
                                <th>Admission No</th>
                                <th>Total Obtainable</th>
                                <th>Total Obtained</th>
                                <th>% Obtained</th>
                                <th>Remark</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    `;

                    const tbody = table.querySelector('tbody');

                    classData.students.forEach((student) => {
                        const row = document.createElement('tr');

                        // Apply highlight to top 3 performers
                        if (student.position <= 3) row.className = 'highlight';

                        // Determine performance badge
                        let performanceBadge = '';
                        if (student.percentage >= 80) {
                            performanceBadge = '<span class="performance-badge badge-high"><i class="fas fa-star"></i> Excellent</span>';
                        } else if (student.percentage >= 60) {
                            performanceBadge = '<span class="performance-badge badge-medium"><i class="fas fa-thumbs-up"></i> Good</span>';
                        } else if (student.percentage >= 50) {
                            performanceBadge = '<span class="performance-badge badge-medium"><i class="fas fa-minus-circle"></i> Average</span>';
                        } else {
                            performanceBadge = '<span class="performance-badge badge-low"><i class="fas fa-exclamation-circle"></i> Needs Improvement</span>';
                        }

                        row.innerHTML = `
                            <td>${student.position}${getOrdinalSuffix(student.position)}</td>
                            <td><strong>${student.studentName}</strong></td>
                            <td>${student.studentno}</td>
                            <td>${student.total_obtainable}</td>
                            <td>${student.total_obtained}</td>
                            <td class="${student.percentage >= 80 ? 'top-performer' : student.percentage < 50 ? 'weak-performer' : ''}">
                                ${student.percentage.toFixed(2)}%
                            </td>
                            <td>${performanceBadge}</td>
                        `;

                        tbody.appendChild(row);
                    });

                    wrap.appendChild(table);
                    contentDiv.appendChild(wrap);

                    // Add class statistics
                    const statsDiv = document.createElement('div');
                    statsDiv.className = 'stats-grid';
                    statsDiv.style.marginBottom = '24px';

                    const totalStudents = classData.students.length;
                    const classAverage = classData.students.reduce((sum, student) => sum + student.percentage, 0) / totalStudents;
                    const passRate = (classData.students.filter(s => s.percentage >= 50).length / totalStudents * 100).toFixed(1);

                    statsDiv.innerHTML = `
                        <div class="stat-card" style="--card-accent:#4a6fdc"><div class="stat-icon" style="background:#eef2ff;color:#4a6fdc"><i class="fas fa-users"></i></div><h5>Total Students</h5><div class="stat-value" style="color:#4a6fdc">${totalStudents}</div><p>In class</p></div>
                        <div class="stat-card" style="--card-accent:#06b6d4"><div class="stat-icon" style="background:#cffafe;color:#06b6d4"><i class="fas fa-chart-line"></i></div><h5>Class Average</h5><div class="stat-value" style="color:#06b6d4">${classAverage.toFixed(2)}%</div><p>Overall performance</p></div>
                        <div class="stat-card" style="--card-accent:#22c55e"><div class="stat-icon" style="background:#dcfce7;color:#22c55e"><i class="fas fa-check-circle"></i></div><h5>Pass Rate</h5><div class="stat-value" style="color:#22c55e">${passRate}%</div><p>Students with ≥50%</p></div>
                        <div class="stat-card" style="--card-accent:#f59e0b"><div class="stat-icon" style="background:#fef3c7;color:#f59e0b"><i class="fas fa-trophy"></i></div><h5>Top Student</h5><div class="stat-value" style="color:#f59e0b">${classData.students[0].percentage.toFixed(2)}%</div><p>${classData.students[0].studentName}</p></div>
                    `;

                    contentDiv.appendChild(statsDiv);
                });
            } else {
                contentDiv.innerHTML = '<div class="rpt-empty"><i class="fas fa-list-ol"></i><p>No results data available</p></div>';
            }
        }

        // Helper function to get ordinal suffix
        function getOrdinalSuffix(num) {
            const j = num % 10, k = num % 100;
            if (j === 1 && k !== 11) return "st";
            if (j === 2 && k !== 12) return "nd";
            if (j === 3 && k !== 13) return "rd";
            return "th";
        }

        const schoolInfo = {
            name: "<?php echo strtoupper(addslashes($_ENV['SCHOOL_NAME_1'])); ?>",
            logo: "<?php echo addslashes($_ENV['WEBSITE_LOGO'] ?? ''); ?>",
            address: "<?php echo addslashes($_ENV['id_address'] ?? ''); ?>",
            email: "<?php echo addslashes($_ENV['SCHOOL_EMAIL'] ?? ''); ?>",
            signature: "<?php echo addslashes($_ENV['PRINCIPAL_SIGNATURE'] ?? ''); ?>",
            website: "<?php echo addslashes($_ENV['SCHOOL_WEBSITE'] ?? ''); ?>"
        };
        function addPDFHeader(doc) {
            let y = 15;

            // Add logo if available
            if (schoolInfo.logo) {
                doc.addImage(schoolInfo.logo, "PNG", 14, y - 5, 25, 25); // x, y, width, height
            }

            // Add school name
            doc.setFontSize(16);
            doc.setFont("helvetica", "bold");
            doc.text(schoolInfo.name, 45, y);

            // Add address & website
            doc.setFontSize(11);
            doc.setFont("helvetica", "normal");
            doc.text(schoolInfo.address, 45, y + 8);
            doc.text(schoolInfo.website, 45, y + 15);

            // Add email
            if (schoolInfo.email) {
                doc.text("Email: " + schoolInfo.email, 45, y + 22);
            }

            // Draw line under header
            doc.setLineWidth(0.5);
            doc.line(14, y + 28, 200, y + 28);

            return y + 35; // return where content should start
        }


        // PDF Header Function
        function addPDFHeader(doc) {
            let pageWidth = doc.internal.pageSize.getWidth();
            let y = 15;

            // === Logo (Centered, Top) ===
            if (schoolInfo.logo) {
                let logoWidth = 25;
                let logoHeight = 30;
                let logoX = (pageWidth - logoWidth) / 2; // center horizontally
                doc.addImage(schoolInfo.logo, "PNG", logoX, y, logoWidth, logoHeight);
                y += logoHeight + 10; // move Y down after logo
            }

            // === School Name (Centered, Bold) ===
            doc.setFont("Times New Roman", "bold");
            doc.setFontSize(28);
            doc.text(schoolInfo.name, pageWidth / 2, y, { align: "center" });

            // === Address (Centered, Normal Font) ===
            doc.setFont("Times New Roman", "normal");
            doc.setFontSize(12);
            doc.text(schoolInfo.address, pageWidth / 2, y + 8, { align: "center" });

            // === Website + Email (Centered, Small Font) ===
            doc.setFontSize(12);
            let contactLine = `Website: ${schoolInfo.website}   |   E-mail: ${schoolInfo.email}`;
            doc.text(contactLine, pageWidth / 2, y + 15, { align: "center" });

            // === Divider Line ===
            doc.setLineWidth(0.5);
            doc.line(14, y + 22, pageWidth - 14, y + 22);

            return y + 30; // Return new Y for content start
        }



        // PDF download function
        function downloadPDF(reportType) {
            if (!reportData || Object.keys(reportData).length === 0) {
                alert('Please generate a report first before downloading.');
                return;
            }

            const { jsPDF } = window.jspdf;
            const doc = new jsPDF();

            // Add header
            let contentStartY = addPDFHeader(doc);

            // === Title (Centered + Underlined) ===
            doc.setFontSize(14);
            doc.setFont("Times New Roman", "bold");
            let pageWidth = doc.internal.pageSize.getWidth();
            doc.text('STUDENT PERFORMANCE REPORT', pageWidth / 2, contentStartY, { align: "center" });

            // underline title
            let titleWidth = doc.getTextWidth('STUDENT PERFORMANCE REPORT');
            doc.setLineWidth(0.5);
            doc.line((pageWidth - titleWidth) / 2, contentStartY + 2, (pageWidth + titleWidth) / 2, contentStartY + 2);

            contentStartY += 12; // spacing after title

            // === Filters Info (Horizontal Grid) ===
            doc.setFontSize(12);
            doc.setFont("Times New Roman", "normal");

            // get selected term text & value
            let termSelect = document.getElementById('term');
            let selectedTermText = termSelect.options[termSelect.selectedIndex].text;
            let selectedTermValue = termSelect.value;

            // only show term if a real option is chosen
            let termText = selectedTermValue ? `Term: ${selectedTermText}` : "Term:";

            let filters = [
                `Session: ${document.getElementById('session').options[document.getElementById('session').selectedIndex].text}`,
                termText, // will be empty if "Select Term" was chosen
                `Class: ${document.getElementById('class').value}`,
                `Arm: ${document.getElementById('section').value}`
            ].filter(f => f !== ""); // remove empty ones


            // calculate spacing for equal distribution
            let colWidth = pageWidth / filters.length;
            filters.forEach((filter, i) => {
                let x = (colWidth * i) + (colWidth / 2);
                doc.text(filter, x, contentStartY, { align: "center" });
            });

            contentStartY += 12; // spacing after filters

            // Report content
            doc.setFontSize(12);
            doc.setFont("Times New Roman", "normal");


            if (reportType === 'overview') {
                doc.text('Overall Performance Summary', 14, contentStartY);
                doc.autoTable({
                    html: '#overall-table',
                    startY: contentStartY + 5,
                });

            } else if (reportType === 'class-performance') {
                doc.text('Class Performance Ranking', 14, contentStartY);
                let startY = contentStartY + 10;

                if (reportData.classPerformance) {
                    reportData.classPerformance.forEach(classData => {
                        if (startY > 250) {
                            doc.addPage();
                            startY = 20;
                        }

                        doc.setFontSize(14);
                        doc.text(`${classData.class} - ${classData.section} Arm`, 14, startY);
                        startY += 10;

                        const tableData = classData.students.map((student, index) => [
                            index + 1,
                            student.studentno,
                            student.studentName,
                            `${student.average_score}%`,
                            `${index + 1}${getOrdinalSuffix(index + 1)}`,
                            student.average_score >= 50 ? 'Promoted' : 'Review Needed'
                        ]);

                        doc.autoTable({
                            head: [['Rank', 'Admission No', 'Student Name', 'Average (%)', 'Position', 'Promotion Status']],
                            body: tableData,
                            startY: startY,
                            theme: 'grid',
                            headStyles: { fillColor: [74, 111, 220] }
                        });

                        startY = doc.lastAutoTable.finalY + 15;
                    });
                }

            } else if (reportType === 'subject-performance') {
                doc.text('Subject Performance', 14, contentStartY);
                let startY = contentStartY + 10;

                if (reportData.subjectPerformance) {
                    reportData.subjectPerformance.forEach(subjectData => {
                        if (startY > 250) {
                            doc.addPage();
                            startY = 20;
                        }

                        doc.setFontSize(14);
                        doc.text(`${subjectData.subject} - Top Performers by Class`, 14, startY);
                        startY += 10;

                        const tableData = subjectData.topPerformers.map(performer => [
                            performer.class,
                            performer.studentno,
                            performer.studentName,
                            `${performer.score}%`,
                            `Best in ${subjectData.subject}`
                        ]);

                        doc.autoTable({
                            head: [['Class', 'Admission No', 'Student Name', 'Average (%)', 'Award']],
                            body: tableData,
                            startY: startY,
                            theme: 'grid',
                            headStyles: { fillColor: [74, 111, 220] }
                        });

                        startY = doc.lastAutoTable.finalY + 15;
                    });
                }

            } else if (reportType === 'weak-students') {
                doc.text('Students Needing Improvement', 14, contentStartY);
                contentStartY += 10;

                doc.setFontSize(14);
                doc.text('Students Below 50% Average', 14, contentStartY);
                contentStartY += 5;

                const below50Data = reportData.weakStudents
                    .filter(student => student.average_score < 50)
                    .map(student => [
                        student.studentno,
                        student.studentName,
                        student.class,
                        student.section,
                        `${student.average_score}%`,
                        'Extra classes, Parent meeting'
                    ]);

                if (below50Data.length > 0) {
                    doc.autoTable({
                        head: [['Admission No', 'Student Name', 'Class', 'Arm', 'Average (%)', 'Intervention Needed']],
                        body: below50Data,
                        startY: contentStartY,
                        theme: 'grid',
                        headStyles: { fillColor: [220, 53, 69] }
                    });
                } else {
                    doc.text('No students below 50% average', 14, contentStartY + 5);
                }

            } else if (reportType === 'class-performance-overall') {
                doc.text('Overall Class Performance Ranking', 14, contentStartY);
                let startY = contentStartY + 10;

                if (reportData.classPerformanceOverall) {
                    reportData.classPerformanceOverall.forEach(classData => {
                        if (startY > 250) {
                            doc.addPage();
                            startY = 20;
                        }

                        doc.setFontSize(14);
                        doc.text(`${classData.class} Overall`, 14, startY);
                        startY += 10;

                        const tableData = classData.students.map((student, index) => [
                            index + 1,
                            student.studentno,
                            student.studentName,
                            student.section,
                            `${student.average_score}%`,
                            `${index + 1}${getOrdinalSuffix(index + 1)}`,
                            student.average_score >= 50 ? 'Promoted' : 'Review Needed'
                        ]);

                        doc.autoTable({
                            head: [['Rank', 'Admission No', 'Student Name', 'Arm', 'Average (%)', 'Position', 'Promotion Status']],
                            body: tableData,
                            startY: startY,
                            theme: 'grid',
                            headStyles: { fillColor: [74, 111, 220] }
                        });

                        startY = doc.lastAutoTable.finalY + 15;
                    });
                } else {
                    doc.setFontSize(12);
                    doc.text('No overall class performance data available', 14, startY);
                }

                const atRiskData = reportData.weakStudents
                    .filter(student => student.average_score >= 50 && student.average_score < 60)
                    .map(student => [
                        student.studentno,
                        student.studentName,
                        student.class,
                        student.section,
                        `${student.average_score}%`,
                        'Multiple subjects below 50%'
                    ]);

                if (atRiskData.length > 0) {
                    const startY = below50Data && below50Data.length > 0 ? doc.lastAutoTable.finalY + 15 : contentStartY + 20;
                    doc.setFontSize(14);
                    doc.text('Students at Risk of Not Being Promoted', 14, startY);

                    doc.autoTable({
                        head: [['Admission No', 'Student Name', 'Class', 'Arm', 'Average (%)', 'Key Concerns']],
                        body: atRiskData,
                        startY: startY + 5,
                        theme: 'grid',
                        headStyles: { fillColor: [255, 193, 7] }
                    });
                }
            }
            // Add to the downloadPDF function
            else if (reportType === 'class-performance-top3') {
                doc.text('Top 3 Students Per Class (All Arms)', 14, contentStartY);
                let startY = contentStartY + 10;

                if (reportData.classPerformanceTop3) {
                    reportData.classPerformanceTop3.forEach(classData => {
                        if (startY > 250) {
                            doc.addPage();
                            startY = 20;
                        }

                        doc.setFontSize(14);
                        doc.text(`${classData.class} — Top 3 Students (All Arms)`, 14, startY);
                        startY += 10;

                        const tableData = classData.students.map((student, index) => [
                            index + 1,
                            student.studentno,
                            student.studentName,
                            student.section,
                            `${student.average_score}%`,
                            `${index + 1}${getOrdinalSuffix(index + 1)}`
                        ]);

                        doc.autoTable({
                            head: [['Rank', 'Admission No', 'Student Name', 'Arm', 'Average (%)', 'Position']],
                            body: tableData,
                            startY: startY,
                            theme: 'grid',
                            headStyles: { fillColor: [74, 111, 220] }
                        });

                        startY = doc.lastAutoTable.finalY + 15;
                    });
                } else {
                    doc.setFontSize(12);
                    doc.text('No top 3 class data available', 14, startY);
                }
            }
            // Add to the downloadPDF function
            else if (reportType === 'results') {
                doc.text('Student Results Summary', 14, contentStartY);
                let startY = contentStartY + 10;

                if (reportData.studentResults) {
                    // Group by class for the PDF
                    const resultsByClass = {};

                    reportData.studentResults.forEach(student => {
                        const classKey = student.class + '|' + student.section;
                        if (!resultsByClass[classKey]) {
                            resultsByClass[classKey] = {
                                class: student.class,
                                section: student.section,
                                students: []
                            };
                        }
                        resultsByClass[classKey].students.push(student);
                    });

                    // Sort and assign positions
                    Object.keys(resultsByClass).forEach(key => {
                        resultsByClass[key].students.sort((a, b) => b.percentage - a.percentage);
                        resultsByClass[key].students.forEach((student, index) => {
                            student.position = index + 1;
                        });
                    });

                    // Create PDF for each class
                    Object.keys(resultsByClass).forEach(key => {
                        const classData = resultsByClass[key];

                        if (startY > 250) {
                            doc.addPage();
                            startY = 20;
                            contentStartY = addPDFHeader(doc) + 10;
                        }

                        doc.setFontSize(14);
                        doc.text(`${classData.class} - ${classData.section} Arm - Student Results`, 14, startY);
                        startY += 10;

                        const tableData = classData.students.map(student => [
                            `${student.position}${getOrdinalSuffix(student.position)}`,
                            student.studentName,
                            student.studentno,
                            student.total_obtainable.toString(),
                            student.total_obtained.toString(),
                            `${student.percentage.toFixed(2)}%`,
                            student.percentage >= 80 ? 'Excellent' :
                                student.percentage >= 60 ? 'Good' :
                                    student.percentage >= 50 ? 'Average' : 'Needs Improvement'
                        ]);

                        doc.autoTable({
                            head: [['Position', 'Student Name', 'Admission No', 'Total Obtainable', 'Total Obtained', '% Obtained', 'Remark']],
                            body: tableData,
                            startY: startY,
                            theme: 'grid',
                            headStyles: { fillColor: [74, 111, 220] }
                        });

                        startY = doc.lastAutoTable.finalY + 15;
                    });
                }

            }
            // Save the PDF
            doc.save(`student-report-${reportType}.pdf`);
        }

        // =====================================================================
        // AI Insights Functions
        // =====================================================================

        // Track DataTable instances so we can destroy/reinit on re-render
        const aiDTInstances = {};

        function initAITable(tableId) {
            if (aiDTInstances[tableId]) {
                aiDTInstances[tableId].destroy();
            }
            aiDTInstances[tableId] = $('#' + tableId).DataTable({
                responsive: true,
                autoWidth: false,
                pageLength: 20,
                lengthMenu: [10, 20, 50, 100],
                language: { search: 'Search:', lengthMenu: 'Show _MENU_ entries' }
            });
        }

        function getBandBadgeClass(band) {
            // SS grades (WAEC/NECO)
            if (['A1', 'B2', 'B3'].includes(band)) return 'badge-high';
            if (['C4', 'C5', 'C6'].includes(band)) return 'badge-medium';
            if (['D7', 'E8', 'F9'].includes(band)) return 'badge-low';
            // JSS grades (NERDC)
            if (band === 'Distinction') return 'badge-high';
            if (['Credit', 'Merit'].includes(band)) return 'badge-medium';
            if (band === 'Pass') return 'badge-medium';
            if (band === 'Fail') return 'badge-low';
            // Primary grades (NERDC)
            if (['Excellent', 'Very Good'].includes(band)) return 'badge-high';
            if (['Good', 'Average'].includes(band)) return 'badge-medium';
            if (band === 'Below Average') return 'badge-medium';
            // Generic fallback
            if (['A', 'B'].includes(band)) return 'badge-high';
            if (band === 'C') return 'badge-medium';
            if (['D', 'F'].includes(band)) return 'badge-low';
            return 'badge-medium';
        }

        function getTrendArrow(trend) {
            if (trend > 0) return '<span style="color:#28a745">▲ +' + trend.toFixed(1) + '</span>';
            if (trend < 0) return '<span style="color:#dc3545">▼ ' + trend.toFixed(1) + '</span>';
            return '<span style="color:#6c757d">— 0</span>';
        }

        function displaySchoolInsights(insights) {
            const div = document.getElementById('ai-school-insights');
            if (!insights || insights.length === 0) {
                div.innerHTML = '';
                return;
            }
            let html = '<h5 style="margin-bottom:12px;"><i class="fas fa-lightbulb" style="color:#ffc107"></i> School Insights</h5>';
            html += '<div style="background:#fff8e1;border-left:4px solid #ffc107;padding:15px;border-radius:6px;">';
            insights.forEach(rec => {
                html += `<p style="margin-bottom:8px;"><i class="fas fa-chevron-right" style="color:#ffc107;margin-right:6px;"></i>${rec}</p>`;
            });
            html += '</div>';
            div.innerHTML = html;
        }

        function displayAIRankings(rankings) {
            const div = document.getElementById('ai-rankings-section');
            if (!rankings || rankings.length === 0) {
                div.innerHTML = '<p style="color:#6c757d;">No ranking data available.</p>';
                return;
            }
            let html = '<h5 style="margin-bottom:12px;"><i class="fas fa-trophy" style="color:#4a6fdc"></i> AI Performance Rankings</h5>';
            html += `<table id="ai-rankings-table" class="table table-bordered table-hover table-striped" style="width:100%;font-size:13px;">
                <thead>
                    <tr style="background:#f8f9fa;">
                        <th>Rank</th>
                        <th>Adm. No</th>
                        <th>Student Name</th>
                        <th>Class</th>
                        <th>Arm</th>
                        <th>Exam</th>
                        <th>C.A. Test</th>
                        <th>Class Ex.</th>
                        <th>Assign.</th>
                        <th>AI Score</th>
                        <th>Trend</th>
                        <th>Band</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody id="ai-rankings-tbody">`;

            rankings.forEach((s, idx) => {
                const rowClass = idx < 3 ? 'highlight' : '';
                const strengthsHtml = (s.strength_subjects || []).map(x => `<span style="background:#e8f5e9;color:#28a745;padding:2px 6px;border-radius:10px;font-size:11px;margin:2px;">${x.subject}</span>`).join('');
                const improvementsHtml = (s.improvement_subjects || []).map(x => `<span style="background:#ffebee;color:#dc3545;padding:2px 6px;border-radius:10px;font-size:11px;margin:2px;">${x.subject}</span>`).join('');
                const detailId = 'ai-detail-' + s.student_id;

                html += `<tr class="${rowClass}">
                    <td style="font-weight:bold;">${s.rank}</td>
                    <td>${s.studentno}</td>
                    <td>${s.student_name}</td>
                    <td>${s.class}</td>
                    <td>${s.section}</td>
                    <td>${s.exam_score}</td>
                    <td>${s.test_score}</td>
                    <td>${s.class_performance}</td>
                    <td>${s.weekly_assessment}</td>
                    <td style="font-weight:bold;">${s.performance_score}</td>
                    <td>${getTrendArrow(s.trend_score)}</td>
                    <td><span class="performance-badge ${getBandBadgeClass(s.ai_band)}">${s.ai_band}</span></td>
                    <td><button onclick="var el=document.getElementById('${detailId}');el.style.display=el.style.display==='none'?'table-row':'none'" style="background:#4a6fdc;color:#fff;border:none;padding:4px 8px;border-radius:4px;cursor:pointer;font-size:11px;">Details</button></td>
                </tr>
                <tr id="${detailId}" style="display:none;background:#f8f9fa;">
                    <td colspan="13" style="padding:12px 20px;">
                        <strong>Strengths:</strong> ${strengthsHtml || '<em>None identified</em>'}&nbsp;&nbsp;
                        <strong>Needs Improvement:</strong> ${improvementsHtml || '<em>None identified</em>'}
                    </td>
                </tr>`;
            });

            html += '</tbody></table>';
            div.innerHTML = html;
            initAITable('ai-rankings-table');
        }

        function displayAtRiskStudents(atRisk) {
            const div = document.getElementById('ai-at-risk-section');
            let html = '<h5 style="margin-bottom:12px;"><i class="fas fa-exclamation-triangle" style="color:#dc3545"></i> AI At-Risk Students</h5>';

            if (!atRisk || atRisk.length === 0) {
                html += '<div style="background:#e8f5e9;border-left:4px solid #28a745;padding:12px;border-radius:6px;color:#28a745;">No at-risk students identified for the selected period.</div>';
                div.innerHTML = html;
                return;
            }

            html += `<table id="ai-atrisk-table" class="table table-bordered table-hover table-striped" style="width:100%;font-size:13px;">
                <thead>
                    <tr style="background:#ffebee;">
                        <th>Student Name</th>
                        <th>Class</th>
                        <th>Arm</th>
                        <th>AI Score</th>
                        <th>Trend</th>
                        <th>Risk Level</th>
                        <th>Reason</th>
                    </tr>
                </thead>
                <tbody>`;

            atRisk.forEach(s => {
                const riskColor = s.risk_level === 'Critical' ? '#dc3545' : s.risk_level === 'High' ? '#fd7e14' : '#ffc107';
                html += `<tr>
                    <td>${s.student_name}</td>
                    <td>${s.class}</td>
                    <td>${s.section}</td>
                    <td style="color:#dc3545;font-weight:bold;">${s.performance_score}</td>
                    <td>${getTrendArrow(s.trend_score)}</td>
                    <td><span style="background:${riskColor};color:#fff;padding:3px 8px;border-radius:10px;font-size:11px;">${s.risk_level}</span></td>
                    <td style="font-size:12px;">${s.risk_reason}</td>
                </tr>`;
            });

            html += '</tbody></table>';
            div.innerHTML = html;
            initAITable('ai-atrisk-table');
        }

        function displayClassInsights(classInsights) {
            const div = document.getElementById('ai-class-insights-section');
            if (!classInsights || classInsights.length === 0) {
                div.innerHTML = '';
                return;
            }
            let html = '<h5 style="margin-bottom:12px;"><i class="fas fa-chalkboard-teacher" style="color:#17a2b8"></i> Class Insights</h5>';

            classInsights.forEach(ci => {
                html += `<div style="background:#e3f2fd;border-left:4px solid #17a2b8;padding:15px;border-radius:6px;margin-bottom:12px;">
                    <strong>${ci.class} — ${ci.section} Arm</strong>`;
                (ci.recommendations || []).forEach(rec => {
                    html += `<p style="margin:6px 0 0 0;font-size:13px;"><i class="fas fa-chevron-right" style="color:#17a2b8;margin-right:6px;"></i>${rec}</p>`;
                });
                html += '</div>';
            });

            div.innerHTML = html;
        }

        function downloadAIPDF() {
            if (!aiReportData || !aiReportData.rankings || aiReportData.rankings.length === 0) {
                alert('Please generate a report first before downloading the AI report.');
                return;
            }
            const { jsPDF } = window.jspdf;
            const doc = new jsPDF({ orientation: 'landscape', unit: 'mm', format: 'a4' });

            doc.setFontSize(16);
            doc.setFont(undefined, 'bold');
            doc.text('AI Student Performance Report', 148, 15, { align: 'center' });
            doc.setFontSize(10);
            doc.setFont(undefined, 'normal');
            doc.text(`Generated: ${new Date().toLocaleString()}`, 148, 22, { align: 'center' });

            // Rankings table
            doc.setFontSize(12);
            doc.setFont(undefined, 'bold');
            doc.text('AI Performance Rankings', 14, 32);

            const rankHead = [['Rank', 'Adm. No', 'Student Name', 'Class', 'Arm', 'AI Score', 'Trend', 'Band']];
            const rankBody = aiReportData.rankings.map(s => [
                s.rank, s.studentno, s.student_name, s.class, s.section,
                s.performance_score, (s.trend_score >= 0 ? '+' : '') + s.trend_score, s.ai_band
            ]);

            doc.autoTable({
                head: rankHead,
                body: rankBody,
                startY: 36,
                styles: { fontSize: 9 },
                headStyles: { fillColor: [74, 111, 220] },
                didParseCell: (data) => {
                    if (data.row.index < 3 && data.section === 'body') {
                        data.cell.styles.fillColor = [232, 244, 255];
                    }
                }
            });

            // At-risk table
            if (aiReportData.atRiskStudents && aiReportData.atRiskStudents.length > 0) {
                const startY = doc.lastAutoTable.finalY + 10;
                doc.setFontSize(12);
                doc.setFont(undefined, 'bold'); doc.text('At-Risk Students', 14, startY);

                const riskHead = [['Student Name', 'Class', 'Arm', 'AI Score', 'Risk Level', 'Reason']];
                const riskBody = aiReportData.atRiskStudents.map(s => [
                    s.student_name, s.class, s.section, s.performance_score, s.risk_level, s.risk_reason
                ]);

                doc.autoTable({
                    head: riskHead,
                    body: riskBody,
                    startY: startY + 4,
                    styles: { fontSize: 9 },
                    headStyles: { fillColor: [220, 53, 69] },
                });
            }

            doc.save('ai-performance-report.pdf');
        }

    </script>
</body>

</html>