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

$stmt = $conn->prepare(
    "SELECT ts.id, ts.class_name, ts.day_of_week, ts.room,
            ts.period_id,
            tp.period_name, tp.start_time, tp.end_time, tp.is_break,
            tp.order_no,
            COALESCE(s.subject_name, '') AS subject_name,
            COALESCE(s.subject_code, '') AS subject_code
       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.academic_year = ?
      ORDER BY FIELD(ts.day_of_week,'Mon','Tue','Wed','Thu','Fri','Sat'),
               tp.order_no, tp.start_time"
);
$stmt->bind_param('is', $teacher_id, $ay);
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// Group by day
$days = ['Mon','Tue','Wed','Thu','Fri','Sat'];
$by_day = array_fill_keys($days, []);
foreach ($rows as $row) {
    $by_day[$row['day_of_week']][] = $row;
}

// Get all unique periods for row headers
$all_periods = [];
$seen_periods = [];
foreach ($rows as $r) {
    if (!isset($seen_periods[$r['period_id']])) {
        $seen_periods[$r['period_id']] = true;
        $all_periods[] = [
            'id'          => $r['period_id'],
            'period_name' => $r['period_name'],
            'start_time'  => $r['start_time'],
            'end_time'    => $r['end_time'],
            'is_break'    => $r['is_break'],
            'order_no'    => $r['order_no'],
        ];
    }
}
usort($all_periods, fn($a, $b) => $a['order_no'] <=> $b['order_no']);

tp_json(true, [
    'days'        => $days,
    'by_day'      => $by_day,
    'all_periods' => $all_periods,
    'academic_year' => $ay,
    'term'          => $term,
    'today_day'     => date('D'),
]);
