>} */ public function for(Poll $poll, bool $withTexts): array { $answers = $poll->responses()->pluck('answers')->map(fn ($a) => is_array($a) ? $a : (json_decode((string) $a, true) ?: [])); $total = $answers->count(); return [ 'total' => $total, 'questions' => collect($poll->questions)->map(function (array $question) use ($answers, $withTexts) { $given = $answers->map(fn ($a) => $a[$question['id']] ?? null)->filter(fn ($v) => $v !== null && $v !== []); $count = $given->count(); $result = ['id' => $question['id'], 'type' => $question['type'], 'label' => $question['label'], 'answered' => $count]; if (in_array($question['type'], ['single', 'multiple'], true)) { $tally = $given->flatMap(fn ($v) => (array) $v)->countBy(); $result['options'] = collect($question['options'])->map(fn ($o) => [ 'id' => $o['id'], 'label' => $o['label'], 'votes' => (int) ($tally[$o['id']] ?? 0), 'percent' => $count ? (int) round(($tally[$o['id']] ?? 0) / $count * 100) : 0, ])->all(); } if ($question['type'] === 'scale') { $tally = $given->countBy(); $result['scale'] = $question['scale']; $result['min_label'] = $question['min_label'] ?? null; $result['max_label'] = $question['max_label'] ?? null; $result['average'] = $count ? round($given->avg(), 1) : null; $result['distribution'] = collect(range(1, $question['scale']))->map(fn ($n) => ['value' => $n, 'votes' => (int) ($tally[$n] ?? 0)])->all(); } if ($question['type'] === 'text') { // Freitexte nur für die Redaktion – sie können Rückschlüsse auf Personen erlauben $result['texts'] = $withTexts ? $given->values()->shuffle()->take(500)->values()->all() : null; } return $result; })->all(), ]; } }