<?php
/**
 * API: Modulfreigabe (Lehrer steuert welche Module Schueler sehen/spielen)
 * GET  /api/modules?class_id=X     → Modulstatus fuer Klasse
 * POST /api/modules {action}        → Modul freigeben/sperren/starten
 */

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

// Alle verfuegbaren Module
$ALL_MODULES = [
    ['id' => 'sim-05', 'name' => 'Klimawächter', 'desc' => 'Treibhauseffekt-Simulation'],
    ['id' => 'sim-05-3d', 'name' => 'Klimawächter 3D', 'desc' => '3D-Version der Klimasimulation'],
    ['id' => 'sim-07', 'name' => 'Erdbeben', 'desc' => 'Plattentektonik und Stadtplanung'],
    ['id' => 'sim-09', 'name' => 'Energiemix', 'desc' => 'Energiewende planen'],
    ['id' => 'sim-10', 'name' => 'Lieferketten', 'desc' => 'Globale Lieferketten verstehen'],
    ['id' => 'sim-11', 'name' => 'Regenwald', 'desc' => 'Regenwald-Exploration'],
    ['id' => 'sim-12', 'name' => 'Flussmanagement', 'desc' => 'Fluss und Hochwasserschutz'],
    ['id' => 'sim-13', 'name' => 'Stadt & Raumplanung', 'desc' => 'Stadtsimulation mit Kacheln'],
];

if ($method === 'GET') {
    $teacherId = Session::requireTeacher();
    $classId = (int)($_GET['class_id'] ?? 0);
    if (!$classId) Response::error('class_id erforderlich');

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

    // Aktuelle Freigaben laden
    $settings = $db->fetchAll('SELECT module_id, mode, started_at, due_date FROM class_modules WHERE class_id = ?', [$classId]);
    $settingsMap = [];
    foreach ($settings as $s) $settingsMap[$s['module_id']] = $s;

    // Mit allen Modulen zusammenfuehren
    $result = [];
    foreach ($ALL_MODULES as $mod) {
        $s = $settingsMap[$mod['id']] ?? null;
        $result[] = [
            'id' => $mod['id'],
            'name' => $mod['name'],
            'desc' => $mod['desc'],
            'mode' => $s['mode'] ?? 'locked',
            'startedAt' => $s['started_at'] ?? null,
            'dueDate' => $s['due_date'] ?? null,
        ];
    }
    Response::ok($result);
}

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

    if (!$classId || !$moduleId) Response::error('classId und moduleId erforderlich');

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

    if ($action === 'set_mode') {
        $mode = $body['mode'] ?? 'locked';
        if (!in_array($mode, ['locked', 'free', 'teacher_started'])) Response::error('Ungültiger Modus');

        $dueDate = $body['dueDate'] ?? null;

        $db->execute(
            'INSERT INTO class_modules (class_id, module_id, enabled, mode, started_at, due_date)
             VALUES (?, ?, ?, ?, NOW(), ?)
             ON DUPLICATE KEY UPDATE mode = VALUES(mode), started_at = VALUES(started_at), due_date = VALUES(due_date), enabled = 1',
            [$classId, $moduleId, 1, $mode, $dueDate]
        );

        $db->execute(
            "INSERT INTO activity_log (user_type, user_id, action, detail) VALUES ('teacher', ?, 'set_module_mode', ?)",
            [$teacherId, "$moduleId → $mode"]
        );

        Response::ok();
    }

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

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