<?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']   ?? '');

$subject_id = (int)($_GET['subject'] ?? 0);

$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 st.id, st.student_id, st.first_name, st.last_name,

            st.photo_path, st.phone AS parent_phone, st.parent_name

       FROM students st

      WHERE st.class = ? AND st.status = 'active'

      ORDER BY st.first_name, st.last_name"

);

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

$stmt->execute();

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

$stmt->close();



foreach ($students as &$s) {

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

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

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

}

unset($s);



// ── Subjects assigned to teacher for this class (class_subjects + timetable) ──

$stmt = $conn->prepare(

    "SELECT subject_id, subject_name, subject_code,

            max_class_score, max_exam_score,

            class_score_percent, exam_score_percent,

            configured

       FROM (

           SELECT cs.subject_id, s.subject_name, s.subject_code,

                  cs.max_class_score, cs.max_exam_score,

                  cs.class_score_percent, cs.exam_score_percent,

                  1 AS configured

             FROM class_subjects cs

             JOIN subjects s ON s.id = cs.subject_id

            WHERE cs.class_name = ? AND cs.teacher_id = ?



           UNION



           SELECT ts.subject_id, s.subject_name, s.subject_code,

                  100.0 AS max_class_score, 100.0 AS max_exam_score,

                  30 AS class_score_percent, 70 AS exam_score_percent,

                  0 AS configured

             FROM timetable_slots ts

             JOIN subjects s ON s.id = ts.subject_id

            WHERE ts.class_name    = ?

              AND ts.teacher_id    = ?

              AND ts.subject_id   IS NOT NULL

              AND ts.academic_year = ?

              AND NOT EXISTS (

                  SELECT 1 FROM class_subjects cx

                   WHERE cx.class_name = ts.class_name

                     AND cx.subject_id = ts.subject_id

                     AND cx.teacher_id = ?

              )

       ) AS combined

       ORDER BY subject_name"

);

$stmt->bind_param('sisisi', $class_name, $teacher_id, $class_name, $teacher_id, $ay, $teacher_id);

$stmt->execute();

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

$stmt->close();



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

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

$stmt = $conn->prepare(

    "SELECT student_id,

            SUM(status = 'present')  AS present_days,

            SUM(status = 'absent')   AS absent_days,

            SUM(status = 'late')     AS late_days,

            SUM(status = 'excused')  AS excused_days,

            COUNT(*)                 AS total_days

       FROM attendance

      WHERE class_name = ? AND attendance_date >= ?

      GROUP BY student_id"

);

$stmt->bind_param('ss', $class_name, $thirty);

$stmt->execute();

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

$stmt->close();



$att_map = [];

foreach ($att_rows as $r) {

    $att_map[$r['student_id']] = $r;

}



foreach ($students as &$s) {

    $a = $att_map[$s['id']] ?? null;

    $s['att_present'] = $a ? (int)$a['present_days'] : 0;

    $s['att_absent']  = $a ? (int)$a['absent_days']  : 0;

    $s['att_late']    = $a ? (int)$a['late_days']     : 0;

    $s['att_total']   = $a ? (int)$a['total_days']    : 0;

    $s['att_pct']     = ($s['att_total'] > 0)

                        ? round(($s['att_present'] / $s['att_total']) * 100)

                        : null;

}

unset($s);



// ── Scores: use selected subject when provided, otherwise all teacher subjects ─

$all_subject_ids = array_column($subjects, 'subject_id');

$query_ids       = ($subject_id > 0 && in_array($subject_id, $all_subject_ids))

                   ? [$subject_id]

                   : $all_subject_ids;



$scores_map = [];

if (!empty($query_ids)) {

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

    $types = 'ss' . str_repeat('i', count($query_ids));

    $stmt  = $conn->prepare(

        "SELECT sc.student_id, sc.subject_id,

                sc.total_score, sc.grade, sc.remark

           FROM scores sc

          WHERE sc.term = ? AND sc.academic_year = ?

            AND sc.subject_id IN ({$ph})

            AND sc.student_id IN (

                SELECT id FROM students WHERE class = ? AND status = 'active'

            )"

    );

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

    $stmt->bind_param($types . 's', ...$params);

    $stmt->execute();

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

    $stmt->close();



    foreach ($score_rows as $r) {

        $scores_map[$r['student_id']][$r['subject_id']] = [

            'total' => $r['total_score'],

            'grade' => $r['grade'],

        ];

    }

}



foreach ($students as &$s) {

    $s['scores'] = $scores_map[$s['id']] ?? [];

}

unset($s);



tp_json(true, [

    'class_name'    => $class_name,

    'classes'       => $classes,

    'students'      => $students,

    'subjects'      => $subjects,

    'subject_id'    => $subject_id,

    'term'          => $term,

    'academic_year' => $ay,

    'att_from'      => $thirty,

]);

