<?php
/**
 * API: Klassenverwaltung (nur fuer Lehrer)
 * GET    /api/classes              → Alle Klassen des Lehrers
 * POST   /api/classes {action}     → Klasse erstellen/bearbeiten/loeschen
 */

$method = $_SERVER['REQUEST_METHOD'];
$db = Database::get();

if ($method === 'GET') {
    $teacherId = Session::requireTeacher();
    $classes = $db->fetchAll(
        'SELECT id, name, school_year, join_code, created_at FROM classes WHERE teacher_id = ? ORDER BY created_at DESC',
        [$teacherId]
    );
    // Schueleranzahl pro Klasse
    foreach ($classes as &$c) {
        $c['student_count'] = (int)$db->fetchOne(
            'SELECT COUNT(*) as cnt FROM students WHERE class_id = ?', [$c['id']]
        )['cnt'];
    }
    Response::ok($classes);
}

if ($method === 'POST') {
    $teacherId = Session::requireTeacher();
    $body = json_decode(file_get_contents('php://input'), true);
    $action = $body['action'] ?? '';

    // === KLASSE ERSTELLEN ===
    if ($action === 'create') {
        $name = mb_substr(trim($body['name'] ?? ''), 0, 64);
        $schoolYear = mb_substr(trim($body['schoolYear'] ?? ''), 0, 10);
        if (!$name) Response::error('Klassenname erforderlich');

        // Join-Code generieren (6 Zeichen, eindeutig)
        $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // ohne I,O,0,1 (Verwechslungsgefahr)
        do {
            $code = '';
            for ($i = 0; $i < 6; $i++) $code .= $chars[random_int(0, strlen($chars) - 1)];
            $exists = $db->fetchOne('SELECT id FROM classes WHERE join_code = ?', [$code]);
        } while ($exists);

        $db->execute(
            'INSERT INTO classes (teacher_id, name, school_year, join_code) VALUES (?, ?, ?, ?)',
            [$teacherId, $name, $schoolYear, $code]
        );
        Response::ok(['id' => (int)$db->lastInsertId(), 'joinCode' => $code]);
    }

    // === KLASSE BEARBEITEN ===
    if ($action === 'update') {
        $classId = (int)($body['classId'] ?? 0);
        $name = mb_substr(trim($body['name'] ?? ''), 0, 64);
        $schoolYear = mb_substr(trim($body['schoolYear'] ?? ''), 0, 10);
        if (!$classId || !$name) Response::error('classId und name erforderlich');

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

        $db->execute('UPDATE classes SET name = ?, school_year = ? WHERE id = ?', [$name, $schoolYear, $classId]);
        Response::ok();
    }

    // === KLASSE LOESCHEN ===
    if ($action === 'delete') {
        $classId = (int)($body['classId'] ?? 0);
        $class = $db->fetchOne('SELECT id FROM classes WHERE id = ? AND teacher_id = ?', [$classId, $teacherId]);
        if (!$class) Response::error('Klasse nicht gefunden', 404);

        $db->execute('DELETE FROM classes WHERE id = ?', [$classId]);
        Response::ok();
    }

    Response::error('Unbekannte Aktion');
}

Response::error('Methode nicht erlaubt', 405);
