<?php

declare(strict_types=1);

require_once __DIR__ . '/tp_auth.php';



$teacher_id = tp_require_auth();

$conn       = getDBConnection();

$ay         = (string)(getSettingValue('academic_year') ?? date('Y'));

$term       = (string)(getSettingValue('current_term')  ?? '');



$class_name = trim($_GET['class'] ?? '');

$classes    = tp_teacher_classes($teacher_id);



if ($class_name === '' && !empty($classes)) {

    $class_name = $classes[0];

}

if ($class_name === '' || !in_array($class_name, $classes, true)) {

    tp_json(false, null, 'Class not found or not assigned to you.');

}



// ── Students ──────────────────────────────────────────────────────────────────

$stmt = $conn->prepare(

    "SELECT id, student_id, first_name, last_name, photo_path

       FROM students

      WHERE class = ? AND status = 'active'

      ORDER BY first_name, last_name"

);

$stmt->bind_param('s', $class_name);

$stmt->execute();

$students = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

$stmt->close();



if (empty($students)) {

    tp_json(true, ['students' => [], 'class_name' => $class_name, 'classes' => $classes]);

}



$student_ids = array_column($students, 'id');

$ph          = implode(',', array_fill(0, count($student_ids), '?'));

$types_i     = str_repeat('i', count($student_ids));



// ── Scores (current term/year avg) ───────────────────────────────────────────

$score_map = [];

if ($term !== '') {

    $stmt = $conn->prepare(

        "SELECT student_id, ROUND(AVG(total_score), 1) AS avg_score

           FROM scores

          WHERE term = ? AND academic_year = ? AND student_id IN ({$ph})

          GROUP BY student_id"

    );

    $params = array_merge([$term, $ay], $student_ids);

    $stmt->bind_param('ss' . $types_i, ...$params);

    $stmt->execute();

    foreach ($stmt->get_result()->fetch_all(MYSQLI_ASSOC) as $r) {

        $score_map[$r['student_id']] = (float)$r['avg_score'];

    }

    $stmt->close();

}



// ── Attendance (last 30 days) ─────────────────────────────────────────────────

$thirty    = date('Y-m-d', strtotime('-30 days'));

$att_map   = [];

$stmt = $conn->prepare(

    "SELECT student_id,

            SUM(status IN ('present','late'))  AS present_days,

            COUNT(*)                           AS total_days

       FROM attendance

      WHERE class_name = ? AND attendance_date >= ? AND student_id IN ({$ph})

      GROUP BY student_id"

);

$params = array_merge([$class_name, $thirty], $student_ids);

$stmt->bind_param('ss' . $types_i, ...$params);

$stmt->execute();

foreach ($stmt->get_result()->fetch_all(MYSQLI_ASSOC) as $r) {

    $att_map[$r['student_id']] = $r['total_days'] > 0

        ? round(($r['present_days'] / $r['total_days']) * 100, 1)

        : null;

}

$stmt->close();



// ── Homework completion (last 30 days) ────────────────────────────────────────

$hw_map = [];

$stmt = $conn->prepare(

    "SELECT hs.student_id,

            COUNT(*)                                           AS total_assigned,

            SUM(hs.status = 'submitted')                      AS submitted

       FROM homework_submissions hs

       JOIN homework h ON h.id = hs.homework_id

      WHERE h.class_name = ? AND h.due_date >= ? AND hs.student_id IN ({$ph})

      GROUP BY hs.student_id"

);

$params = array_merge([$class_name, $thirty], $student_ids);

$stmt->bind_param('ss' . $types_i, ...$params);

$stmt->execute();

foreach ($stmt->get_result()->fetch_all(MYSQLI_ASSOC) as $r) {

    $hw_map[$r['student_id']] = $r['total_assigned'] > 0

        ? round(($r['submitted'] / $r['total_assigned']) * 100, 1)

        : null;

}

$stmt->close();



// ── Open interventions count ──────────────────────────────────────────────────

$int_map = [];

$stmt = $conn->prepare(

    "SELECT student_id, COUNT(*) AS cnt

       FROM student_interventions

      WHERE student_id IN ({$ph}) AND status IN ('open','monitoring')

      GROUP BY student_id"

);

$stmt->bind_param($types_i, ...$student_ids);

$stmt->execute();

foreach ($stmt->get_result()->fetch_all(MYSQLI_ASSOC) as $r) {

    $int_map[$r['student_id']] = (int)$r['cnt'];

}

$stmt->close();



// ── Build result ──────────────────────────────────────────────────────────────

$result = [];

foreach ($students as $s) {

    $sid        = (int)$s['id'];

    $score_pct  = $score_map[$sid] ?? null;

    $att_pct    = $att_map[$sid]   ?? null;

    $hw_pct     = $hw_map[$sid]    ?? null;



    // Weighted risk score using only available metrics

    $weight_sum = 0;

    $score_sum  = 0;

    if ($score_pct !== null) { $score_sum += $score_pct * 0.5; $weight_sum += 0.5; }

    if ($att_pct   !== null) { $score_sum += $att_pct   * 0.3; $weight_sum += 0.3; }

    if ($hw_pct    !== null) { $score_sum += $hw_pct    * 0.2; $weight_sum += 0.2; }



    $risk_score = $weight_sum > 0

        ? round($score_sum / $weight_sum, 1)

        : null; // not enough data yet



    $tier = match(true) {

        $risk_score === null      => 'nodata',

        $risk_score < 40          => 'critical',

        $risk_score < 60          => 'atrisk',

        $risk_score < 75          => 'monitor',

        default                   => 'ontrack',

    };



    $result[] = [

        'id'              => $sid,

        'student_id'      => $s['student_id'],

        'name'            => trim($s['first_name'] . ' ' . $s['last_name']),

        'photo_url'       => $s['photo_path']

                             ? '../../' . ltrim($s['photo_path'], '/')

                             : '../../assets/images/default-student.png',

        'score_pct'       => $score_pct,

        'att_pct'         => $att_pct,

        'hw_pct'          => $hw_pct,

        'risk_score'      => $risk_score,

        'tier'            => $tier,

        'open_interventions' => $int_map[$sid] ?? 0,

    ];

}



// Sort: worst first (null data last)

usort($result, function ($a, $b) {

    if ($a['risk_score'] === null && $b['risk_score'] === null) return 0;

    if ($a['risk_score'] === null) return 1;

    if ($b['risk_score'] === null) return -1;

    return $a['risk_score'] <=> $b['risk_score'];

});



tp_json(true, [

    'students'   => $result,

    'class_name' => $class_name,

    'classes'    => $classes,

    'term'       => $term,

    'ay'         => $ay,

]);

