<?php
/**
 * API: Assessment-Daten speichern
 * POST /api/assessment {simId, processLog, predictions, results, reflections, duration, completedPhases}
 */

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

$sessionId = Session::requireStudent();
$body = json_decode(file_get_contents('php://input'), true);
if (!$body || !isset($body['simId'])) {
    Response::error('simId erforderlich');
}

$db = Database::get();

// class_id aus student_session holen
$session = $db->fetchOne('SELECT class_id FROM student_sessions WHERE id = ?', [$sessionId]);
$classId = $session ? $session['class_id'] : null;

$db->execute(
    'INSERT INTO assessments (session_id, sim_id, class_id, process_log, predictions, results, reflections, duration_ms, completed_phases)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
    [
        $sessionId,
        $body['simId'],
        $classId,
        json_encode($body['processLog'] ?? []),
        json_encode($body['predictions'] ?? []),
        json_encode($body['results'] ?? []),
        json_encode($body['reflections'] ?? []),
        $body['duration'] ?? 0,
        json_encode($body['completedPhases'] ?? []),
    ]
);

Response::ok(['id' => $db->lastInsertId()]);
