<?php

declare(strict_types=1);

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once dirname(__DIR__) . '/app-support.php';

if (!isset($_SESSION['survey_csrf'])) {
    $_SESSION['survey_csrf'] = bin2hex(random_bytes(24));
}

function survey_h(string $value): string
{
    return app_h($value);
}

function survey_dt(?string $value): string
{
    if ($value === null || trim($value) === '') {
        return '-';
    }

    $time = strtotime($value);

    return $time === false ? $value : date('d.m.Y H:i', $time);
}

function survey_options_from_storage(?string $raw, string $type): array
{
    if ($raw !== null && trim($raw) !== '') {
        $decoded = json_decode($raw, true);
        if (is_array($decoded)) {
            return array_values(array_filter(array_map(static fn(mixed $item): string => trim((string) $item), $decoded)));
        }
    }

    if ($type === 'scale') {
        return ['1', '2', '3', '4', '5'];
    }

    return [];
}

function survey_option_text_to_json(string $raw, string $type): ?string
{
    $lines = preg_split('/\R+/', trim($raw)) ?: [];
    $options = array_values(array_filter(array_map('trim', $lines)));

    if ($options === [] && $type === 'scale') {
        $options = ['1', '2', '3', '4', '5'];
    }

    return $options === [] ? null : json_encode($options, JSON_UNESCAPED_UNICODE);
}

function survey_publications_ready(PDO $pdo): bool
{
    return scripts_table_exists($pdo, 'survey_publications');
}

function survey_fetch_questions(PDO $pdo, string $surveyId): array
{
    $hasOptions = app_table_has_column($pdo, 'survey_questions', 'options_json');
    $questionSelect = $hasOptions ? 'options_json' : 'NULL AS options_json';

    $questions = app_query_all(
        $pdo,
        str_replace(
            '__OPTIONS__',
            $questionSelect,
            <<<'SQL'
SELECT id, question, question_type, is_required, sort_order, __OPTIONS__
FROM survey_questions
WHERE survey_id = :survey_id
ORDER BY sort_order ASC, created_at ASC
SQL
        ),
        ['survey_id' => $surveyId]
    );

    foreach ($questions as &$question) {
        $question['options'] = survey_options_from_storage((string) ($question['options_json'] ?? ''), (string) ($question['question_type'] ?? 'text'));
    }
    unset($question);

    return $questions;
}

function survey_build_results(PDO $pdo, array $questions, string $surveyId): array
{
    $results = [];

    foreach ($questions as $question) {
        $questionId = (string) ($question['id'] ?? '');
        $questionType = (string) ($question['question_type'] ?? 'text');
        $entries = [];

        if ($questionType === 'text') {
            $entries = app_query_all(
                $pdo,
                'SELECT answer_text, created_at FROM survey_answers WHERE survey_id = :survey_id AND question_id = :question_id AND answer_text <> "" ORDER BY created_at DESC LIMIT 5',
                ['survey_id' => $surveyId, 'question_id' => $questionId]
            );
        } elseif ($questionType === 'multi_select') {
            $summary = [];
            foreach (app_query_all(
                $pdo,
                'SELECT answer_text FROM survey_answers WHERE survey_id = :survey_id AND question_id = :question_id ORDER BY created_at ASC',
                ['survey_id' => $surveyId, 'question_id' => $questionId]
            ) as $answer) {
                $answerText = trim((string) ($answer['answer_text'] ?? ''));
                if ($answerText === '') {
                    continue;
                }

                foreach (array_filter(array_map('trim', preg_split('/\R+/', str_replace([",", "\r\n"], "\n", $answerText)) ?: [])) as $item) {
                    $summary[$item] = ($summary[$item] ?? 0) + 1;
                }
            }

            $options = is_array($question['options'] ?? null) ? array_values(array_map('strval', $question['options'])) : [];
            $orderedSummary = [];
            if ($options !== []) {
                foreach ($options as $option) {
                    $orderedSummary[$option] = $summary[$option] ?? 0;
                }
                foreach ($summary as $label => $count) {
                    if (!array_key_exists($label, $orderedSummary)) {
                        $orderedSummary[$label] = $count;
                    }
                }
            } else {
                ksort($summary);
                $orderedSummary = $summary;
            }

            foreach ($orderedSummary as $label => $count) {
                $entries[] = [
                    'answer_text' => $label,
                    'answer_count' => $count,
                ];
            }
        } else {
            $entries = app_query_all(
                $pdo,
                'SELECT answer_text, COUNT(*) AS answer_count FROM survey_answers WHERE survey_id = :survey_id AND question_id = :question_id GROUP BY answer_text ORDER BY answer_count DESC, answer_text ASC',
                ['survey_id' => $surveyId, 'question_id' => $questionId]
            );
        }

        $results[] = [
            'question' => $question,
            'entries' => $entries,
        ];
    }

    return $results;
}

function survey_build_snapshot(PDO $pdo, array $survey): array
{
    $questions = is_array($survey['questions'] ?? null) ? $survey['questions'] : [];
    $surveyId = (string) ($survey['id'] ?? '');

    return [
        'survey' => [
            'id' => $surveyId,
            'tenant_id' => (string) ($survey['tenant_id'] ?? ''),
            'title' => (string) ($survey['title'] ?? ''),
            'status' => (string) ($survey['status'] ?? 'draft'),
            'starts_at' => (string) ($survey['starts_at'] ?? ''),
            'ends_at' => (string) ($survey['ends_at'] ?? ''),
            'created_at' => (string) ($survey['created_at'] ?? ''),
            'updated_at' => (string) ($survey['updated_at'] ?? ''),
        ],
        'questions' => array_map(static function (array $question): array {
            return [
                'id' => (string) ($question['id'] ?? ''),
                'question' => (string) ($question['question'] ?? ''),
                'question_type' => (string) ($question['question_type'] ?? 'text'),
                'is_required' => (int) ($question['is_required'] ?? 0),
                'sort_order' => (int) ($question['sort_order'] ?? 0),
                'options' => is_array($question['options'] ?? null) ? array_values($question['options']) : [],
            ];
        }, $questions),
        'results' => survey_build_results($pdo, $questions, $surveyId),
    ];
}

function survey_decode_publication_row(array $row): array
{
    $snapshot = json_decode((string) ($row['snapshot_json'] ?? '[]'), true);
    $results = json_decode((string) ($row['results_json'] ?? '[]'), true);

    return [
        'id' => (string) ($row['id'] ?? ''),
        'survey_id' => (string) ($row['survey_id'] ?? ''),
        'tenant_id' => (string) ($row['tenant_id'] ?? ''),
        'version_no' => (int) ($row['version_no'] ?? 0),
        'title' => (string) ($row['title'] ?? ''),
        'member_visible' => !empty($row['member_visible']),
        'published_by' => (string) ($row['published_by'] ?? ''),
        'published_at' => (string) ($row['published_at'] ?? ''),
        'response_count' => (int) ($row['response_count'] ?? 0),
        'snapshot' => is_array($snapshot) ? $snapshot : [],
        'results' => is_array($results) ? $results : [],
    ];
}

function survey_fetch_publications(PDO $pdo, string $surveyId): array
{
    if (!survey_publications_ready($pdo) || $surveyId === '') {
        return [];
    }

    $rows = app_query_all(
        $pdo,
        'SELECT id, survey_id, tenant_id, version_no, title, member_visible, published_by, published_at, snapshot_json, results_json, response_count, created_at, updated_at FROM survey_publications WHERE survey_id = :survey_id ORDER BY version_no DESC, published_at DESC',
        ['survey_id' => $surveyId]
    );

    return array_map('survey_decode_publication_row', $rows);
}

function survey_latest_publication(PDO $pdo, string $surveyId): ?array
{
    $publications = survey_fetch_publications($pdo, $surveyId);

    return $publications[0] ?? null;
}

function survey_publish_snapshot(PDO $pdo, string $tenantId, array $auth, array $survey, bool $memberVisible): array
{
    if (!survey_publications_ready($pdo)) {
        throw new RuntimeException('Die Freigabe kann erst nach dem Datenbank-Update verwendet werden.');
    }

    $surveyId = (string) ($survey['id'] ?? '');
    $questions = is_array($survey['questions'] ?? null) ? $survey['questions'] : [];

    if ($surveyId === '') {
        throw new RuntimeException('Die gewählte Umfrage konnte nicht freigegeben werden.');
    }

    if ($questions === []) {
        throw new RuntimeException('Eine Umfrage braucht mindestens eine Frage, bevor sie freigegeben werden kann.');
    }

    $now = date('Y-m-d H:i:s');
    $snapshot = survey_build_snapshot($pdo, $survey);
    $results = $snapshot['results'];

    $versionNo = (int) (app_query_value(
        $pdo,
        'SELECT COALESCE(MAX(version_no), 0) FROM survey_publications WHERE survey_id = :survey_id',
        ['survey_id' => $surveyId],
        0
    ) ?? 0) + 1;

    $publishedBy = trim((string) ($auth['display_name'] ?? ''));
    if ($publishedBy === '') {
        $publishedBy = trim((string) ($auth['name'] ?? ''));
    }
    if ($publishedBy === '') {
        $publishedBy = 'Unbekannt';
    }

    app_execute(
        $pdo,
        'INSERT INTO survey_publications (id, tenant_id, survey_id, version_no, title, member_visible, published_by, published_at, snapshot_json, results_json, response_count, created_at, updated_at) VALUES (:id, :tenant_id, :survey_id, :version_no, :title, :member_visible, :published_by, :published_at, :snapshot_json, :results_json, :response_count, :created_at, :updated_at)',
        [
            'id' => app_uuid(),
            'tenant_id' => $tenantId,
            'survey_id' => $surveyId,
            'version_no' => $versionNo,
            'title' => (string) ($survey['title'] ?? ''),
            'member_visible' => $memberVisible ? 1 : 0,
            'published_by' => $publishedBy,
            'published_at' => $now,
            'snapshot_json' => json_encode($snapshot, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            'results_json' => json_encode($results, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
            'response_count' => (int) app_query_value(
                $pdo,
                'SELECT COUNT(DISTINCT tenant_user_id) FROM survey_answers WHERE survey_id = :survey_id',
                ['survey_id' => $surveyId],
                0
            ),
            'created_at' => $now,
            'updated_at' => $now,
        ]
    );

    app_execute(
        $pdo,
        'UPDATE surveys SET status = :status, updated_at = :updated_at WHERE tenant_id = :tenant_id AND id = :id',
        [
            'status' => 'published',
            'updated_at' => $now,
            'tenant_id' => $tenantId,
            'id' => $surveyId,
        ]
    );

    return survey_latest_publication($pdo, $surveyId) ?? [];
}

function survey_fetch_list(PDO $pdo, string $tenantId): array
{
    $surveys = app_query_all(
        $pdo,
        <<<'SQL'
SELECT
    s.id,
    s.title,
    s.status,
    s.starts_at,
    s.ends_at,
    s.created_at,
    COUNT(DISTINCT sq.id) AS question_count,
    COUNT(DISTINCT sa.id) AS answer_count
FROM surveys s
LEFT JOIN survey_questions sq ON sq.survey_id = s.id
LEFT JOIN survey_answers sa ON sa.survey_id = s.id
WHERE s.tenant_id = :tenant_id
GROUP BY s.id, s.title, s.status, s.starts_at, s.ends_at, s.created_at
ORDER BY
    CASE s.status
        WHEN 'active' THEN 0
        WHEN 'draft' THEN 1
        ELSE 2
    END,
    s.created_at DESC
SQL,
        ['tenant_id' => $tenantId]
    );

    return array_map(static function (array $survey) use ($pdo): array {
        $survey['questions'] = survey_fetch_questions($pdo, (string) ($survey['id'] ?? ''));
        return $survey;
    }, $surveys);
}

function survey_fetch_detail(PDO $pdo, string $tenantId, string $surveyId): ?array
{
    if ($surveyId === '') {
        return null;
    }

    $survey = app_query_one(
        $pdo,
        'SELECT id, tenant_id, title, status, starts_at, ends_at, created_at, updated_at FROM surveys WHERE tenant_id = :tenant_id AND id = :id LIMIT 1',
        ['tenant_id' => $tenantId, 'id' => $surveyId]
    );

    if ($survey === null) {
        return null;
    }

    $survey['questions'] = survey_fetch_questions($pdo, $surveyId);

    return $survey;
}

function survey_fetch_answer_map(PDO $pdo, string $surveyId, string $tenantUserId): array
{
    if ($surveyId === '' || $tenantUserId === '') {
        return [];
    }

    $answers = [];
    foreach (app_query_all(
        $pdo,
        'SELECT question_id, answer_text FROM survey_answers WHERE survey_id = :survey_id AND tenant_user_id = :tenant_user_id',
        ['survey_id' => $surveyId, 'tenant_user_id' => $tenantUserId]
    ) as $row) {
        $answers[(string) ($row['question_id'] ?? '')] = (string) ($row['answer_text'] ?? '');
    }

    return $answers;
}

function survey_fetch_results(PDO $pdo, string $surveyId): array
{
    return survey_build_results($pdo, survey_fetch_questions($pdo, $surveyId), $surveyId);
}

function survey_save_survey(PDO $pdo, string $tenantId, array $input): void
{
    $surveyId = trim((string) ($input['survey_id'] ?? ''));
    $title = trim((string) ($input['title'] ?? ''));
    $startsAt = trim((string) ($input['starts_at'] ?? ''));
    $endsAt = trim((string) ($input['ends_at'] ?? ''));

    if ($title === '') {
        throw new RuntimeException('Bitte gib einen Titel für die Umfrage an.');
    }

    $startsAtValue = $startsAt !== '' ? str_replace('T', ' ', $startsAt) . ':00' : null;
    $endsAtValue = $endsAt !== '' ? str_replace('T', ' ', $endsAt) . ':00' : null;
    $now = date('Y-m-d H:i:s');

    if ($surveyId !== '') {
        app_execute(
            $pdo,
            'UPDATE surveys SET title = :title, starts_at = :starts_at, ends_at = :ends_at, updated_at = :updated_at WHERE tenant_id = :tenant_id AND id = :id',
            [
                'title' => $title,
                'starts_at' => $startsAtValue,
                'ends_at' => $endsAtValue,
                'updated_at' => $now,
                'tenant_id' => $tenantId,
                'id' => $surveyId,
            ]
        );

        return;
    }

    app_execute(
        $pdo,
        'INSERT INTO surveys (id, tenant_id, title, status, starts_at, ends_at, created_at, updated_at) VALUES (:id, :tenant_id, :title, :status, :starts_at, :ends_at, :created_at, :updated_at)',
        [
            'id' => app_uuid(),
            'tenant_id' => $tenantId,
            'title' => $title,
            'status' => 'draft',
            'starts_at' => $startsAtValue,
            'ends_at' => $endsAtValue,
            'created_at' => $now,
            'updated_at' => $now,
        ]
    );
}

function survey_save_question(PDO $pdo, string $surveyId, array $input): void
{
    $questionId = trim((string) ($input['question_id'] ?? ''));
    $question = trim((string) ($input['question'] ?? ''));
    $questionType = trim((string) ($input['question_type'] ?? 'text'));
    $sortOrder = max(0, (int) ($input['sort_order'] ?? 10));
    $isRequired = !empty($input['is_required']) ? 1 : 0;
    $optionsJson = survey_option_text_to_json((string) ($input['options_text'] ?? ''), $questionType);

    if ($question === '') {
        throw new RuntimeException('Bitte gib einen Fragetext an.');
    }

    if (!in_array($questionType, ['text', 'scale', 'single_select', 'multi_select'], true)) {
        $questionType = 'text';
    }

    $hasOptions = app_table_has_column($pdo, 'survey_questions', 'options_json');
    $now = date('Y-m-d H:i:s');

    if ($questionId !== '') {
        $sql = $hasOptions
            ? 'UPDATE survey_questions SET question = :question, question_type = :question_type, is_required = :is_required, sort_order = :sort_order, options_json = :options_json, updated_at = :updated_at WHERE survey_id = :survey_id AND id = :id'
            : 'UPDATE survey_questions SET question = :question, question_type = :question_type, is_required = :is_required, sort_order = :sort_order, updated_at = :updated_at WHERE survey_id = :survey_id AND id = :id';
        $params = [
            'question' => $question,
            'question_type' => $questionType,
            'is_required' => $isRequired,
            'sort_order' => $sortOrder,
            'updated_at' => $now,
            'survey_id' => $surveyId,
            'id' => $questionId,
        ];
        if ($hasOptions) {
            $params['options_json'] = $optionsJson;
        }
        app_execute($pdo, $sql, $params);

        return;
    }

    $sql = $hasOptions
        ? 'INSERT INTO survey_questions (id, survey_id, question, question_type, options_json, is_required, sort_order, created_at, updated_at) VALUES (:id, :survey_id, :question, :question_type, :options_json, :is_required, :sort_order, :created_at, :updated_at)'
        : 'INSERT INTO survey_questions (id, survey_id, question, question_type, is_required, sort_order, created_at, updated_at) VALUES (:id, :survey_id, :question, :question_type, :is_required, :sort_order, :created_at, :updated_at)';
    $params = [
        'id' => app_uuid(),
        'survey_id' => $surveyId,
        'question' => $question,
        'question_type' => $questionType,
        'is_required' => $isRequired,
        'sort_order' => $sortOrder,
        'created_at' => $now,
        'updated_at' => $now,
    ];
    if ($hasOptions) {
        $params['options_json'] = $optionsJson;
    }
    app_execute($pdo, $sql, $params);
}

function survey_submit_answers(PDO $pdo, array $auth, array $survey): void
{
    $tenantUserId = (string) ($auth['tenant_user_id'] ?? '');
    $surveyId = (string) ($survey['id'] ?? '');
    $questions = is_array($survey['questions'] ?? null) ? $survey['questions'] : [];

    if ($tenantUserId === '' || $surveyId === '') {
        throw new RuntimeException('Die Teilnahme konnte nicht zugeordnet werden.');
    }

    if (!in_array((string) ($survey['status'] ?? 'draft'), ['active', 'published'], true)) {
        throw new RuntimeException('Diese Umfrage ist aktuell nicht für Teilnahmen freigegeben.');
    }

    $answersInput = $_POST['answers'] ?? [];
    $normalized = [];

    foreach ($questions as $question) {
        $questionId = (string) ($question['id'] ?? '');
        $rawAnswer = $answersInput[$questionId] ?? '';
        $answerText = is_array($rawAnswer)
            ? implode("\n", array_values(array_filter(array_map('trim', $rawAnswer))))
            : trim((string) $rawAnswer);

        if ((int) ($question['is_required'] ?? 0) === 1 && $answerText === '') {
            throw new RuntimeException('Bitte beantworte alle Pflichtfragen.');
        }

        $normalized[$questionId] = $answerText;
    }

    $pdo->beginTransaction();

    try {
        app_execute(
            $pdo,
            'DELETE FROM survey_answers WHERE survey_id = :survey_id AND tenant_user_id = :tenant_user_id',
            ['survey_id' => $surveyId, 'tenant_user_id' => $tenantUserId]
        );

        $now = date('Y-m-d H:i:s');
        foreach ($normalized as $questionId => $answerText) {
            if ($answerText === '') {
                continue;
            }

            app_execute(
                $pdo,
                'INSERT INTO survey_answers (id, survey_id, question_id, tenant_user_id, answer_text, created_at, updated_at) VALUES (:id, :survey_id, :question_id, :tenant_user_id, :answer_text, :created_at, :updated_at)',
                [
                    'id' => app_uuid(),
                    'survey_id' => $surveyId,
                    'question_id' => $questionId,
                    'tenant_user_id' => $tenantUserId,
                    'answer_text' => $answerText,
                    'created_at' => $now,
                    'updated_at' => $now,
                ]
            );
        }

        $pdo->commit();
    } catch (Throwable $exception) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }

        throw $exception;
    }
}

$auth = app_require_auth();
$tenantId = (string) ($auth['tenant_id'] ?? '');
$tenantLicense = ['plan_name' => 'Free', 'features' => app_feature_defaults()];
$tenantSettings = app_tenant_settings_defaults();
$tenantNavItems = [];
$tenantNavGroups = [];
$tenantHeaderNavItems = [];
$mobileBottomNavItems = [];
$mobileDrawerPrimaryItems = [];
$flash = app_flash();
$dbError = null;
$pdo = null;
$surveys = [];
$selectedSurvey = null;
$selectedSurveyAnswers = [];
$selectedSurveyResults = [];
$selectedSurveyPublication = null;
$selectedSurveyPublications = [];
$editingQuestion = null;
$canManage = app_can_manage_surveys($auth);
$surveyTablesReady = false;
$publicationTablesReady = false;
$csrf = (string) ($_SESSION['survey_csrf'] ?? '');

try {
    $pdo = app_pdo();
    $tenantLicense = app_tenant_license($pdo, $tenantId);
    $tenantSettings = app_tenant_settings($pdo, $tenantId);
    $tenantNavItems = app_tenant_navigation_items($auth, $tenantLicense);
    $tenantNavGroups = app_tenant_navigation_groups($tenantNavItems);
    foreach ($tenantNavItems as $item) {
        if (in_array((string) ($item['key'] ?? ''), ['dashboard', 'ledger', 'payments'], true)) {
            $tenantHeaderNavItems[] = $item;
            $mobileBottomNavItems[] = $item;
        }
    }
    $surveyTablesReady = scripts_table_exists($pdo, 'surveys')
        && scripts_table_exists($pdo, 'survey_questions')
        && scripts_table_exists($pdo, 'survey_answers');
    $publicationTablesReady = survey_publications_ready($pdo);
} catch (Throwable $exception) {
    $dbError = $exception->getMessage();
}

if ($pdo instanceof PDO && $surveyTablesReady && ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    if (!hash_equals($csrf, (string) ($_POST['csrf'] ?? ''))) {
        app_flash('Die Sitzung ist abgelaufen. Bitte lade die Seite neu.', 'error');
        app_redirect('/surveys/');
    }

    $action = (string) ($_POST['action'] ?? '');

    try {
        if ($action === 'save-survey' && $canManage) {
            survey_save_survey($pdo, $tenantId, $_POST);
            app_flash('Die Umfrage wurde gespeichert.', 'success');
        }

        if ($action === 'save-question' && $canManage) {
            survey_save_question($pdo, (string) ($_POST['survey_id'] ?? ''), $_POST);
            app_flash('Die Frage wurde gespeichert.', 'success');
        }

        if ($action === 'change-survey-status' && $canManage) {
            $status = (string) ($_POST['status'] ?? 'draft');
            if (!in_array($status, ['draft', 'active', 'published', 'closed'], true)) {
                $status = 'draft';
            }
            app_execute(
                $pdo,
                'UPDATE surveys SET status = :status, updated_at = :updated_at WHERE tenant_id = :tenant_id AND id = :id',
                [
                    'status' => $status,
                    'updated_at' => date('Y-m-d H:i:s'),
                    'tenant_id' => $tenantId,
                    'id' => (string) ($_POST['survey_id'] ?? ''),
                ]
            );
            app_flash('Der Umfragestatus wurde aktualisiert.', 'success');
        }

        if ($action === 'publish-survey' && $canManage) {
            $survey = survey_fetch_detail($pdo, $tenantId, (string) ($_POST['survey_id'] ?? ''));
            if ($survey === null) {
                throw new RuntimeException('Die ausgewählte Umfrage konnte nicht gefunden werden.');
            }

            $publication = survey_publish_snapshot($pdo, $tenantId, $auth, $survey, !empty($_POST['member_visible']));
            app_flash('Der Snapshot wurde freigegeben (Version ' . (string) ($publication['version_no'] ?? 1) . ').', 'success');
        }

        if ($action === 'answer-survey') {
            $survey = survey_fetch_detail($pdo, $tenantId, (string) ($_POST['survey_id'] ?? ''));
            if ($survey === null) {
                throw new RuntimeException('Die ausgewählte Umfrage konnte nicht gefunden werden.');
            }
            survey_submit_answers($pdo, $auth, $survey);
            app_flash('Deine Antworten wurden gespeichert.', 'success');
        }
    } catch (Throwable $exception) {
        app_flash($exception->getMessage(), 'error');
    }

    $redirectSurvey = trim((string) ($_POST['survey_id'] ?? ''));
    app_redirect('/surveys/' . ($redirectSurvey !== '' ? '?survey=' . rawurlencode($redirectSurvey) : ''));
}

if ($pdo instanceof PDO && $surveyTablesReady) {
    $surveys = survey_fetch_list($pdo, $tenantId);
    $selectedSurveyId = trim((string) ($_GET['survey'] ?? ''));

    if ($selectedSurveyId === '' && $surveys !== []) {
        $selectedSurveyId = (string) ($surveys[0]['id'] ?? '');
    }

    $selectedSurvey = survey_fetch_detail($pdo, $tenantId, $selectedSurveyId);
    $selectedSurveyAnswers = survey_fetch_answer_map($pdo, $selectedSurveyId, (string) ($auth['tenant_user_id'] ?? ''));
    $selectedSurveyResults = $canManage && $selectedSurvey !== null ? survey_fetch_results($pdo, $selectedSurveyId) : [];
    $selectedSurveyPublication = $selectedSurvey !== null ? survey_latest_publication($pdo, $selectedSurveyId) : null;
    $selectedSurveyPublications = $selectedSurvey !== null ? survey_fetch_publications($pdo, $selectedSurveyId) : [];

    if ($selectedSurvey !== null && isset($_GET['question']) && $_GET['question'] !== '') {
        foreach (($selectedSurvey['questions'] ?? []) as $question) {
            if ((string) ($question['id'] ?? '') === (string) $_GET['question']) {
                $editingQuestion = $question;
                break;
            }
        }
    }
}

$themeCss = app_tenant_theme_root_css($tenantSettings);
?><!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Die Kaffeeliste</title>
    <style>
        :root{<?= $themeCss ?>--line:rgba(143,158,191,.16);--line-strong:rgba(174,189,223,.26);--shadow:0 24px 64px rgba(1,6,18,.36);--surface-1:rgba(8,12,22,.84);--surface-2:rgba(13,18,31,.92);--surface-3:rgba(17,24,40,.96);--text-strong:#f4f7ff;--text-soft:rgba(219,228,248,.74)}
        *{box-sizing:border-box}body{margin:0;min-height:100vh;font-family:"Aptos","Segoe UI",sans-serif;color:var(--text-strong);background:radial-gradient(circle at top center,rgba(88,122,255,.2),transparent 26%),radial-gradient(circle at 18% 18%,rgba(var(--brand-rgb),.16),transparent 22%),linear-gradient(180deg,#05070d 0%,#0a0f1a 48%,#0d1320 100%)}a{color:inherit;text-decoration:none}h1,h2,h3{font-family:"Inter Tight","Aptos","Segoe UI",sans-serif;letter-spacing:-.04em}.button,button{display:inline-flex;align-items:center;justify-content:center;padding:.72rem 1rem;border-radius:10px;border:1px solid transparent;background:linear-gradient(135deg,#587aff 0%,#243a91 100%);color:#fff;font:inherit;font-weight:700;cursor:pointer}.button.secondary{background:rgba(255,255,255,.03);border-color:rgba(255,255,255,.12)}.page{width:min(1320px,calc(100vw - 32px));margin:0 auto 34px;display:grid;gap:16px}.header{position:sticky;top:0;z-index:30;width:100%;margin-left:0;margin-bottom:24px}.header__inner{display:flex;align-items:center;justify-content:space-between;gap:16px;min-height:74px;padding:0 24px;border-bottom:1px solid var(--line);background:rgba(8,10,18,.82);backdrop-filter:blur(18px)}.brand,.nav,.actions{display:flex;align-items:center;gap:10px;flex-wrap:wrap}.brand__mark{width:38px;height:38px;border-radius:10px;display:grid;place-items:center;background:linear-gradient(135deg,#587aff 0%,#243a91 100%);font-weight:800}.nav__link{display:inline-flex;align-items:center;justify-content:center;min-height:34px;padding:0 .34rem;border-radius:6px;border:1px solid transparent;color:var(--text-soft);font-weight:600}.nav__link.active,.nav__link:hover{background:rgba(255,255,255,.08);color:var(--text-strong);border-color:rgba(255,255,255,.12)}.nav-more{position:relative}.nav-more[open]{z-index:25}.nav-more__toggle{display:inline-flex;align-items:center;justify-content:center;min-height:34px;padding:0 .6rem;border-radius:8px;border:1px solid rgba(255,255,255,.08);background:rgba(255,255,255,.03);color:var(--text-soft);font-weight:700;cursor:pointer;list-style:none}.nav-more__toggle::-webkit-details-marker{display:none}.nav-more__panel{position:absolute;right:0;top:calc(100% + 10px);min-width:240px;padding:12px;border-radius:14px;border:1px solid var(--line);background:var(--surface-3);box-shadow:var(--shadow);display:grid;gap:8px}.nav-more__label{font-size:.76rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase;color:rgba(219,228,248,.52)}.site-mobile{display:none}.site-mobile__toggle{display:none;align-items:center;justify-content:center;gap:10px;cursor:pointer;min-height:38px;padding:.45rem .72rem;border-radius:10px;border:1px solid var(--line-strong);background:rgba(255,255,255,.04);color:#f4f7ff;font-size:.92rem;font-weight:600}.site-mobile__toggle::before{content:"";display:block;width:18px;height:2px;border-radius:999px;background:currentColor;box-shadow:0 -6px 0 currentColor,0 6px 0 currentColor}.mobile-drawer{position:fixed;inset:0;display:none;z-index:55}.mobile-drawer.is-open{display:block}.mobile-drawer__scrim{position:absolute;inset:0;background:rgba(4,10,18,.58);backdrop-filter:blur(6px)}.mobile-drawer__panel{position:absolute;right:0;top:0;bottom:0;width:min(100vw,420px);max-width:100%;padding:18px 16px calc(28px + env(safe-area-inset-bottom));background:var(--surface-3);border-left:1px solid var(--line);box-shadow:var(--shadow);display:grid;grid-template-rows:auto 1fr auto;gap:18px;overflow:auto}.mobile-drawer__header{display:flex;align-items:flex-start;justify-content:space-between;gap:12px}.mobile-drawer__title{margin:0;font-size:1.08rem}.mobile-drawer__subtitle{margin:4px 0 0;color:var(--text-soft);font-size:.9rem}.mobile-drawer__close{display:inline-flex;align-items:center;justify-content:center;width:40px;height:40px;border-radius:999px;border:1px solid var(--line);background:rgba(255,255,255,.04);color:var(--text-strong);font-size:1.15rem;font-weight:700;cursor:pointer}.mobile-drawer__section{display:grid;gap:10px}.mobile-drawer__label{font-size:.76rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase;color:var(--text-faint)}.mobile-drawer__links{display:grid;gap:8px}.mobile-drawer__link{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:.9rem 1rem;border-radius:14px;border:1px solid var(--line);background:rgba(255,255,255,.04);color:var(--text-strong);font-weight:700}.mobile-drawer__link.active{background:rgba(var(--brand-rgb),.16);border-color:rgba(var(--brand-rgb),.28)}.mobile-drawer__footer{display:grid;gap:12px;padding-top:8px;border-top:1px solid var(--line)}.mobile-drawer__meta{display:grid;gap:4px}.mobile-bottom-nav{display:none}.mobile-bottom-nav__link,.mobile-bottom-nav__toggle{display:inline-flex;align-items:center;justify-content:center;gap:6px;min-height:56px;padding:0 8px;border:0;background:transparent;color:var(--text-soft);font:inherit;font-weight:700}.mobile-bottom-nav__link.active,.mobile-bottom-nav__toggle.active{color:var(--text-strong)}.mobile-bottom-nav__icon{font-size:1rem;line-height:1}.mobile-bottom-nav__label{font-size:.74rem}.hero,.card,.alert{border:1px solid var(--line);border-radius:14px;background:var(--surface-2);padding:18px}.grid{display:grid;gap:18px}.grid-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-3{grid-template-columns:repeat(3,minmax(0,1fr))}.table{overflow-x:auto}.table table{width:100%;border-collapse:collapse;min-width:720px}.table th,.table td{padding:12px 10px;border-bottom:1px solid var(--line);text-align:left;vertical-align:top}.table th{font-size:.78rem;text-transform:uppercase;color:var(--text-soft)}label{display:flex;flex-direction:column;gap:8px;font-weight:700}input,select,textarea{width:100%;padding:12px 14px;border-radius:12px;border:1px solid rgba(255,255,255,.08);font:inherit;background:rgba(255,255,255,.04);color:var(--text-strong)}select{color-scheme:dark;background-color:var(--surface-3)}select option,select optgroup{background:var(--surface-3);color:var(--text-strong)}textarea{min-height:110px}.badge{display:inline-flex;align-items:center;padding:7px 12px;border-radius:999px;background:rgba(88,122,255,.14);font-size:.86rem;font-weight:700}.muted,p{color:var(--text-soft)}.metric{padding:18px;border:1px solid var(--line);border-radius:14px;background:rgba(255,255,255,.04)}.metric strong{display:block;font-size:1.55rem;margin-bottom:6px}.list{margin:0;padding-left:18px;color:var(--text-soft);line-height:1.7}.eyebrow{display:inline-block;color:#8aa0d0;text-transform:uppercase;letter-spacing:.14em;font-size:.8rem;font-weight:800}.stack{display:grid;gap:12px}@media(max-width:1180px){body.mobile-drawer-open{overflow:hidden}.header__inner{padding:0 16px}.nav{display:none}.site-mobile{display:block}.grid-2,.grid-3{grid-template-columns:1fr}.page{width:min(100vw - 20px,1320px);padding-bottom:94px}.actions{gap:8px}.actions .badge,.actions .nav-more{display:none}.site-mobile__toggle{display:inline-flex}.mobile-bottom-nav{position:fixed;left:10px;right:10px;bottom:max(10px,env(safe-area-inset-bottom));z-index:45;display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:4px;padding:6px;border:1px solid var(--line);border-radius:18px;background:var(--surface-3);box-shadow:var(--shadow)}}@media(min-width:1181px){.site-mobile{display:none}}
    </style>
</head>
<body>
<main class="page">
    <header class="header">
        <div class="header__inner">
            <a href="/dashboard/" class="brand">
                <div class="brand__mark">K</div>
                <div>
                    <h1 style="margin:0;font-size:1rem;">Die Kaffeeliste</h1>
                    <p style="margin:2px 0 0">Umfragen</p>
                </div>
            </a>
            <nav class="nav" aria-label="Tenant-Menü">
                <?php foreach ($tenantHeaderNavItems as $item): ?>
                    <a class="nav__link <?= (($item['key'] ?? '') === 'surveys') ? 'active' : '' ?>" href="<?= survey_h((string) ($item['href'] ?? '/')) ?>"><?= survey_h((string) ($item['label'] ?? 'Link')) ?></a>
                <?php endforeach; ?>
                <?php foreach ($tenantNavGroups as $group): ?>
                    <details class="nav-more">
                        <summary class="nav-more__toggle"><?= survey_h((string) ($group['label'] ?? 'Mehr')) ?></summary>
                        <div class="nav-more__panel">
                            <div class="nav-more__label"><?= survey_h((string) ($group['label'] ?? 'Mehr')) ?></div>
                            <?php foreach (($group['items'] ?? []) as $item): ?>
                                <a class="nav__link <?= (($item['key'] ?? '') === 'surveys') ? 'active' : '' ?>" href="<?= survey_h((string) ($item['href'] ?? '/')) ?>"><?= survey_h((string) ($item['label'] ?? 'Link')) ?></a>
                            <?php endforeach; ?>
                        </div>
                    </details>
                <?php endforeach; ?>
            </nav>
            <div class="actions">
                <span class="badge"><?= $canManage ? 'Verwaltung und Teilnahme' : 'Teilnahme' ?></span>
                <details class="nav-more">
                    <summary class="nav-more__toggle">Konto</summary>
                    <div class="nav-more__panel">
                        <div class="nav-more__label">Konto</div>
                        <a class="nav__link" href="/profile/">Persönliche Einstellungen</a>
                        <form method="post" action="/logout/"><button type="submit" class="button secondary" style="width:100%">Abmelden</button></form>
                    </div>
                </details>
                <button type="button" class="site-mobile__toggle" data-mobile-drawer-open>Menü</button>
            </div>
        </div>
    </header>

    <?php if ($mobileBottomNavItems !== []): ?>
        <div class="mobile-drawer" data-mobile-drawer>
            <button type="button" class="mobile-drawer__scrim" aria-label="Menü schließen" data-mobile-drawer-close></button>
            <aside class="mobile-drawer__panel" aria-label="Menü">
                <div class="mobile-drawer__header">
                    <div>
                        <h2 class="mobile-drawer__title">Menü</h2>
                        <p class="mobile-drawer__subtitle"><?= survey_h((string) ($auth['tenant_name'] ?? 'Bereich')) ?></p>
                    </div>
                    <button type="button" class="mobile-drawer__close" aria-label="Schließen" data-mobile-drawer-close>&times;</button>
                </div>
                <?php if ($tenantHeaderNavItems !== []): ?>
                    <div class="mobile-drawer__section">
                        <div class="mobile-drawer__label">Kernnavigation</div>
                        <div class="mobile-drawer__links">
                            <?php foreach ($tenantHeaderNavItems as $item): ?>
                                <a class="mobile-drawer__link <?= (($item['key'] ?? '') === 'surveys') ? 'active' : '' ?>" href="<?= survey_h((string) ($item['href'] ?? '/')) ?>" <?= (($item['key'] ?? '') === 'surveys') ? 'aria-current="page"' : '' ?>><?= survey_h((string) ($item['label'] ?? 'Link')) ?></a>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endif; ?>
                <?php foreach ($tenantNavGroups as $group): ?>
                    <div class="mobile-drawer__section">
                        <div class="mobile-drawer__label"><?= survey_h((string) ($group['label'] ?? 'Mehr')) ?></div>
                        <div class="mobile-drawer__links">
                            <?php foreach (($group['items'] ?? []) as $item): ?>
                                <a class="mobile-drawer__link <?= (($item['key'] ?? '') === 'surveys') ? 'active' : '' ?>" href="<?= survey_h((string) ($item['href'] ?? '/')) ?>" <?= (($item['key'] ?? '') === 'surveys') ? 'aria-current="page"' : '' ?>><?= survey_h((string) ($item['label'] ?? 'Link')) ?></a>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
                <div class="mobile-drawer__footer">
                    <div class="mobile-drawer__section">
                        <div class="mobile-drawer__label">Konto</div>
                        <div class="mobile-drawer__links">
                            <a class="mobile-drawer__link" href="/profile/">Persönliche Einstellungen</a>
                        </div>
                    </div>
                    <form method="post" action="/logout/"><button type="submit" class="button secondary" style="width:100%">Abmelden</button></form>
                </div>
            </aside>
        </div>
    <?php endif; ?>

    <?php if ($flash !== null): ?>
        <section class="alert"><?= survey_h((string) ($flash['message'] ?? '')) ?></section>
    <?php endif; ?>

    <section class="hero">
        <div class="eyebrow">Umfragen</div>
        <h1 style="margin:8px 0 10px">Tenantbezogene Umfragen mit Teilnahme und Auswertung</h1>
        <p>Entwürfe, aktive Umfragen und Ergebnisse laufen in einer Seite zusammen. Mitglieder beantworten freigegebene Umfragen direkt im Tenant, Verantwortliche pflegen Fragen und sehen die Auswertung.</p>
    </section>

    <?php if ($dbError !== null): ?>
        <section class="alert">Die Datenbank konnte nicht geladen werden: <?= survey_h($dbError) ?></section>
    <?php elseif (!$surveyTablesReady): ?>
        <section class="alert">Die Survey-Tabellen sind noch nicht verfügbar. Bitte Migrationen und Updates ausführen.</section>
    <?php else: ?>
        <section class="grid grid-3">
            <article class="metric"><strong><?= survey_h((string) count($surveys)) ?></strong><h3>Umfragen</h3><p>Alle Entwürfe und aktiven Umfragen des Tenants.</p></article>
            <article class="metric"><strong><?= survey_h((string) count(array_filter($surveys, static fn(array $survey): bool => ($survey['status'] ?? '') === 'active'))) ?></strong><h3>Aktiv</h3><p>Aktuell für Mitglieder freigegebene Umfragen.</p></article>
            <article class="metric"><strong><?= survey_h((string) array_sum(array_map(static fn(array $survey): int => (int) ($survey['answer_count'] ?? 0), $surveys))) ?></strong><h3>Antworten</h3><p>Erfasste Rückmeldungen über alle Umfragen.</p></article>
        </section>

        <section class="grid grid-2">
            <article class="card">
                <h2>Umfragen im Tenant</h2>
                <div class="table">
                    <table>
                        <thead><tr><th>Titel</th><th>Status</th><th>Fragen</th><th>Antworten</th><th>Aktion</th></tr></thead>
                        <tbody>
                            <?php foreach ($surveys as $survey): ?>
                                <tr>
                                    <td><strong><?= survey_h((string) ($survey['title'] ?? '')) ?></strong><br><span class="muted"><?= survey_dt((string) ($survey['created_at'] ?? '')) ?></span></td>
                                    <td><?= survey_h((string) ($survey['status'] ?? 'draft')) ?></td>
                                    <td><?= survey_h((string) ($survey['question_count'] ?? '0')) ?></td>
                                    <td><?= survey_h((string) ($survey['answer_count'] ?? '0')) ?></td>
                                    <td><a class="button secondary" href="/surveys/?survey=<?= survey_h((string) ($survey['id'] ?? '')) ?>">Öffnen</a></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </article>

            <?php if ($canManage): ?>
                <article class="card">
                    <h2><?= $selectedSurvey !== null ? 'Umfrage aktualisieren' : 'Neue Umfrage anlegen' ?></h2>
                    <form method="post" action="/surveys/" class="grid">
                        <input type="hidden" name="csrf" value="<?= survey_h($csrf) ?>">
                        <input type="hidden" name="action" value="save-survey">
                        <input type="hidden" name="survey_id" value="<?= survey_h((string) ($selectedSurvey['id'] ?? '')) ?>">
                        <label>Titel<input name="title" value="<?= survey_h((string) ($selectedSurvey['title'] ?? '')) ?>" required></label>
                        <label>Start<input type="datetime-local" name="starts_at" value="<?= !empty($selectedSurvey['starts_at']) ? survey_h(date('Y-m-d\TH:i', strtotime((string) $selectedSurvey['starts_at']))) : '' ?>"></label>
                        <label>Ende<input type="datetime-local" name="ends_at" value="<?= !empty($selectedSurvey['ends_at']) ? survey_h(date('Y-m-d\TH:i', strtotime((string) $selectedSurvey['ends_at']))) : '' ?>"></label>
                        <div class="actions"><button type="submit">Umfrage speichern</button><a class="button secondary" href="/surveys/">Neu</a></div>
                    </form>
                </article>
            <?php else: ?>
                <article class="card">
                    <h2>Teilnahme</h2>
                    <ul class="list">
                        <li>Du kannst aktive Umfragen direkt im Tenant beantworten.</li>
                        <li>Deine letzte Antwort pro Frage wird gespeichert.</li>
                        <li>Geschlossene Umfragen bleiben nur noch zur Einsicht für Verantwortliche sichtbar.</li>
                    </ul>
                </article>
            <?php endif; ?>
        </section>

        <?php if ($selectedSurvey !== null): ?>
            <section class="grid grid-2">
                <article class="card">
                    <div class="actions" style="justify-content:space-between">
                        <div>
                            <div class="eyebrow">Aktive Auswahl</div>
                            <h2 style="margin:8px 0 6px"><?= survey_h((string) ($selectedSurvey['title'] ?? '')) ?></h2>
                            <p>Status: <?= survey_h((string) ($selectedSurvey['status'] ?? 'draft')) ?></p>
                        </div>
                        <?php if ($canManage): ?>
                            <div class="actions">
                                <?php foreach (['draft' => 'Entwurf', 'active' => 'Aktivieren', 'closed' => 'Schließen'] as $statusKey => $statusLabel): ?>
                                    <form method="post" action="/surveys/">
                                        <input type="hidden" name="csrf" value="<?= survey_h($csrf) ?>">
                                        <input type="hidden" name="action" value="change-survey-status">
                                        <input type="hidden" name="survey_id" value="<?= survey_h((string) ($selectedSurvey['id'] ?? '')) ?>">
                                        <input type="hidden" name="status" value="<?= survey_h($statusKey) ?>">
                                        <button type="submit" class="button secondary"><?= survey_h($statusLabel) ?></button>
                                    </form>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    </div>

                    <?php if ($selectedSurveyPublication !== null && ($canManage || !empty($selectedSurveyPublication['member_visible']))): ?>
                        <div class="metric" style="margin-top:18px">
                            <div class="eyebrow">Freigegebener Snapshot</div>
                            <strong>Version <?= survey_h((string) ($selectedSurveyPublication['version_no'] ?? 0)) ?></strong>
                            <p>Freigegeben am <?= survey_dt((string) ($selectedSurveyPublication['published_at'] ?? '')) ?> von <?= survey_h((string) ($selectedSurveyPublication['published_by'] ?? '')) ?>.</p>
                            <p><?= !empty($selectedSurveyPublication['member_visible']) ? 'Mitglieder sehen diesen Stand in der Freigabeansicht.' : 'Dieser Stand ist für Mitglieder noch nicht sichtbar.' ?></p>
                        </div>
                    <?php endif; ?>

                    <?php if ($canManage): ?>
                        <?php if ($publicationTablesReady): ?>
                            <form method="post" action="/surveys/" class="grid" style="margin-top:18px">
                                <input type="hidden" name="csrf" value="<?= survey_h($csrf) ?>">
                                <input type="hidden" name="action" value="publish-survey">
                                <input type="hidden" name="survey_id" value="<?= survey_h((string) ($selectedSurvey['id'] ?? '')) ?>">
                                <label style="display:flex;flex-direction:row;align-items:center;gap:10px"><input type="checkbox" name="member_visible" value="1"<?= $selectedSurveyPublication === null || !empty($selectedSurveyPublication['member_visible']) ? ' checked' : '' ?> style="width:auto">Mitglieder dürfen den Snapshot sehen</label>
                                <div class="actions"><button type="submit">Snapshot freigeben</button></div>
                            </form>
                        <?php else: ?>
                            <div class="metric" style="margin-top:18px">
                                <div class="eyebrow">Freigabe</div>
                                <strong>Freigabe noch nicht verfügbar</strong>
                                <p>Bitte die neue Publication-Migration ausführen, dann kann der Snapshot veröffentlicht werden.</p>
                            </div>
                        <?php endif; ?>

                        <form method="post" action="/surveys/" class="grid" style="margin-top:18px">
                            <input type="hidden" name="csrf" value="<?= survey_h($csrf) ?>">
                            <input type="hidden" name="action" value="save-question">
                            <input type="hidden" name="survey_id" value="<?= survey_h((string) ($selectedSurvey['id'] ?? '')) ?>">
                            <input type="hidden" name="question_id" value="<?= survey_h((string) ($editingQuestion['id'] ?? '')) ?>">
                            <label>Fragetext<input name="question" value="<?= survey_h((string) ($editingQuestion['question'] ?? '')) ?>" required></label>
                            <label>Typ<select name="question_type"><option value="text"<?= (($editingQuestion['question_type'] ?? '') === 'text') ? ' selected' : '' ?>>Freitext</option><option value="scale"<?= (($editingQuestion['question_type'] ?? '') === 'scale') ? ' selected' : '' ?>>Skala</option><option value="single_select"<?= (($editingQuestion['question_type'] ?? '') === 'single_select') ? ' selected' : '' ?>>Einfachauswahl</option><option value="multi_select"<?= (($editingQuestion['question_type'] ?? '') === 'multi_select') ? ' selected' : '' ?>>Mehrfachauswahl</option></select></label>
                            <label>Sortierung<input type="number" name="sort_order" min="0" step="1" value="<?= survey_h((string) ($editingQuestion['sort_order'] ?? '10')) ?>"></label>
                            <label style="display:flex;flex-direction:row;align-items:center;gap:10px"><input type="checkbox" name="is_required" value="1"<?= !empty($editingQuestion['is_required']) ? ' checked' : '' ?> style="width:auto">Pflichtfrage</label>
                            <label style="grid-column:1 / -1;">Antwortoptionen<textarea name="options_text" placeholder="Eine Option pro Zeile"><?= survey_h(implode("\n", survey_options_from_storage((string) ($editingQuestion['options_json'] ?? ''), (string) ($editingQuestion['question_type'] ?? '')))) ?></textarea></label>
                            <div class="actions"><button type="submit">Frage speichern</button><a class="button secondary" href="/surveys/?survey=<?= survey_h((string) ($selectedSurvey['id'] ?? '')) ?>">Neue Frage</a></div>
                        </form>
                    <?php endif; ?>

                    <div class="table" style="margin-top:18px">
                        <table>
                            <thead><tr><th>Frage</th><th>Typ</th><th>Pflicht</th><th>Aktion</th></tr></thead>
                            <tbody>
                                <?php foreach (($selectedSurvey['questions'] ?? []) as $question): ?>
                                    <tr>
                                        <td><?= survey_h((string) ($question['question'] ?? '')) ?></td>
                                        <td><?= survey_h((string) ($question['question_type'] ?? 'text')) ?></td>
                                        <td><?= !empty($question['is_required']) ? 'Ja' : 'Nein' ?></td>
                                        <td><?php if ($canManage): ?><a class="button secondary" href="/surveys/?survey=<?= survey_h((string) ($selectedSurvey['id'] ?? '')) ?>&question=<?= survey_h((string) ($question['id'] ?? '')) ?>">Bearbeiten</a><?php else: ?><span class="muted">-</span><?php endif; ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <?php if ($canManage && $selectedSurveyPublications !== []): ?>
                        <div class="table" style="margin-top:18px">
                            <table>
                                <thead><tr><th>Version</th><th>Freigegeben</th><th>Sichtbarkeit</th><th>Rückmeldungen</th></tr></thead>
                                <tbody>
                                    <?php foreach ($selectedSurveyPublications as $publication): ?>
                                        <tr>
                                            <td><strong>v<?= survey_h((string) ($publication['version_no'] ?? 0)) ?></strong></td>
                                            <td><?= survey_dt((string) ($publication['published_at'] ?? '')) ?><br><span class="muted">von <?= survey_h((string) ($publication['published_by'] ?? '')) ?></span></td>
                                            <td><?= !empty($publication['member_visible']) ? 'Mitglieder' : 'Nur Verwaltung' ?></td>
                                            <td><?= survey_h((string) ($publication['response_count'] ?? 0)) ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </article>

                <article class="card">
                    <?php if ($canManage || in_array((string) ($selectedSurvey['status'] ?? 'draft'), ['active', 'published'], true)): ?>
                        <h2><?= $canManage ? 'Mitgliedersicht und Teilnahme' : 'Umfrage beantworten' ?></h2>
                        <form method="post" action="/surveys/" class="stack">
                            <input type="hidden" name="csrf" value="<?= survey_h($csrf) ?>">
                            <input type="hidden" name="action" value="answer-survey">
                            <input type="hidden" name="survey_id" value="<?= survey_h((string) ($selectedSurvey['id'] ?? '')) ?>">
                            <?php foreach (($selectedSurvey['questions'] ?? []) as $question): ?>
                                <?php
                                    $questionId = (string) ($question['id'] ?? '');
                                    $questionType = (string) ($question['question_type'] ?? 'text');
                                    $options = survey_options_from_storage((string) ($question['options_json'] ?? ''), $questionType);
                                    $savedAnswer = (string) ($selectedSurveyAnswers[$questionId] ?? '');
                                    $savedSelections = $savedAnswer !== '' ? preg_split('/\R+/', $savedAnswer) : [];
                                ?>
                                <div class="metric">
                                    <h3><?= survey_h((string) ($question['question'] ?? '')) ?></h3>
                                    <?php if ($questionType === 'text'): ?>
                                        <textarea name="answers[<?= survey_h($questionId) ?>]"><?= survey_h($savedAnswer) ?></textarea>
                                    <?php elseif ($questionType === 'multi_select'): ?>
                                        <div class="stack">
                                            <?php foreach ($options as $option): ?>
                                                <label style="display:flex;flex-direction:row;align-items:center;gap:10px"><input type="checkbox" name="answers[<?= survey_h($questionId) ?>][]" value="<?= survey_h($option) ?>"<?= in_array($option, $savedSelections ?: [], true) ? ' checked' : '' ?> style="width:auto"><?= survey_h($option) ?></label>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php else: ?>
                                        <select name="answers[<?= survey_h($questionId) ?>]">
                                            <option value="">Bitte wählen</option>
                                            <?php foreach ($options as $option): ?>
                                                <option value="<?= survey_h($option) ?>"<?= $savedAnswer === $option ? ' selected' : '' ?>><?= survey_h($option) ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                            <?php if (!$canManage): ?>
                                <div class="actions"><button type="submit">Antworten speichern</button></div>
                            <?php endif; ?>
                        </form>
                        <?php if ($selectedSurveyPublication !== null): ?>
                            <div class="metric" style="margin-top:18px">
                                <div class="eyebrow">Freigegebene Ergebnisse</div>
                                <strong><?= survey_h((string) ($selectedSurveyPublication['title'] ?? ($selectedSurvey['title'] ?? '')) ) ?></strong>
                                <p>Snapshot v<?= survey_h((string) ($selectedSurveyPublication['version_no'] ?? 0)) ?> mit <?= survey_h((string) ($selectedSurveyPublication['response_count'] ?? 0)) ?> Rückmeldungen.</p>
                                <?php if ($canManage || !empty($selectedSurveyPublication['member_visible'])): ?>
                                    <div class="grid grid-2">
                                        <?php foreach ((array) ($selectedSurveyPublication['results'] ?? []) as $result): ?>
                                            <?php $question = $result['question'] ?? []; ?>
                                            <article class="metric">
                                                <h3><?= survey_h((string) ($question['question'] ?? '')) ?></h3>
                                                <?php if (($question['question_type'] ?? 'text') === 'text'): ?>
                                                    <ul class="list"><?php foreach (($result['entries'] ?? []) as $entry): ?><li><?= survey_h((string) ($entry['answer_text'] ?? '')) ?> <span class="muted">(<?= survey_dt((string) ($entry['created_at'] ?? '')) ?>)</span></li><?php endforeach; ?></ul>
                                                <?php else: ?>
                                                    <ul class="list"><?php foreach (($result['entries'] ?? []) as $entry): ?><li><?= survey_h((string) ($entry['answer_text'] ?? '')) ?>: <?= survey_h((string) ($entry['answer_count'] ?? '0')) ?></li><?php endforeach; ?></ul>
                                                <?php endif; ?>
                                            </article>
                                        <?php endforeach; ?>
                                    </div>
                                <?php else: ?>
                                    <p>Dieser Stand ist für Mitglieder noch nicht sichtbar.</p>
                                <?php endif; ?>
                            </div>
                        <?php elseif (!$canManage): ?>
                            <div class="metric" style="margin-top:18px">
                                <div class="eyebrow">Freigegebene Ergebnisse</div>
                                <strong>Noch nicht veröffentlicht</strong>
                                <p>Mitglieder sehen nur Ergebnisse aus einem freigegebenen Snapshot.</p>
                            </div>
                        <?php endif; ?>
                    <?php else: ?>
                        <h2>Diese Umfrage ist derzeit nicht freigegeben</h2>
                        <p>Mitglieder können nur Umfragen mit Status <code>active</code> oder <code>published</code> beantworten.</p>
                    <?php endif; ?>
                </article>
            </section>

            <?php if ($canManage): ?>
                <section class="card">
                    <h2>Auswertung</h2>
                    <div class="grid grid-2">
                        <?php foreach ($selectedSurveyResults as $result): ?>
                            <?php $question = $result['question']; ?>
                            <article class="metric">
                                <h3><?= survey_h((string) ($question['question'] ?? '')) ?></h3>
                                <?php if (($question['question_type'] ?? 'text') === 'text'): ?>
                                    <ul class="list"><?php foreach (($result['entries'] ?? []) as $entry): ?><li><?= survey_h((string) ($entry['answer_text'] ?? '')) ?> <span class="muted">(<?= survey_dt((string) ($entry['created_at'] ?? '')) ?>)</span></li><?php endforeach; ?></ul>
                                <?php else: ?>
                                    <ul class="list"><?php foreach (($result['entries'] ?? []) as $entry): ?><li><?= survey_h((string) ($entry['answer_text'] ?? '')) ?>: <?= survey_h((string) ($entry['answer_count'] ?? '0')) ?></li><?php endforeach; ?></ul>
                                <?php endif; ?>
                            </article>
                        <?php endforeach; ?>
                    </div>
                </section>
            <?php endif; ?>
        <?php endif; ?>
    <?php endif; ?>
</main>
<?php if ($mobileBottomNavItems !== []): ?>
    <nav class="mobile-bottom-nav" aria-label="Mobile Kernnavigation">
        <?php foreach ($mobileBottomNavItems as $item): ?>
            <a class="mobile-bottom-nav__link <?= (($item['key'] ?? '') === 'surveys') ? 'active' : '' ?>" href="<?= survey_h((string) ($item['href'] ?? '/')) ?>" <?= (($item['key'] ?? '') === 'surveys') ? 'aria-current="page"' : '' ?>>
                <span class="mobile-bottom-nav__icon"><?= match ((string) ($item['key'] ?? '')) {
                    'dashboard' => 'U',
                    'ledger' => 'B',
                    'payments' => 'Z',
                    default => '•',
                } ?></span>
                <span class="mobile-bottom-nav__label"><?= survey_h((string) ($item['label'] ?? 'Link')) ?></span>
            </a>
        <?php endforeach; ?>
        <button type="button" class="mobile-bottom-nav__toggle" data-mobile-drawer-open>
            <span class="mobile-bottom-nav__icon">+</span>
            <span class="mobile-bottom-nav__label">Menü</span>
        </button>
    </nav>
<?php endif; ?>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const details = document.querySelectorAll('.nav-more');
    const drawer = document.querySelector('[data-mobile-drawer]');
    const drawerOpeners = document.querySelectorAll('[data-mobile-drawer-open]');
    const drawerClosers = document.querySelectorAll('[data-mobile-drawer-close]');

    function closeOthers(current) {
        details.forEach(function (other) {
            if (other !== current) {
                other.open = false;
            }
        });
    }

    details.forEach(function (detail) {
        const summary = detail.querySelector('summary');
        if (summary) {
            summary.addEventListener('click', function () {
                if (!detail.open) {
                    closeOthers(detail);
                }
            });
        }

        detail.addEventListener('toggle', function () {
            if (detail.open) {
                closeOthers(detail);
            }
        });
    });

    document.querySelectorAll('.nav-more__panel a, .mobile-drawer__link').forEach(function (link) {
        link.addEventListener('click', function () {
            details.forEach(function (detail) {
                detail.open = false;
            });
            if (drawer) {
                drawer.classList.remove('is-open');
                document.body.classList.remove('mobile-drawer-open');
            }
        });
    });

    if (drawer) {
        drawerOpeners.forEach(function (button) {
            button.addEventListener('click', function () {
                drawer.classList.add('is-open');
                document.body.classList.add('mobile-drawer-open');
            });
        });

        drawerClosers.forEach(function (button) {
            button.addEventListener('click', function () {
                drawer.classList.remove('is-open');
                document.body.classList.remove('mobile-drawer-open');
            });
        });
    }
});
</script>
</body>
</html>
