        if ($isRight) $score++;
        $detailed[] = [
            'question_id' => $qid,
            'given'       => $given,
            'correct'     => $correct,
            'is_correct'  => $isRight,
            'explanation' => $correctMap[$qid]['explanation'] ?? '',
        ];
    }

    // Save result
    $stmt = $db->prepare('INSERT INTO quiz_results (user_id, entity_type, entity_id, score, total, answers) VALUES (?,?,?,?,?,?)');
    $stmt->execute([$userId, $type, $id, $score, $total, json_encode($detailed)]);
    $resultId = $db->lastInsertId();

    echo json_encode([
        'result_id' => $resultId,
        'score'     => $score,
        'total'     => $total,
        'percentage'=> $total > 0 ? round($score / $total * 100) : 0,
        'details'   => $detailed,
    ]);
    exit;
}

// ── GET /api/quiz.php?action=history&type=event&id=1 ──────────────────────
if ($method === 'GET' && $action === 'history') {
    $type = $_GET['type'] ?? '';
    $id   = (int)($_GET['id'] ?? 0);
    if (!in_array($type, ['event', 'person']) || $id < 1) {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid type or id']);
        exit;
    }
    $stmt = $db->prepare('SELECT id, score, total, taken_at FROM quiz_results WHERE user_id = ? AND entity_type = ? AND entity_id = ? ORDER BY taken_at DESC LIMIT 5');
    $stmt->execute([$userId, $type, $id]);
    $history = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode(['history' => $history]);
    exit;
}

// ── GET /api/quiz.php?action=all_results ──────────────────────────────────
if ($method === 'GET' && $action === 'all_results') {
    $stmt = $db->prepare('
        SELECT qr.entity_type, qr.entity_id, qr.score, qr.total, qr.taken_at,
               e.title as event_title, p.name as person_name
        FROM quiz_results qr
        LEFT JOIN events e ON qr.entity_type = \'event\' AND qr.entity_id = e.id
        LEFT JOIN people p ON qr.entity_type = \'person\' AND qr.entity_id = p.id
        WHERE qr.user_id = ?
        ORDER BY qr.taken_at DESC
