<?php
/**
 * API: Lehrkraefte-Dashboard Daten
 * GET /api/dashboard?class_id=X
 */

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    Response::error('Nur GET erlaubt', 405);
}

$teacherId = Session::requireTeacher();
$db = Database::get();

$classId = (int)($_GET['class_id'] ?? 0);

// Verifizieren dass die Klasse dem Lehrer gehoert
if ($classId) {
    $class = $db->fetchOne(
        'SELECT id, name, school_year, join_code, created_at FROM classes WHERE id = ? AND teacher_id = ?',
        [$classId, $teacherId]
    );
    if (!$class) Response::error('Klasse nicht gefunden', 404);
}

// Klassen des Lehrers
$classes = $db->fetchAll('SELECT id, name, school_year, join_code, created_at FROM classes WHERE teacher_id = ? ORDER BY created_at DESC', [$teacherId]);

if (!$classId && !empty($classes)) {
    $classId = $classes[0]['id'];
}

// Aktive Schueler (letzte 60 Minuten)
$activeStudents = $db->fetchAll(
    'SELECT id, display_name, last_seen FROM student_sessions
     WHERE class_id = ? AND last_seen > DATE_SUB(NOW(), INTERVAL 60 MINUTE)
     ORDER BY last_seen DESC',
    [$classId]
);

// Alle Schueler der Klasse
$allStudents = $db->fetchAll(
    'SELECT id, display_name, created_at, last_seen FROM student_sessions WHERE class_id = ? ORDER BY display_name',
    [$classId]
);

// Assessments fuer diese Klasse
$assessments = $db->fetchAll(
    'SELECT a.*, s.display_name FROM assessments a
     JOIN student_sessions s ON s.id = a.session_id
     WHERE a.class_id = ?
     ORDER BY a.submitted_at DESC
     LIMIT 100',
    [$classId]
);

// Modulfreigaben
$modules = $db->fetchAll('SELECT * FROM class_modules WHERE class_id = ?', [$classId]);

Response::ok([
    'classes'        => $classes,
    'currentClassId' => $classId,
    'activeStudents' => $activeStudents,
    'allStudents'    => $allStudents,
    'assessments'    => $assessments,
    'modules'        => $modules,
]);
