<?php
/**
 * API: Schueler-Verwaltung (nur fuer Lehrer)
 * GET    /api/students?class_id=X   → Alle Schueler einer Klasse
 * POST   /api/students {action}     → Schueler erstellen/bearbeiten/loeschen
 */

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

if ($method === 'GET') {
    $teacherId = Session::requireTeacher();
    $classId = (int)($_GET['class_id'] ?? 0);
    if (!$classId) Response::error('class_id 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);

    $students = $db->fetchAll(
        'SELECT id, username, display_name, is_anonymous, created_at, last_login FROM students WHERE class_id = ? ORDER BY username',
        [$classId]
    );

    // Letzte Ergebnisse pro Schueler
    foreach ($students as &$s) {
        $s['results'] = $db->fetchAll(
            'SELECT module_id, score, balance_idx, completed_at FROM student_results WHERE student_id = ? ORDER BY completed_at DESC LIMIT 10',
            [$s['id']]
        );
        $s['total_score'] = $db->fetchOne(
            'SELECT AVG(score) as avg_score, COUNT(*) as count FROM student_results WHERE student_id = ?',
            [$s['id']]
        );
    }

    Response::ok($students);
}

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

    // === SCHUELER ERSTELLEN ===
    if ($action === 'create') {
        $classId = (int)($body['classId'] ?? 0);
        $username = mb_substr(trim($body['username'] ?? ''), 0, 64);
        $password = $body['password'] ?? '';
        $displayName = mb_substr(trim($body['displayName'] ?? ''), 0, 128);
        $isAnonymous = (bool)($body['isAnonymous'] ?? true);

        if (!$classId || !$username || !$password) Response::error('classId, username und password erforderlich');
        if (strlen($password) < 4) Response::error('Passwort muss mindestens 4 Zeichen lang sein');

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

        // Username eindeutig in Klasse?
        $existing = $db->fetchOne('SELECT id FROM students WHERE class_id = ? AND username = ?', [$classId, $username]);
        if ($existing) Response::error('Benutzername in dieser Klasse bereits vergeben');

        $hash = password_hash($password, PASSWORD_DEFAULT);
        $db->execute(
            'INSERT INTO students (class_id, username, password, display_name, is_anonymous) VALUES (?, ?, ?, ?, ?)',
            [$classId, $username, $hash, $displayName ?: null, $isAnonymous ? 1 : 0]
        );
        Response::ok(['id' => (int)$db->lastInsertId()]);
    }

    // === MEHRERE SCHUELER AUF EINMAL ERSTELLEN ===
    if ($action === 'create_batch') {
        $classId = (int)($body['classId'] ?? 0);
        $count = min(50, max(1, (int)($body['count'] ?? 10)));
        $prefix = mb_substr(trim($body['prefix'] ?? 'schueler'), 0, 20);

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

        $created = [];
        for ($i = 1; $i <= $count; $i++) {
            $username = $prefix . str_pad($i, 2, '0', STR_PAD_LEFT);
            // Einfaches Passwort generieren (4 Ziffern)
            $pw = str_pad(random_int(1000, 9999), 4, '0', STR_PAD_LEFT);
            $hash = password_hash($pw, PASSWORD_DEFAULT);

            $existing = $db->fetchOne('SELECT id FROM students WHERE class_id = ? AND username = ?', [$classId, $username]);
            if ($existing) continue; // Ueberspringen wenn schon vorhanden

            $db->execute(
                'INSERT INTO students (class_id, username, password, display_name, is_anonymous) VALUES (?, ?, ?, ?, 1)',
                [$classId, $username, $hash, $username]
            );
            $created[] = ['username' => $username, 'password' => $pw, 'id' => (int)$db->lastInsertId()];
        }
        Response::ok(['created' => $created]);
    }

    // === SCHUELER BEARBEITEN ===
    if ($action === 'update') {
        $studentId = (int)($body['studentId'] ?? 0);
        $displayName = mb_substr(trim($body['displayName'] ?? ''), 0, 128);
        $newPassword = $body['newPassword'] ?? '';

        // Schueler + Klasse pruefen
        $student = $db->fetchOne(
            'SELECT s.id, s.class_id FROM students s JOIN classes c ON c.id = s.class_id WHERE s.id = ? AND c.teacher_id = ?',
            [$studentId, $teacherId]
        );
        if (!$student) Response::error('Schüler nicht gefunden', 404);

        if ($displayName) {
            $db->execute('UPDATE students SET display_name = ? WHERE id = ?', [$displayName, $studentId]);
        }
        if ($newPassword && strlen($newPassword) >= 4) {
            $db->execute('UPDATE students SET password = ? WHERE id = ?', [password_hash($newPassword, PASSWORD_DEFAULT), $studentId]);
        }
        Response::ok();
    }

    // === SCHUELER LOESCHEN ===
    if ($action === 'delete') {
        $studentId = (int)($body['studentId'] ?? 0);
        $student = $db->fetchOne(
            'SELECT s.id FROM students s JOIN classes c ON c.id = s.class_id WHERE s.id = ? AND c.teacher_id = ?',
            [$studentId, $teacherId]
        );
        if (!$student) Response::error('Schüler nicht gefunden', 404);

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

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

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