<?php

declare(strict_types=1);

use App\Modules\Surveys\Application\SurveyService;
use App\Modules\Surveys\Controllers\SurveyController;

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

require_once dirname(__DIR__) . '/app-support.php';
require_once dirname(__DIR__, 2) . '/app/Modules/Surveys/Domain/Survey.php';
require_once dirname(__DIR__, 2) . '/app/Modules/Surveys/Domain/SurveyQuestion.php';
require_once dirname(__DIR__, 2) . '/app/Modules/Surveys/Domain/SurveyPublication.php';
require_once dirname(__DIR__, 2) . '/app/Modules/Surveys/Application/SurveyService.php';
require_once dirname(__DIR__, 2) . '/app/Modules/Surveys/Controllers/SurveyController.php';

if (!function_exists('h')) {
    function h(string $value): string
    {
        return app_h($value);
    }
}

if (!function_exists('dt_short')) {
    function dt_short(string $value): string
    {
        $timestamp = strtotime($value);

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

$auth = app_auth_user();
$tenantId = (string) ($auth['tenant_id'] ?? 'tenant-demo');
$tenantName = (string) ($auth['tenant_name'] ?? 'Demo Tenant');
$tenantUser = (string) ($auth['display_name'] ?? 'Survey-Verantwortliche');

$controller = new SurveyController(new SurveyService());
$payload = $controller->index($tenantId);
$data = $payload['data'];
$board = $data['board'];
$memberBoard = $data['memberBoard'];

?><!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Kaffeeliste SaaS - Surveys</title>
    <style>
        :root{--bg:#f4efe6;--card:#fffaf4;--ink:#1f2933;--muted:#667085;--brand:#0f766e;--accent:#b45309;--line:rgba(31,41,51,.12);--shadow:0 24px 60px rgba(15,23,42,.08);--radius:26px;--radius-lg:20px;--content-width:1200px}
        *{box-sizing:border-box}
        body{margin:0;min-height:100vh;font-family:"Aptos","Segoe UI","Trebuchet MS",sans-serif;color:var(--ink);background:radial-gradient(circle at top left,rgba(180,83,9,.12),transparent 30%),radial-gradient(circle at top right,rgba(15,118,110,.12),transparent 26%),linear-gradient(180deg,#faf7f1 0%,var(--bg) 100%)}
        a{color:inherit;text-decoration:none}
        h1,h2,h3,.brand__title{font-family:"Palatino Linotype","Book Antiqua",Georgia,serif;letter-spacing:-.02em}
        .shell{width:min(var(--content-width),calc(100vw - 32px));margin:24px auto 40px}
        .bar,.hero,.panel,.table-card,.note{border:1px solid var(--line);border-radius:var(--radius);background:var(--card);box-shadow:var(--shadow)}
        .bar{display:flex;justify-content:space-between;gap:16px;align-items:center;padding:18px 22px;margin-bottom:18px}
        .brand{display:grid;gap:4px}
        .brand__title{font-size:1.25rem;font-weight:700}
        .brand__subtitle{color:var(--muted)}
        .toolbar,.meta,.stack{display:flex;flex-wrap:wrap;gap:10px}
        .badge,.pill{display:inline-flex;align-items:center;padding:7px 12px;border-radius:999px;background:rgba(15,118,110,.08);color:var(--brand);font-weight:700;font-size:.86rem}
        .badge--solid{background:linear-gradient(135deg,var(--brand),#0f5752);color:#fff}
        .hero{display:grid;grid-template-columns:minmax(0,1.35fr) minmax(260px,.65fr);gap:20px;padding:28px;margin-bottom:18px}
        .hero__kicker{margin:0 0 10px;color:var(--accent);text-transform:uppercase;letter-spacing:.15em;font-size:.8rem;font-weight:800}
        .hero__title{margin:0 0 12px;font-size:clamp(2rem,4vw,3.5rem);line-height:1.05}
        .hero__lead{margin:0;color:var(--muted);max-width:70ch;line-height:1.7}
        .hero__actions{display:flex;flex-wrap:wrap;gap:12px;margin-top:16px}
        .button{display:inline-flex;align-items:center;justify-content:center;padding:11px 16px;border-radius:999px;border:0;background:linear-gradient(135deg,var(--brand),#0f5752);color:#fff;font-weight:700}
        .button--ghost{background:transparent;color:var(--brand);border:1px solid rgba(15,118,110,.18)}
        .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))}
        .card,.panel,.table-card{padding:22px}
        .metric{padding:18px;border:1px solid var(--line);border-radius:20px;background:#fffdf8}
        .metric__label,.muted{color:var(--muted)}
        .metric__value{font-size:1.8rem;font-weight:800;margin:6px 0 8px}
        .table-card__header{display:flex;justify-content:space-between;gap:12px;align-items:flex-start;margin-bottom:16px}
        table{width:100%;border-collapse:collapse}
        th,td{padding:12px 10px;border-bottom:1px solid var(--line);text-align:left;vertical-align:top}
        th{font-size:.82rem;text-transform:uppercase;letter-spacing:.08em;color:var(--muted)}
        .status{display:inline-flex;align-items:center;padding:6px 10px;border-radius:999px;background:rgba(15,118,110,.1);color:var(--brand);font-weight:700;font-size:.84rem}
        .status--warning{background:rgba(180,83,9,.12);color:#a34b12}
        .status--success{background:rgba(17,98,61,.12);color:#11623d}
        .feature-list__item{display:flex;gap:12px;padding:14px 16px;border-radius:16px;background:rgba(255,255,255,.78);border:1px solid rgba(31,41,51,.08)}
        .feature-list__badge{flex:0 0 auto;width:34px;height:34px;border-radius:12px;display:grid;place-items:center;background:rgba(15,118,110,.1);color:var(--brand);font-weight:800}
        .feature-list__title{margin:0 0 4px;font-weight:700}
        .timeline{display:grid;gap:12px}
        .timeline__item{padding:14px 16px;border-radius:16px;background:rgba(255,255,255,.72);border:1px solid rgba(31,41,51,.08)}
        .timeline__title{margin:0 0 4px;font-weight:700}
        .timeline__meta{margin:0;color:var(--muted)}
        .note{padding:16px 18px;margin-top:16px;background:rgba(15,118,110,.06)}
        .list-reset{margin:0;padding-left:18px}
        .list-reset li+li{margin-top:10px}
        @media(max-width:960px){.hero,.grid--2,.grid--3{grid-template-columns:1fr}.bar{align-items:flex-start;flex-direction:column}}
    </style>
</head>
<body>
    <main class="shell">
        <header class="bar">
            <div class="brand">
                <strong class="brand__title">Kaffeeliste SaaS</strong>
                <span class="brand__subtitle">Surveys als tenantfaehiger Verwaltungsbereich mit Snapshot-Publishing.</span>
            </div>
            <div class="toolbar">
                <span class="badge"><?= h($tenantName) ?></span>
                <span class="badge">Tenant-Admin / Survey-Manager</span>
                <span class="badge badge--solid">Snapshot-Modus</span>
            </div>
        </header>

        <section class="hero">
            <div>
                <p class="hero__kicker">Survey Admin</p>
                <h1 class="hero__title">Umfragen werden fachlich gepflegt und als veroeffentlichte Version ausgeliefert.</h1>
                <p class="hero__lead">
                    Entwuerfe bleiben im Admin-Bereich bearbeitbar. Erst nach Freigabe wird ein Snapshot erzeugt,
                    den Mitglieder lesen koennen. So bleibt die Fachseite flexibel und die Mitgliederansicht stabil.
                </p>
                <div class="hero__actions">
                    <a class="button" href="#admin-surveys">Admin Uebersicht</a>
                    <a class="button button--ghost" href="#member-surveys">Mitgliederansicht</a>
                </div>
            </div>
            <div class="stack">
                <?php foreach (array_slice($board['metrics'] ?? [], 0, 4) as $metric): ?>
                    <article class="metric">
                        <div class="metric__label"><?= h((string) ($metric['label'] ?? 'Kennzahl')) ?></div>
                        <div class="metric__value"><?= h((string) ($metric['value'] ?? '-')) ?></div>
                        <div class="muted"><?= h((string) ($metric['detail'] ?? '')) ?></div>
                    </article>
                <?php endforeach; ?>
            </div>
        </section>

        <section id="admin-surveys" class="grid grid--2">
            <article class="table-card">
                <div class="table-card__header">
                    <div>
                        <p class="hero__kicker">Verwaltung</p>
                        <h2>Entwuerfe und Freigaben</h2>
                    </div>
                    <span class="pill">Draft -> Review -> Snapshot</span>
                </div>
                <table>
                    <thead>
                        <tr>
                            <th>Umfrage</th>
                            <th>Fragen</th>
                            <th>Status</th>
                            <th>Kommentar</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach (($board['draft_surveys'] ?? []) as $survey): ?>
                            <tr>
                                <td>
                                    <strong><?= h($survey->title()) ?></strong>
                                    <div class="muted">ID <?= h($survey->id()) ?></div>
                                </td>
                                <td><?= (int) $survey->questionCount() ?></td>
                                <td>
                                    <?php if ($survey->isDraft()): ?>
                                        <span class="status">Entwurf</span>
                                    <?php elseif ($survey->status() === 'in_review'): ?>
                                        <span class="status status--warning">Pruefung</span>
                                    <?php else: ?>
                                        <span class="status status--success">Freigegeben</span>
                                    <?php endif; ?>
                                </td>
                                <td class="muted">
                                    <?= h($survey->isDraft() ? 'Live bearbeitbar, noch nicht freigegeben.' : 'Bereit fuer Freigabe oder Snapshot.') ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <div class="note">
                    Die Fachseite pflegt Entwuerfe live. Mitglieder sehen spaeter nur den veroeffentlichten Snapshot.
                </div>
            </article>

            <article class="panel">
                <h2>Freigabe-Workflow</h2>
                <div class="timeline">
                    <?php foreach (($board['workflow'] ?? []) as $step): ?>
                        <div class="timeline__item">
                            <p class="timeline__title"><?= h((string) ($step['step'] ?? 'Schritt')) ?></p>
                            <p class="timeline__meta"><?= h((string) ($step['detail'] ?? '')) ?></p>
                        </div>
                    <?php endforeach; ?>
                </div>
                <div class="note">
                    Freigaben koennen tenantweit konfigurierbar bleiben. Snapshot und Entwurf sind sauber getrennt.
                </div>
            </article>
        </section>

        <section id="member-surveys" class="grid grid--2" style="margin-top:18px;">
            <article class="table-card">
                <div class="table-card__header">
                    <div>
                        <p class="hero__kicker">Veroeffentlicht</p>
                        <h2>Snapshots fuer Mitglieder</h2>
                    </div>
                    <span class="pill">Read only</span>
                </div>
                <table>
                    <thead>
                        <tr>
                            <th>Snapshot</th>
                            <th>Stand</th>
                            <th>Antworten</th>
                            <th>Freigabe</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach (($board['published_snapshots'] ?? []) as $snapshot): ?>
                            <tr>
                                <td>
                                    <strong><?= h($snapshot->surveyTitle()) ?></strong>
                                    <div class="muted"><?= h($snapshot->versionLabel()) ?></div>
                                </td>
                                <td>
                                    <div><?= h(dt_short($snapshot->publishedAt())) ?></div>
                                    <div class="muted">von <?= h($snapshot->publishedBy()) ?></div>
                                </td>
                                <td><?= (int) $snapshot->responseCount() ?></td>
                                <td>
                                    <?php if ($snapshot->memberVisible()): ?>
                                        <span class="status status--success">Sichtbar</span>
                                    <?php else: ?>
                                        <span class="status status--warning">Gesperrt</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </article>

            <article class="panel">
                <h2>Mitglieder-Sicht</h2>
                <div class="stack">
                    <?php foreach (($memberBoard['participation'] ?? []) as $item): ?>
                        <div class="feature-list__item">
                            <div class="feature-list__badge">S</div>
                            <div>
                                <p class="feature-list__title"><?= h((string) $item) ?></p>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
                <div class="note">
                    Mitglieder sehen nur freigegebene Snapshots. Entwuerfe bleiben fuer Tenant-Admins und Survey-Manager editierbar.
                </div>
            </article>
        </section>

        <section class="grid grid--2" style="margin-top:18px;">
            <article class="panel">
                <h2>Rollen Im Modul</h2>
                <div class="stack">
                    <?php foreach (($board['roles'] ?? []) as $role): ?>
                        <div class="feature-list__item">
                            <div class="feature-list__badge"><?= h(strtoupper(substr((string) ($role['role'] ?? ''), 0, 1))) ?></div>
                            <div>
                                <p class="feature-list__title"><?= h((string) ($role['role'] ?? '')) ?></p>
                                <p class="muted"><?= h((string) ($role['capability'] ?? '')) ?></p>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </article>

            <article class="panel">
                <h2>Publishing-Regeln</h2>
                <ul class="list-reset">
                    <?php foreach (($board['publishing_rules'] ?? []) as $rule): ?>
                        <li><span class="status">Regel</span> <?= h((string) $rule) ?></li>
                    <?php endforeach; ?>
                </ul>
                <div class="note">
                    Tenant-Verantwortliche koennen Freigaben steuern und bei Bedarf den Vier-Augen-Mechanismus tenantweit deaktivieren.
                </div>
            </article>
        </section>
    </main>
</body>
</html>
