<?php
/**
 * API: Authentifizierung (Lehrer + Schueler)
 * POST /api/auth {action: "register"|"login"|"logout"|"student_login"|"reset_request"|"reset_confirm"}
 */

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

$body = json_decode(file_get_contents('php://input'), true);
$action = $body['action'] ?? '';
$db = Database::get();

// === LEHRER-REGISTRIERUNG ===
if ($action === 'register') {
    $email = trim($body['email'] ?? '');
    $password = $body['password'] ?? '';
    $displayName = mb_substr(trim($body['displayName'] ?? ''), 0, 128);
    $schoolName = mb_substr(trim($body['schoolName'] ?? ''), 0, 255);

    if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) Response::error('Gültige E-Mail-Adresse erforderlich');
    if (strlen($password) < 8) Response::error('Passwort muss mindestens 8 Zeichen lang sein');
    if (!$displayName) Response::error('Name erforderlich');

    // Pruefen ob E-Mail schon existiert
    $existing = $db->fetchOne('SELECT id FROM teachers WHERE email = ?', [$email]);
    if ($existing) Response::error('Diese E-Mail-Adresse ist bereits registriert');

    $username = strtolower(explode('@', $email)[0]) . '_' . rand(100, 999);
    $hash = password_hash($password, PASSWORD_DEFAULT);

    $db->execute(
        'INSERT INTO teachers (username, email, password, display_name, school_name) VALUES (?, ?, ?, ?, ?)',
        [$username, $email, $hash, $displayName, $schoolName]
    );

    $teacherId = (int)$db->lastInsertId();
    Session::start();
    Session::loginTeacher($teacherId);

    Response::ok([
        'teacherId' => $teacherId,
        'displayName' => $displayName,
    ]);
}

// === LEHRER-LOGIN ===
if ($action === 'login') {
    $email = trim($body['email'] ?? '');
    $password = $body['password'] ?? '';

    if (!$email || !$password) Response::error('E-Mail und Passwort erforderlich');

    $teacher = $db->fetchOne(
        'SELECT id, password, display_name FROM teachers WHERE email = ? OR username = ?',
        [$email, $email]
    );

    if (!$teacher || !password_verify($password, $teacher['password'])) {
        Response::error('E-Mail oder Passwort falsch');
    }

    Session::start();
    Session::loginTeacher((int)$teacher['id']);

    $db->execute(
        "INSERT INTO activity_log (user_type, user_id, action) VALUES ('teacher', ?, 'login')",
        [$teacher['id']]
    );

    Response::ok([
        'teacherId' => (int)$teacher['id'],
        'displayName' => $teacher['display_name'],
    ]);
}

// === LOGOUT ===
if ($action === 'logout') {
    Session::logout();
    Response::ok();
}

// === SCHUELER-LOGIN ===
if ($action === 'student_login') {
    $classCode = strtoupper(trim($body['classCode'] ?? ''));
    $username = trim($body['username'] ?? '');
    $password = $body['password'] ?? '';

    if (!$classCode || !$username || !$password) Response::error('Klassencode, Benutzername und Passwort erforderlich');

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

    $student = $db->fetchOne(
        'SELECT id, password, display_name FROM students WHERE class_id = ? AND username = ?',
        [$class['id'], $username]
    );

    if (!$student || !password_verify($password, $student['password'])) {
        Response::error('Benutzername oder Passwort falsch');
    }

    // Schueler-Session erstellen
    $sessionId = Session::createStudent((int)$class['id'], $student['display_name'] ?: $username);

    $db->execute('UPDATE students SET last_login = NOW() WHERE id = ?', [$student['id']]);
    $db->execute(
        "INSERT INTO activity_log (user_type, user_id, action) VALUES ('student', ?, 'login')",
        [$student['id']]
    );

    Response::ok([
        'sessionId' => $sessionId,
        'studentId' => (int)$student['id'],
        'displayName' => $student['display_name'] ?: $username,
        'className' => $class['name'] ?? '',
    ]);
}

// === STATUS ===
if ($action === 'status') {
    Session::start();
    $teacherId = Session::teacherId();
    $studentId = Session::studentId();

    if ($teacherId) {
        $teacher = $db->fetchOne('SELECT id, display_name, email, school_name FROM teachers WHERE id = ?', [$teacherId]);
        Response::ok(['role' => 'teacher', 'user' => $teacher]);
    }
    if ($studentId) {
        $session = $db->fetchOne(
            'SELECT s.display_name, s.class_id, c.name as class_name FROM student_sessions s LEFT JOIN classes c ON c.id = s.class_id WHERE s.id = ?',
            [$studentId]
        );
        Response::ok(['role' => 'student', 'session' => $session]);
    }
    Response::ok(['role' => 'guest']);
}

Response::error('Unbekannte Aktion');
