<?php
/**
 * Progress Analytics — admin dashboard page.
 *
 * Graphical academic-progress view: whole-school, per-class, or per-student,
 * filterable by year / term / class / subject, with a chart row and a DataTable
 * beneath. All data is fetched from analytics/ajax/data.php (which builds every
 * number via analytics/lib/progress_query.php).
 */
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
if (!isset($_SESSION['user_id'])) {
    header('Location: ../index.php');
    exit;
}

require_once '../config.php';
require_once __DIR__ . '/lib/progress_access.php';

// Module + role gate (redirects to upgrade/dashboard on failure).
requireModule('progress_analytics');

$conn = getDBConnection();
require_once __DIR__ . '/lib/progress_query.php';

$context = progressAccessContext();
$filters = progressFilterOptions($conn, $context['allowed_classes']);
$isRestricted = $context['allowed_classes'] !== null;

require_once __DIR__ . '/lib/progress_insight.php';
$hasAiInsight = progressInsightAvailable();

$page_title = 'Progress Analytics';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Progress Analytics — EduTrack</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/datatables.net-bs5@1.13.6/css/dataTables.bootstrap5.min.css">
    <link rel="stylesheet" href="../css/style.css">
    <style>
    /* ── Progress Analytics — chart/design tokens (dataviz reference palette) ── */
    .pa-root {
        --surface-1:      #fcfcfb;
        --page-plane:     #f9f9f7;
        --text-primary:   #0b0b0b;
        --text-secondary: #52514e;
        --text-muted:     #898781;
        --grid:           #e1e0d9;
        --axis:           #c3c2b7;
        --series-1:       #2a78d6; /* blue  — primary / "this student" */
        --series-2:       #eb6834; /* orange — comparison / "class avg" */
        --good:           #0ca30c;
        --warning:        #fab219;
        --serious:        #ec835a;
        --critical:       #d03b3b;
        --border:         rgba(11,11,11,.10);
    }
    .pa-toolbar { background:#fff; border:1px solid var(--border); border-radius:14px; padding:14px 16px; margin-bottom:18px; }
    .pa-viewtabs .btn { border-radius:10px; }
    .pa-kpis { display:grid; grid-template-columns:repeat(auto-fit,minmax(155px,1fr)); gap:14px; margin-bottom:18px; }
    .pa-kpi { background:#fff; border:1px solid var(--border); border-radius:14px; padding:16px 18px; }
    .pa-kpi .lbl { font-size:.72rem; letter-spacing:.04em; text-transform:uppercase; color:var(--text-muted); margin-bottom:6px; }
    .pa-kpi .val { font-size:1.6rem; font-weight:700; color:var(--text-primary); line-height:1.1; }
    .pa-kpi .val.tabnum { font-variant-numeric:tabular-nums; }
    .pa-kpi .sub { font-size:.78rem; color:var(--text-secondary); margin-top:4px; }
    .pa-card { background:#fff; border:1px solid var(--border); border-radius:14px; padding:16px 18px; margin-bottom:18px; }
    .pa-card h6 { font-weight:700; color:var(--text-primary); margin:0 0 2px; }
    .pa-card .hint { font-size:.78rem; color:var(--text-muted); margin-bottom:12px; }
    .pa-chart-wrap { position:relative; height:300px; }
    .pa-chart-wrap.tall { height:340px; }
    .pa-coverage-warn { font-size:.78rem; color:#8a5a00; background:#fff6e5; border:1px solid #ffe1a8;
                        border-radius:8px; padding:6px 10px; display:none; }
    .pa-badge-grade { font-weight:700; padding:2px 8px; border-radius:6px; color:#fff; font-variant-numeric:tabular-nums; }
    table.dataTable td.num, table.dataTable th.num { text-align:right; font-variant-numeric:tabular-nums; }
    .pa-drill { cursor:pointer; }
    .pa-drill:hover { background:#f3f7fd !important; }
    .pa-empty { text-align:center; color:var(--text-muted); padding:38px 12px; }
    /* Heatmap */
    .pa-heat { border-collapse:separate; border-spacing:2px; font-size:.8rem; }
    .pa-heat th { font-weight:600; color:var(--text-secondary); padding:4px 6px; white-space:nowrap; }
    .pa-heat th.rot { height:96px; vertical-align:bottom; }
    .pa-heat th.rot > div { transform:rotate(-52deg); transform-origin:bottom left; width:20px; white-space:nowrap; font-weight:600; }
    .pa-heat td.rowname { text-align:left; white-space:nowrap; color:var(--text-primary); font-weight:600; padding-right:8px; max-width:180px; overflow:hidden; text-overflow:ellipsis; }
    .pa-heat td.cell { width:40px; height:30px; text-align:center; border-radius:5px; color:#0b0b0b; font-variant-numeric:tabular-nums; cursor:default; }
    .pa-heat td.cell.empty { background:#f1f0ec !important; color:var(--text-muted); }
    .pa-heat td.rowavg { font-weight:700; text-align:center; font-variant-numeric:tabular-nums; }
    /* Movement lists */
    .pa-move-row { display:flex; align-items:center; justify-content:space-between; padding:6px 0; border-bottom:1px solid #f0efec; }
    .pa-move-row:last-child { border-bottom:0; }
    .pa-move-name { font-weight:600; color:var(--text-primary); font-size:.86rem; }
    .pa-move-sub { font-size:.74rem; color:var(--text-muted); }
    .pa-delta { font-weight:700; font-variant-numeric:tabular-nums; padding:2px 8px; border-radius:6px; font-size:.8rem; }
    .pa-delta.up { color:#0a6b0a; background:#e6f4e6; }
    .pa-delta.down { color:#a11; background:#fbeaea; }
    .pa-move-col h6 { font-size:.82rem; text-transform:uppercase; letter-spacing:.04em; color:var(--text-muted); }
    /* Compare */
    .pa-cmp-grid { display:grid; grid-template-columns:1fr 1fr; gap:14px; }
    .pa-cmp-side { border:1px solid var(--border); border-radius:12px; padding:12px 14px; }
    .pa-cmp-side .name { font-weight:700; margin-bottom:8px; }
    .pa-cmp-metric { display:flex; justify-content:space-between; padding:3px 0; font-size:.86rem; }
    .pa-cmp-metric .v { font-weight:700; font-variant-numeric:tabular-nums; }
    .pa-cmp-win { color:#0a6b0a; } .pa-cmp-lose { color:#a11; }
    /* AI summary */
    .pa-ai-card { border-left:3px solid var(--series-1); }
    .pa-ai-body { font-size:.9rem; color:var(--text-primary); line-height:1.55; white-space:pre-wrap; }
    .pa-ai-body ul { margin:.2rem 0 .2rem 1.1rem; }
    .pa-ai-body.loading { color:var(--text-muted); }
    .pa-scope-crumb { font-size:.82rem; color:var(--text-secondary); }
    .pa-scope-crumb .chip { background:#eef4fc; color:#1c5cab; border-radius:20px; padding:2px 10px; margin-left:6px; font-weight:600; }
    @media (prefers-color-scheme: dark) {
      /* Charts render on white cards regardless of OS theme to match the app chrome. */
    }
    </style>
</head>
<body>
    <div class="wrapper">
        <nav id="sidebar" class="sidebar">
            <?php
            if (!defined('EDUTRACK_MODULES')) require_once __DIR__ . '/../module_definitions.php';
            echo buildSidebar('analytics/progress.php');
            ?>
        </nav>

        <div class="main-content">
            <header class="header">
                <button class="btn-toggle" id="sidebarToggle"><i class="fas fa-bars"></i></button>
                <div class="header-right">
                    <div class="dropdown">
                        <button class="btn btn-link dropdown-toggle" type="button" data-bs-toggle="dropdown">
                            <i class="fas fa-user-circle me-2"></i><?= htmlspecialchars((string)($_SESSION['full_name'] ?? '')) ?>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="../settings.php"><i class="fas fa-cog me-2"></i>Settings</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="../logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>
                        </ul>
                    </div>
                </div>
            </header>

            <main class="content pa-root">
                <div class="content-header d-flex justify-content-between align-items-center flex-wrap">
                    <div>
                        <h2><i class="fas fa-chart-line me-2"></i>Progress Analytics</h2>
                        <p class="mb-0 pa-scope-crumb" id="paScopeCrumb">Whole school overview</p>
                    </div>
                    <div class="text-end">
                        <span class="pa-scope-crumb" id="paPeriodCrumb"></span>
                    </div>
                </div>

                <!-- ── Toolbar / filters ─────────────────────────────────── -->
                <div class="pa-toolbar">
                    <div class="row g-2 align-items-end">
                        <div class="col-12 col-lg-auto">
                            <label class="form-label small text-muted mb-1 d-block">View</label>
                            <div class="btn-group pa-viewtabs" role="group" id="paViewTabs">
                                <button type="button" class="btn btn-outline-primary active" data-level="school">School</button>
                                <button type="button" class="btn btn-outline-primary" data-level="class">Class</button>
                                <button type="button" class="btn btn-outline-primary" data-level="student">Student</button>
                            </div>
                        </div>
                        <div class="col-6 col-md-3 col-lg-2">
                            <label class="form-label small text-muted mb-1">Academic Year</label>
                            <select class="form-select form-select-sm" id="paYear">
                                <?php foreach ($filters['years'] as $y): ?>
                                    <option value="<?= htmlspecialchars($y) ?>" <?= $y === $filters['current_year'] ? 'selected' : '' ?>><?= htmlspecialchars($y) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-6 col-md-3 col-lg-2">
                            <label class="form-label small text-muted mb-1">Term</label>
                            <select class="form-select form-select-sm" id="paTerm">
                                <option value="">All terms</option>
                                <?php foreach ($filters['terms'] as $t): ?>
                                    <option value="<?= htmlspecialchars($t) ?>" <?= $t === $filters['current_term'] ? 'selected' : '' ?>><?= htmlspecialchars($t) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-6 col-md-3 col-lg-2 pa-field-class">
                            <label class="form-label small text-muted mb-1">Class</label>
                            <select class="form-select form-select-sm" id="paClass">
                                <option value="">All classes</option>
                                <?php foreach ($filters['classes'] as $c): ?>
                                    <option value="<?= htmlspecialchars($c) ?>"><?= htmlspecialchars($c) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-6 col-md-3 col-lg-2 pa-field-subject">
                            <label class="form-label small text-muted mb-1">Subject</label>
                            <select class="form-select form-select-sm" id="paSubject">
                                <option value="">All subjects</option>
                                <?php foreach ($filters['subjects'] as $s): ?>
                                    <option value="<?= (int)$s['id'] ?>"><?= htmlspecialchars($s['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-12 col-md-6 col-lg-2 pa-field-student" style="display:none">
                            <label class="form-label small text-muted mb-1">Student</label>
                            <select class="form-select form-select-sm" id="paStudent"><option value="">Select a class first…</option></select>
                        </div>
                        <div class="col-12 col-lg-auto ms-lg-auto">
                            <button class="btn btn-primary btn-sm w-100" id="paApply"><i class="fas fa-rotate me-1"></i>Update</button>
                        </div>
                    </div>
                    <?php if ($isRestricted): ?>
                        <div class="small text-muted mt-2"><i class="fas fa-lock me-1"></i>You are viewing only your assigned classes.</div>
                    <?php endif; ?>
                </div>

                <div class="pa-coverage-warn mb-3" id="paCoverageWarn"></div>

                <!-- ── KPI tiles ─────────────────────────────────────────── -->
                <div class="pa-kpis" id="paKpis"></div>

                <?php if ($hasAiInsight): ?>
                <!-- ── AI summary (premium) ─────────────────────────────── -->
                <div class="pa-card pa-ai-card">
                    <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
                        <h6 class="mb-0"><i class="fas fa-wand-magic-sparkles me-1 text-primary"></i>AI summary</h6>
                        <button class="btn btn-outline-primary btn-sm" id="paAiBtn"><i class="fas fa-wand-magic-sparkles me-1"></i>Generate summary</button>
                    </div>
                    <div class="pa-ai-body mt-2" id="paAiBody">
                        <span class="text-muted small">Generate a plain-English briefing of the current view.</span>
                    </div>
                    <div class="pa-ai-meta small text-muted mt-1" id="paAiMeta"></div>
                </div>
                <?php endif; ?>

                <!-- ── Student header (student view only) ────────────────── -->
                <div class="pa-card" id="paStudentHeader" style="display:none"></div>

                <!-- ── Charts ────────────────────────────────────────────── -->
                <div class="row">
                    <div class="col-12 col-xl-7">
                        <div class="pa-card">
                            <h6 id="paTrendTitle">Performance trend</h6>
                            <div class="hint" id="paTrendHint">Average score across terms</div>
                            <div class="pa-chart-wrap"><canvas id="paTrendChart"></canvas></div>
                        </div>
                    </div>
                    <div class="col-12 col-xl-5">
                        <div class="pa-card">
                            <h6>Grade distribution</h6>
                            <div class="hint">Number of results in each grade band</div>
                            <div class="pa-chart-wrap"><canvas id="paGradeChart"></canvas></div>
                        </div>
                    </div>
                </div>
                <div class="pa-card">
                    <h6 id="paSubjTitle">Subject performance</h6>
                    <div class="hint" id="paSubjHint">Average score per subject, strongest first</div>
                    <div class="pa-chart-wrap tall"><canvas id="paSubjectChart"></canvas></div>
                </div>

                <!-- ── P2: Rank movement + Attendance correlation ────────── -->
                <div class="row pa-cohort" id="paCohortSection">
                    <div class="col-12 col-xl-6">
                        <div class="pa-card">
                            <h6>Most improved &amp; declined</h6>
                            <div class="hint" id="paMovementHint">Change in average between the last two terms</div>
                            <div id="paMovementBody"></div>
                        </div>
                    </div>
                    <div class="col-12 col-xl-6">
                        <div class="pa-card">
                            <h6>Attendance vs average score</h6>
                            <div class="hint" id="paAttHint">Each dot is a student</div>
                            <div class="pa-chart-wrap"><canvas id="paAttChart"></canvas></div>
                            <div class="small text-muted mt-1" id="paAttNote"></div>
                        </div>
                    </div>
                </div>

                <!-- ── P2: Heatmap ───────────────────────────────────────── -->
                <div class="pa-card pa-cohort" id="paHeatmapSection">
                    <div class="d-flex justify-content-between align-items-center mb-1 flex-wrap">
                        <h6 class="mb-0" id="paHeatTitle">Performance heatmap</h6>
                        <span class="small text-muted" id="paHeatLegend"></span>
                    </div>
                    <div class="hint" id="paHeatHint">Average score per subject — darker is stronger</div>
                    <div class="table-responsive" id="paHeatWrap"></div>
                </div>

                <!-- ── DataTable ─────────────────────────────────────────── -->
                <div class="pa-card">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <h6 class="mb-0" id="paTableTitle">Breakdown</h6>
                        <div class="d-flex align-items-center gap-2">
                            <span class="small text-muted" id="paTableHint"></span>
                            <button class="btn btn-outline-secondary btn-sm" id="paExportCsv"><i class="fas fa-download me-1"></i>CSV</button>
                            <button class="btn btn-outline-danger btn-sm" id="paExportPdf"><i class="fas fa-file-pdf me-1"></i>PDF</button>
                        </div>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-hover table-sm align-middle" id="paTable" style="width:100%">
                            <thead><tr id="paTableHead"></tr></thead>
                            <tbody id="paTableBody"></tbody>
                        </table>
                    </div>
                </div>

                <!-- ── P2: Compare mode ──────────────────────────────────── -->
                <div class="pa-card pa-cohort" id="paCompareSection">
                    <div class="d-flex justify-content-between align-items-center mb-2 flex-wrap gap-2">
                        <h6 class="mb-0"><i class="fas fa-code-compare me-1"></i>Compare</h6>
                        <div class="d-flex align-items-end gap-2 flex-wrap">
                            <div>
                                <label class="form-label small text-muted mb-1 d-block">Compare by</label>
                                <select class="form-select form-select-sm" id="paCompareBy" style="min-width:120px">
                                    <option value="class">Class vs class</option>
                                    <option value="term">Term vs term</option>
                                </select>
                            </div>
                            <div id="paCompareBClassWrap">
                                <label class="form-label small text-muted mb-1 d-block">Against class</label>
                                <select class="form-select form-select-sm" id="paCompareBClass" style="min-width:130px">
                                    <option value="">Select…</option>
                                    <?php foreach ($filters['classes'] as $c): ?>
                                        <option value="<?= htmlspecialchars($c) ?>"><?= htmlspecialchars($c) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div id="paCompareBTermWrap" style="display:none">
                                <label class="form-label small text-muted mb-1 d-block">Against term</label>
                                <select class="form-select form-select-sm" id="paCompareBTerm" style="min-width:130px">
                                    <option value="">Select…</option>
                                    <?php foreach ($filters['terms'] as $t): ?>
                                        <option value="<?= htmlspecialchars($t) ?>"><?= htmlspecialchars($t) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <button class="btn btn-primary btn-sm" id="paCompareRun"><i class="fas fa-code-compare me-1"></i>Compare</button>
                        </div>
                    </div>
                    <div id="paCompareResult" class="pa-empty">Pick something to compare against, then press Compare.</div>
                </div>
            </main>
        </div>
    </div>

    <!-- jQuery + DataTables served from the same CDN hosts as Bootstrap/Chart.js
         (jsdelivr) and Font Awesome (cloudflare), which this app already loads
         successfully — avoids a single blocked host (e.g. code.jquery.com)
         silently disabling the table. The page also degrades gracefully if any
         of these fail to load (see renderTable). -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/datatables.net@1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/datatables.net-bs5@1.13.6/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4"></script>
    <script src="../js/main.js"></script>
    <script>
    // Students-per-class come from the same endpoint family; expose the classes list
    // the server already resolved so the Student picker can be populated on demand.
    window.PA_BOOT = {
        classes: <?= json_encode($filters['classes']) ?>,
        restricted: <?= $isRestricted ? 'true' : 'false' ?>,
        hasAi: <?= $hasAiInsight ? 'true' : 'false' ?>
    };
    </script>
    <script src="assets/progress.js"></script>
</body>
</html>
