<?php
/**
 * Teacher Portal — Progress Analytics (class-scoped).
 *
 * Reuses the shared query library (analytics/lib/progress_query.php) but confines
 * EVERY scope to the teacher's own classes, resolved server-side from their
 * assignments — a teacher can never read another class's data.
 *
 * Gated on hasModule('progress_analytics') — NOT requireModule(), whose
 * ROLE_ACCESS lookup would misjudge a portal session (see the portal auth guard).
 *
 * Actions (?action=):
 *   meta       classes the teacher may view + current year/term + subjects
 *   dashboard  kpis/trend/subjects/distribution/table (+ cohort panels) for a scope
 *   students   roster of one of the teacher's classes (for the student picker)
 */
declare(strict_types=1);
require_once __DIR__ . '/tp_auth.php';
require_once dirname(__DIR__, 2) . '/analytics/lib/progress_query.php';

$teacher_id = tp_require_auth();
$conn       = getDBConnection();

// Feature gate — license only (portal sessions have no admin role).
if (!hasModule('progress_analytics')) {
    tp_json(false, ['locked' => true], 'Progress Analytics is not enabled for your school.');
}

$allowed = tp_teacher_classes($teacher_id);
$action  = $_GET['action'] ?? 'dashboard';

/** Build a scope from the request, hard-locked to the teacher's classes. */
function tp_progress_scope(array $allowed): array
{
    return progressNormalizeScope($_GET, $allowed);
}

if ($action === 'meta') {
    $opts = progressFilterOptions($conn, $allowed);
    tp_json(true, [
        'classes'      => $allowed,
        'subjects'     => $opts['subjects'],
        'years'        => $opts['years'],
        'terms'        => $opts['terms'],
        'current_year' => $opts['current_year'],
        'current_term' => $opts['current_term'],
    ]);
}

if ($action === 'students') {
    $class = trim((string) ($_GET['class'] ?? ''));
    if ($class === '' || !in_array($class, $allowed, true)) {
        tp_json(true, ['students' => []]);
    }
    $stmt = $conn->prepare(
        "SELECT id, student_id AS admission_no, first_name, last_name
           FROM students WHERE class = ? AND status = 'active'
          ORDER BY first_name, last_name"
    );
    $stmt->bind_param('s', $class);
    $stmt->execute();
    $res = $stmt->get_result();
    $students = [];
    while ($row = $res->fetch_assoc()) {
        $students[] = [
            'id'    => (int) $row['id'],
            'label' => trim($row['first_name'] . ' ' . $row['last_name']) . ' (' . $row['admission_no'] . ')',
        ];
    }
    $stmt->close();
    tp_json(true, ['students' => $students]);
}

// action = dashboard
if ($allowed === []) {
    tp_json(true, ['no_classes' => true]);
}

$scope = tp_progress_scope($allowed);

$data = [
    'scope'        => $scope,
    'kpis'         => progressKpis($conn, $scope),
    'trend'        => progressTrend($conn, $scope),
    'subjects'     => progressSubjectBreakdown($conn, $scope),
    'distribution' => progressGradeDistribution($conn, $scope),
    'table'        => progressTableRows($conn, $scope),
];

if ($scope['level'] === 'student' && $scope['student_id'] > 0) {
    $data['student'] = progressStudentHeader($conn, $scope['student_id']);
} else {
    $data['heatmap']    = progressHeatmap($conn, $scope);
    $data['movement']   = progressRankMovement($conn, $scope);
    $data['attendance'] = progressAttendanceScatter($conn, $scope);
}

tp_json(true, $data);
