<?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_require_auth();
$tenantId = (string) ($auth['tenant_id'] ?? 'tenant-demo');
$tenantName = (string) ($auth['tenant_name'] ?? 'Demo Tenant');
$tenantUser = (string) ($auth['display_name'] ?? 'Survey-Verantwortliche');
$tenantLicense = ['plan_name' => 'Free', 'features' => app_feature_defaults()];
$tenantSettings = app_tenant_settings_defaults();

try {
    $pdo = app_pdo();
    $tenantLicense = app_tenant_license($pdo, $tenantId);
    $tenantSettings = app_tenant_settings($pdo, $tenantId);
} catch (\Throwable $ignored) {
}
$tenantNavItems = app_tenant_navigation_items($auth, $tenantLicense);

$controller = new SurveyController(new SurveyService());
$payload = $controller->index($tenantId);
$data = $payload['data'];
$board = $data['board'];
$memberBoard = $data['memberBoard'];
$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>Kaffeeliste - Umfragen</title>
    <style>
        :root{<?= $themeCss ?>--line:rgba(37,24,15,.14);--shadow:0 16px 36px rgba(37,24,15,.08);--radius:18px;--radius-lg:16px;--content-width:1200px}
        *{box-sizing:border-box}
        body{margin:0;min-height:100vh;font-family:"Aptos","Segoe UI",sans-serif;color:var(--ink);background:linear-gradient(180deg,#f9f6ef 0%,var(--bg) 100%)}
        a{color:inherit;text-decoration:none}
        h1,h2,h3,.brand__title{font-family:Georgia,serif;letter-spacing:-.02em}
        .shell{width:min(var(--content-width),calc(100vw - 32px));margin:20px 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.18rem;font-weight:700}
        .brand__subtitle{color:var(--muted)}
        .toolbar,.meta,.stack{display:flex;flex-wrap:wrap;gap:10px}
        .links,.meta,.stack{display:flex;flex-wrap:wrap;gap:10px}
        .links a,.button,.pill,button{display:inline-flex;align-items:center;justify-content:center;padding:10px 14px;border-radius:999px;font-weight:700;border:1px solid transparent}
        .links a{background:#fff;color:var(--brand);border-color:rgba(var(--brand-rgb),.12)}
        .links a.active{background:var(--brand);color:#fff}
        .badge,.pill{display:inline-flex;align-items:center;padding:7px 12px;border-radius:999px;background:#fff;color:var(--brand);font-weight:700;font-size:.86rem;border:1px solid rgba(var(--brand-rgb),.12)}
        .badge--solid{background:var(--brand);color:#fff}
        .hero{display:grid;grid-template-columns:minmax(0,1.35fr) minmax(260px,.65fr);gap:20px;padding:24px;margin-bottom:18px;background:linear-gradient(180deg,#fffdf8 0%,#f9f4ea 100%)}
        .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(1.9rem,4vw,3rem);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{background:var(--brand);color:#fff}
        .button--ghost{background:#fff;color:var(--brand);border-color:rgba(var(--brand-rgb),.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:16px;background:#fff}
        .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(var(--brand-rgb),.1);color:var(--brand);font-weight:700;font-size:.84rem}
        .status--warning{background:rgba(var(--accent-rgb),.14);color:#8c6500}
        .status--success{background:rgba(var(--brand-rgb),.12);color:var(--brand)}
        .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(var(--brand-rgb),.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:#fff;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(var(--brand-rgb),.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">Umfragen und Freigaben im Tenant.</span>
            </div>
            <nav class="links">
                <?php foreach ($tenantNavItems as $item): ?>
                    <a class="<?= (($item['key'] ?? '') === 'surveys') ? 'active' : '' ?>" href="<?= h((string) ($item['href'] ?? '/')) ?>"><?= h((string) ($item['label'] ?? 'Link')) ?></a>
                <?php endforeach; ?>
                <form method="post" action="/logout/"><button type="submit" class="button button--ghost">Abmelden</button></form>
            </nav>
        </header>

        <section class="hero">
            <div>
                <p class="hero__kicker">Umfragen</p>
                <h1 class="hero__title">Umfragen</h1>
                <p class="hero__lead">
                    Entwürfe bleiben intern bearbeitbar. Mitglieder sehen nur veröffentlichte Stände.
                </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>
