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

$day_abbr   = date('D'); // Mon, Tue, Wed, Thu, Fri, Sat

$today      = date('Y-m-d');

$now_time   = date('H:i:s');



// ── Today's timetable slots ────────────────────────────────────────────────

$slots = [];

$tt_stmt = $conn->prepare(

    "SELECT ts.id, ts.class_name, ts.room,

            tp.period_name, tp.start_time, tp.end_time, tp.is_break,

            COALESCE(s.subject_name, '') AS subject_name

       FROM timetable_slots ts

       JOIN timetable_periods tp ON tp.id = ts.period_id

       LEFT JOIN subjects s      ON s.id  = ts.subject_id

      WHERE ts.teacher_id   = ?

        AND ts.day_of_week  = ?

        AND ts.academic_year= ?

      ORDER BY tp.start_time ASC"

);

if ($tt_stmt) {

    $tt_stmt->bind_param('iss', $teacher_id, $day_abbr, $ay);

    $tt_stmt->execute();

    $slots = $tt_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

    $tt_stmt->close();

}



// Mark current / upcoming slot

$current_slot = null;

$next_slot    = null;

foreach ($slots as &$slot) {

    $slot['status'] = 'upcoming';

    if ($slot['is_break']) { $slot['status'] = 'break'; continue; }

    if ($now_time >= $slot['start_time'] && $now_time <= $slot['end_time']) {

        $slot['status'] = 'active';

        $current_slot   = $slot;

    } elseif ($now_time < $slot['start_time'] && !$next_slot) {

        $slot['status'] = 'next';

        $next_slot      = $slot;

    } elseif ($now_time > $slot['end_time']) {

        $slot['status'] = 'done';

    }

}

unset($slot);



// ── Attendance already taken today? (per class) ────────────────────────────

$classes = tp_teacher_classes($teacher_id);

$att_done = [];

if (!empty($classes)) {

    $placeholders = implode(',', array_fill(0, count($classes), '?'));

    $types = str_repeat('s', count($classes));

    $stmt = $conn->prepare(

        "SELECT DISTINCT class_name FROM attendance

          WHERE attendance_date = ? AND class_name IN ({$placeholders})"

    );

    $bind = array_merge([$today], $classes);

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

    $stmt->execute();

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

    $stmt->close();

    $att_done = array_column($rows, 'class_name');

}



// ── Homework due today/overdue needing marking ────────────────────────────

$homework_pending = [];

$hw_stmt = $conn->prepare(

    "SELECT h.id, h.title, h.class_name, h.subject_name, h.due_date,

            COUNT(st.id) AS total_students,

            COALESCE(SUM(CASE WHEN hs.status='submitted' THEN 1 ELSE 0 END),0) AS submitted,

            COALESCE(SUM(CASE WHEN hs.status='pending'   THEN 1 ELSE 0 END),0) AS pending_mark

       FROM homework h

       JOIN students st ON st.class = h.class_name AND st.status = 'active'

       LEFT JOIN homework_submissions hs ON hs.homework_id = h.id AND hs.student_id = st.id

      WHERE h.teacher_id = ?

        AND h.status     = 'active'

        AND h.due_date  <= ?

      GROUP BY h.id

      ORDER BY h.due_date ASC

      LIMIT 5"

);

if ($hw_stmt) {

    $hw_stmt->bind_param('is', $teacher_id, $today);

    $hw_stmt->execute();

    $homework_pending = $hw_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

    $hw_stmt->close();

}



// ── Unread announcements count ─────────────────────────────────────────────

$notice_count = 0;

$nr = $conn->query(

    "SELECT COUNT(*) AS n FROM announcements

      WHERE target_role IN ('all','tutor')

        AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)"

);

if ($nr) $notice_count = (int)($nr->fetch_assoc()['n'] ?? 0);



// ── Quick stats ────────────────────────────────────────────────────────────

$teaching_slots = array_filter($slots, fn($s) => !$s['is_break']);

$done_slots     = array_filter($slots, fn($s) => $s['status'] === 'done');



tp_json(true, [

    'date'             => date('l, j F Y'),

    'day'              => date('l'),

    'slots'            => array_values($slots),

    'current_slot'     => $current_slot,

    'next_slot'        => $next_slot,

    'teaching_today'   => count($teaching_slots),

    'done_today'       => count($done_slots),

    'classes'          => $classes,

    'attendance_done'  => $att_done,

    'homework_pending' => $homework_pending,

    'notice_count'     => $notice_count,

]);

