<?php
/**
 * API: Session-Management
 * POST /api/sessions {action: "join", joinCode: "ABC123", displayName: "Anna"}
 * POST /api/sessions {action: "status"}
 */

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();

if ($action === 'join') {
    $joinCode = strtoupper(trim($body['joinCode'] ?? ''));
    if (strlen($joinCode) !== 6) {
        Response::error('Ungültiger Code');
    }

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

    $displayName = mb_substr(trim($body['displayName'] ?? ''), 0, 64);
    $uuid = Session::createStudent((int)$class['id'], $displayName);

    Response::ok([
        'sessionId'  => $uuid,
        'className'  => $class['name'],
        'classId'    => (int)$class['id'],
    ]);
}

if ($action === 'status') {
    $sessionId = Session::studentId();
    if (!$sessionId) {
        Response::json(['loggedIn' => false]);
    }

    $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 = ?',
        [$sessionId]
    );

    if (!$session) {
        Response::json(['loggedIn' => false]);
    }

    // last_seen aktualisieren
    $db->execute('UPDATE student_sessions SET last_seen = NOW() WHERE id = ?', [$sessionId]);

    Response::json([
        'loggedIn'    => true,
        'sessionId'   => $sessionId,
        'displayName' => $session['display_name'],
        'classId'     => $session['class_id'],
        'className'   => $session['class_name'],
    ]);
}

Response::error('Unbekannte Aktion');
