<?php

declare(strict_types=1);

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

require_once __DIR__ . '/app-support.php';

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

function money(string|int|float|null $value): string
{
    return number_format((float) $value, 2, ',', '.') . ' EUR';
}

function num(string|int|float|null $value): string
{
    return number_format((float) $value, 0, ',', '.');
}

function 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 badge(string $label, string $tone = 'neutral'): string
{
    return '<span class="badge badge-' . h($tone) . '">' . h($label) . '</span>';
}

$requestedPage = $_GET['page'] ?? null;

if ($requestedPage === null) {
    $path = rtrim(app_request_path(), '/');
    $requestedPage = match ($path) {
        '', '/', '/index.php' => 'home',
        '/login' => 'login',
        '/tenants', '/admin/tenants' => 'tenants',
        '/dashboard' => 'dashboard',
        '/members' => 'members',
        '/ledger' => 'ledger',
        '/payments' => 'payments',
        '/content' => 'content',
        '/support' => 'support',
        '/surveys' => 'surveys',
        '/settings' => 'settings',
        '/exports' => 'exports',
        '/logout' => 'logout',
        default => 'home',
    };
}

$page = (string) $requestedPage;
$requestMethod = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$tenantPages = ['dashboard', 'members', 'ledger', 'payments', 'content', 'support', 'surveys', 'settings', 'exports'];

if ($page === 'logout' && $requestMethod === 'POST') {
    app_logout();
    app_flash('Du wurdest erfolgreich abgemeldet.', 'success');
    app_redirect('/');
}

$marketing = app_marketing_messages();
$flash = app_flash();
$auth = app_auth_user();
$pdo = null;
$dbError = null;
$tenantOverview = null;
$tenantDashboard = null;
$members = [];
$ledger = [];
$payments = [];
$content = ['announcements' => [], 'faq' => []];
$memberSummary = null;
$loginFlow = ['state' => app_login_state(), 'message' => null, 'error' => null];
$editingMember = null;
$memberForm = app_member_form_defaults();
$tenantLicense = ['plan_key' => 'free', 'plan_name' => 'Free', 'member_limit' => 10, 'features' => app_feature_defaults()];
$tenantSettings = app_tenant_settings_defaults();
$printLists = [];
$activePrintList = null;
$printListGroups = ['front' => [], 'back' => []];
$printListItemMap = [];
$hasTenantSettingsFeature = false;
$hasPdfExportFeature = false;
$hasPaperStrikeEntryFeature = false;
$hasBasicExportsFeature = false;

try {
    $pdo = app_pdo();
    $tenantOverview = app_tenant_overview($pdo);
} catch (Throwable $exception) {
    $dbError = $exception->getMessage();
}

if (in_array($page, $tenantPages, true)) {
    $auth = app_require_auth();
}

if ($page === 'support') {
    app_redirect('/support/');
}

if ($page === 'surveys') {
    app_redirect('/surveys/');
}

if ($page === 'login' && $pdo instanceof PDO) {
    try {
        $loginFlow = app_handle_login($pdo);
        $auth = app_auth_user();
    } catch (Throwable $exception) {
        $loginFlow['error'] = $exception->getMessage();
    }
} elseif ($page === 'login' && $dbError !== null) {
    $loginFlow['error'] = $dbError;
}

if ($auth !== null && $pdo instanceof PDO) {
    try {
        $tenantLicense = app_tenant_license($pdo, (string) $auth['tenant_id']);
        $tenantSettings = app_tenant_settings($pdo, (string) $auth['tenant_id']);
        $hasTenantSettingsFeature = !empty($tenantLicense['features']['tenant_settings']);
        $hasPdfExportFeature = !empty($tenantLicense['features']['pdf_export']);
        $hasPaperStrikeEntryFeature = !empty($tenantLicense['features']['paper_strike_entry']);
        $hasBasicExportsFeature = !empty($tenantLicense['features']['basic_exports']);

        if (in_array($page, ['dashboard', 'ledger', 'payments'], true)) {
            app_handle_tenant_action($pdo, $auth);
        }

        if ($page === 'members') {
            app_handle_member_action($pdo, $auth);
        }

        if ($page === 'settings') {
            app_handle_settings_action($pdo, $auth);
        }

        if ($page === 'exports') {
            app_handle_export_action($pdo, $auth, $tenantSettings);
            app_handle_export_download($pdo, $auth);
        }

        if ($page === 'settings' && !$hasTenantSettingsFeature) {
            app_flash('Die Mandanten-Einstellungen sind in der aktuellen Lizenz nicht freigeschaltet.', 'warning');
            app_redirect('/dashboard/');
        }

        if ($page === 'exports'
            && !$hasPdfExportFeature
            && !$hasPaperStrikeEntryFeature
            && !$hasBasicExportsFeature) {
            app_flash('Die Exportfunktionen sind in der aktuellen Lizenz nicht freigeschaltet.', 'warning');
            app_redirect('/dashboard/');
        }

        $tenantDashboard = app_tenant_dashboard($pdo, (string) $auth['tenant_id']);
        $members = app_members_for_tenant($pdo, (string) $auth['tenant_id']);
        $memberSummary = app_member_summary($pdo, $auth);

        if (in_array($page, ['dashboard', 'ledger'], true)) {
            $ledger = app_ledger_for_tenant($pdo, (string) $auth['tenant_id']);
        }

        if (in_array($page, ['dashboard', 'payments'], true)) {
            $payments = app_payments_for_tenant($pdo, (string) $auth['tenant_id']);
        }

        if ($page === 'content') {
            $content = app_content_for_tenant($pdo, (string) $auth['tenant_id']);
        }

        if ($page === 'exports') {
            $printLists = app_print_lists_for_tenant($pdo, (string) $auth['tenant_id']);

            if (isset($_GET['list']) && $_GET['list'] !== '') {
                $activePrintList = app_print_list_detail($pdo, (string) $auth['tenant_id'], (string) $_GET['list']);
                if (is_array($activePrintList)) {
                    $printListGroups = app_print_list_pdf_groups($pdo, (string) $auth['tenant_id'], (string) $_GET['list']);
                    foreach (($activePrintList['items'] ?? []) as $item) {
                        $printListItemMap[(string) ($item['id'] ?? '')] = $item;
                    }
                }
            }
        }

        if ($page === 'members' && isset($_GET['edit']) && $_GET['edit'] !== '') {
            $editingMember = app_tenant_user_by_id($pdo, (string) $_GET['edit'], (string) $auth['tenant_id']);
            $memberForm = app_member_form_defaults($editingMember);
        }
    } catch (Throwable $exception) {
        $dbError = $exception->getMessage();
    }
}

$loginState = $loginFlow['state'] ?? [];
$loginStep = (string) ($loginState['step'] ?? 'discover');
$selectedMembership = $loginState['selected_membership'] ?? null;
$restrictedPages = [
    'members' => static fn(array $user): bool => app_can_manage_tenant($user),
    'ledger' => static fn(array $user): bool => app_can_manage_finance($user),
    'payments' => static fn(array $user): bool => app_can_manage_finance($user),
    'settings' => static fn(array $user): bool => app_can_manage_tenant($user),
    'exports' => static fn(array $user): bool => app_can_manage_tenant($user),
];

if ($auth !== null && isset($restrictedPages[$page]) && !$restrictedPages[$page]($auth)) {
    app_flash('Dieser Bereich ist für deine Rolle nicht freigegeben.', 'warning');
    app_redirect('/dashboard/');
}

$canManageTenant = app_can_manage_tenant($auth);
$tenantNavItems = app_tenant_navigation_items($auth, $tenantLicense);
$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 SaaS</title>
    <style>
        :root{<?= $themeCss ?>--line:rgba(37,24,15,.14);--radius:18px;--shadow:0 16px 36px rgba(37,24,15,.08)}
        *{box-sizing:border-box}body{margin:0;font-family:"Aptos","Segoe UI",sans-serif;color:var(--ink);background:linear-gradient(180deg,#f9f6ef 0%,var(--bg) 100%)}a{color:inherit}.shell{width:min(1180px,calc(100vw - 32px));margin:20px auto 40px}.bar,.hero,.card,.alert{border:1px solid var(--line);border-radius:var(--radius);background:var(--card);box-shadow:var(--shadow)}.bar,.links,.actions,.context{display:flex;flex-wrap:wrap;gap:10px}.bar{justify-content:space-between;align-items:center;padding:18px 22px;margin-bottom:14px}.brand strong,h1,h2,h3{font-family:Georgia,serif}.brand strong{font-size:1.18rem}.brand span,p,.muted{color:var(--muted)}.hero,.card{padding:24px}.hero{margin-bottom:18px;background:linear-gradient(180deg,#fffdf8 0%,#f9f4ea 100%)}.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))}.grid-4{grid-template-columns:repeat(4,minmax(0,1fr))}.links a,.button,button{display:inline-flex;align-items:center;justify-content:center;padding:10px 14px;border-radius:999px;text-decoration:none;font-weight:700;border:1px solid transparent;cursor:pointer}.links a{background:#fff;color:var(--brand);border-color:rgba(var(--brand-rgb),.12)}.links a.active{background:var(--brand);color:#fff}.button,button{background:var(--brand);color:#fff}.button.secondary{background:#fff;color:var(--brand);border-color:rgba(var(--brand-rgb),.18)}.eyebrow{display:inline-block;margin-bottom:12px;color:var(--accent);font-size:.82rem;font-weight:800;letter-spacing:.14em;text-transform:uppercase}h1{font-size:clamp(2rem,4vw,3.2rem);margin:0 0 12px}h2{font-size:1.35rem;margin:0 0 12px}h3{font-size:1.05rem;margin:0 0 10px}p{margin:0;line-height:1.6}.stack{display:grid;gap:12px}.metric{padding:18px;border:1px solid var(--line);border-radius:16px;background:#fff}.metric strong{display:block;font-size:1.8rem;margin-bottom:8px}.list{margin:14px 0 0;padding-left:18px;color:var(--muted);line-height:1.7}.alert{padding:16px 18px;margin-bottom:18px}.alert-success{background:rgba(var(--brand-rgb),.08)}.alert-warning{background:rgba(var(--accent-rgb),.1)}.alert-error{background:rgba(154,31,31,.1)}.alert-info{background:rgba(var(--brand-rgb),.08)}.badge{display:inline-flex;align-items:center;padding:7px 12px;border-radius:999px;font-size:.86rem;font-weight:700}.badge-neutral{background:rgba(var(--brand-rgb),.08);color:var(--brand)}.badge-success{background:rgba(var(--brand-rgb),.12);color:var(--brand)}.badge-warning{background:rgba(var(--accent-rgb),.14);color:#8c6500}.table{overflow-x:auto}.table table{width:100%;border-collapse:collapse;min-width:720px}.table th,.table td{padding:13px 10px;border-bottom:1px solid var(--line);text-align:left;vertical-align:top}.table th{font-size:.85rem;letter-spacing:.08em;text-transform:uppercase;color:var(--muted)}form.grid{grid-template-columns:repeat(2,minmax(0,1fr))}label{display:flex;flex-direction:column;gap:8px;font-weight:700}input,select,textarea{width:100%;padding:12px 14px;border-radius:14px;border:1px solid rgba(37,24,15,.15);font:inherit;background:#fff;color:var(--ink)}textarea{min-height:120px}.footer{margin-top:18px;text-align:center;color:var(--muted);font-size:.92rem}@media(max-width:960px){.grid-2,.grid-3,.grid-4,form.grid{grid-template-columns:1fr}.bar{align-items:flex-start;flex-direction:column}.table table{min-width:0}}
    </style>
</head>
<body>
    <main class="shell">
        <header class="bar">
            <div class="brand">
                <strong>Kaffeeliste SaaS</strong>
                <span>Kaffeeliste, Hinweise und Support in einem Menü.</span>
            </div>
            <nav class="links" aria-label="Navigation">
                <?php if ($auth === null): ?>
                    <a href="/" class="<?= $page === 'home' ? 'active' : '' ?>">Start</a>
                    <a href="/login/" class="<?= $page === 'login' ? 'active' : '' ?>">Anmeldung</a>
                    <a href="/admin/login/" class="<?= $page === 'tenants' ? 'active' : '' ?>">Verwaltung</a>
                <?php else: ?>
                    <?php foreach ($tenantNavItems as $item): ?>
                        <a href="<?= h((string) ($item['href'] ?? '/')) ?>" class="<?= $page === (string) ($item['key'] ?? '') ? 'active' : '' ?>"><?= h((string) ($item['label'] ?? 'Link')) ?></a>
                    <?php endforeach; ?>
                    <form method="post" action="/logout/"><button type="submit" class="button secondary">Abmelden</button></form>
                <?php endif; ?>
            </nav>
        </header>

        <?php if ($auth !== null): ?>
            <section class="card">
                <div class="context">
                    <?= badge((string) $auth['tenant_name']) ?>
                    <span class="muted"><?= h((string) $auth['display_name']) ?> ist angemeldet als <?= h((string) $auth['email']) ?></span>
                    <?= app_is_platform_admin($auth) ? badge('Global-Admin', 'success') : (app_is_tenant_admin($auth) ? badge('Tenant-Admin', 'success') : badge('Mitglied')) ?>
                    <?= badge('Lizenz ' . (string) ($tenantLicense['plan_name'] ?? 'Free')) ?>
                </div>
            </section>
        <?php endif; ?>

        <?php if ($auth !== null && !empty($auth['acting_as_platform_admin'])): ?>
            <section class="alert alert-info">
                Du siehst diesen Mandanten mit erweitertem Global-Admin-Zugriff.
                <a href="/admin/" style="font-weight:700;text-decoration:underline;">Zur zentralen Verwaltung</a>
            </section>
        <?php endif; ?>

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

        <?php if ($page === 'home'): ?>
            <section class="hero">
                <div class="eyebrow">Für Mitglieder und Betreiber</div>
                <h1><?= h((string) $marketing['hero']) ?></h1>
                <p><?= h((string) $marketing['subhero']) ?></p>
                <div class="actions" style="margin-top:18px">
                    <a class="button" href="/login/">Mitglieder anmelden</a>
                    <a class="button secondary" href="/admin/login/">Als Global-Admin anmelden</a>
                </div>
                <ul class="list">
                    <?php foreach (($marketing['benefits'] ?? []) as $benefit): ?>
                        <li><?= h((string) $benefit) ?></li>
                    <?php endforeach; ?>
                </ul>
            </section>

            <?php if ($tenantOverview !== null): ?>
                <section class="grid grid-4">
                    <?php foreach (($tenantOverview['metrics'] ?? []) as $metric): ?>
                        <article class="metric">
                            <strong><?= h((string) $metric['value']) ?></strong>
                            <h3><?= h((string) $metric['label']) ?></h3>
                            <p><?= h((string) $metric['detail']) ?></p>
                        </article>
                    <?php endforeach; ?>
                </section>
            <?php endif; ?>

            <section class="grid grid-3" style="margin-top:18px">
                <article class="card"><h2>Für Mitglieder</h2><p>Mit der geschäftlichen E-Mail einsteigen, den passenden Bereich automatisch erkennen lassen und den eigenen Stand sofort sehen.</p></article>
                <article class="card"><h2>Für Tenant-Admins</h2><p>Mitglieder, Buchungen, Einzahlungen und Hinweise bleiben pro Tenant sauber getrennt und leicht zu verwalten.</p></article>
                <article class="card"><h2>Für Betreiber</h2><p>Die Plattform wirkt professionell, weil Verwaltung, Anmeldung und Produktpräsentation an einer Stelle zusammenlaufen.</p></article>
            </section>

            <?php if ($dbError !== null): ?>
                <section class="alert alert-warning">Die Datenbank konnte noch nicht gelesen werden: <?= h($dbError) ?></section>
            <?php endif; ?>
        <?php elseif ($page === 'login'): ?>
            <section class="hero">
                <div class="eyebrow">Zentrale Anmeldung</div>
                <h1>Anmeldung</h1>
                <p>Zuerst wird der passende Bereich ermittelt. Falls mehrere Zuordnungen vorhanden sind, wählst du den richtigen Tenant aus und gibst danach dein Passwort ein.</p>
                <div class="context" style="margin-top:16px">
                    <?= badge('E-Mail zuerst') ?>
                    <?= badge('Tenant-Erkennung') ?>
                    <?= badge('Mehrfachzuordnung') ?>
                </div>
            </section>

            <?php if ($loginFlow['message'] !== null): ?>
                <section class="alert alert-info"><?= h((string) $loginFlow['message']) ?></section>
            <?php endif; ?>
            <?php if ($loginFlow['error'] !== null): ?>
                <section class="alert alert-error"><?= h((string) $loginFlow['error']) ?></section>
            <?php endif; ?>

            <section class="grid grid-2">
                <article class="card">
                    <?php if ($loginStep === 'choose-tenant'): ?>
                        <div class="eyebrow">Schritt 2</div>
                        <h2>Passenden Tenant wählen</h2>
                        <div class="stack">
                            <?php foreach (($loginState['memberships'] ?? []) as $membership): ?>
                                <form method="post" action="/login/" class="card">
                                    <input type="hidden" name="action" value="choose-tenant">
                                    <input type="hidden" name="tenant_user_id" value="<?= h((string) ($membership['tenant_user_id'] ?? '')) ?>">
                                    <h3><?= h((string) ($membership['tenant_name'] ?? 'Tenant')) ?></h3>
                                    <p><?= h((string) ($membership['display_name'] ?? $membership['user_email'] ?? '')) ?></p>
                                    <p class="muted"><?= h((string) ($membership['role_keys'] ?? 'Mitglied')) ?></p>
                                    <div class="actions" style="margin-top:12px"><button type="submit">Diesen Tenant öffnen</button></div>
                                </form>
                            <?php endforeach; ?>
                        </div>
                    <?php elseif ($loginStep === 'password' && is_array($selectedMembership)): ?>
                        <div class="eyebrow">Schritt 2</div>
                        <h2>Passwort eingeben</h2>
                        <p>Der Tenant wurde erkannt: <?= h((string) ($selectedMembership['tenant_name'] ?? '')) ?></p>
                        <form method="post" action="/login/" class="stack" style="margin-top:16px">
                            <input type="hidden" name="action" value="authenticate">
                            <label>Passwort<input type="password" name="password" autocomplete="current-password" placeholder="Passwort eingeben"></label>
                            <div class="actions">
                                <button type="submit">Anmelden</button>
                                <a class="button secondary" href="/login/">Neu starten</a>
                            </div>
                        </form>
                    <?php else: ?>
                        <div class="eyebrow">Schritt 1</div>
                        <h2>E-Mail eingeben</h2>
                        <form method="post" action="/login/" class="stack" style="margin-top:16px">
                            <input type="hidden" name="action" value="discover">
                            <label>E-Mail-Adresse<input type="email" name="email" value="<?= h((string) ($loginState['email'] ?? '')) ?>" autocomplete="email" placeholder="mitglied@unternehmen.de"></label>
                            <div class="actions"><button type="submit">Weiter</button></div>
                        </form>
                    <?php endif; ?>
                </article>
                <article class="card">
                    <div class="eyebrow">Hilfe beim Einstieg</div>
                    <h2>Wenn die Anmeldung nicht sofort klappt</h2>
                    <ul class="list">
                        <li>Prüfe zuerst, ob du die richtige berufliche E-Mail-Adresse verwendest.</li>
                        <li>Wenn du in mehreren Bereichen arbeitest, wirst du automatisch zur passenden Auswahl geführt.</li>
                        <li>Falls kein Zugang gefunden wird, brauchst du meist nur eine Einladung oder den Kontakt zur verantwortlichen Person.</li>
                    </ul>
                </article>
            </section>
        <?php elseif ($page === 'tenants'): ?>
            <section class="hero">
                <div class="eyebrow">Betreiber-Sicht</div>
                <h1>Mandanten</h1>
                <p>Hier sehen Betreiber, wie viele Tenants aktiv sind, wie die Anmeldung funktioniert und wo Mehrfachzuordnungen sauber abgefangen werden.</p>
            </section>

            <?php if ($tenantOverview !== null): ?>
                <section class="grid grid-4">
                    <?php foreach (($tenantOverview['metrics'] ?? []) as $metric): ?>
                        <article class="metric">
                            <strong><?= h((string) $metric['value']) ?></strong>
                            <h3><?= h((string) $metric['label']) ?></h3>
                            <p><?= h((string) $metric['detail']) ?></p>
                        </article>
                    <?php endforeach; ?>
                </section>

                <section class="card" style="margin-top:18px">
                    <div class="table">
                        <table>
                            <thead><tr><th>Tenant</th><th>Domain</th><th>Mitglieder</th><th>Admins</th><th>Login</th><th>Status</th></tr></thead>
                            <tbody>
                                <?php foreach (($tenantOverview['tenants'] ?? []) as $tenant): ?>
                                    <tr>
                                        <td><strong><?= h((string) $tenant['name']) ?></strong><br><span class="muted"><?= h((string) $tenant['tenant_key']) ?></span></td>
                                        <td><?= h((string) $tenant['domain']) ?></td>
                                        <td><?= num($tenant['member_count'] ?? 0) ?></td>
                                        <td><?= num($tenant['admin_count'] ?? 0) ?></td>
                                        <td><?= h((string) $tenant['login_mode']) ?></td>
                                        <td><?= ((string) ($tenant['status'] ?? 'active')) === 'active' ? badge('Aktiv', 'success') : badge('Prüfen', 'warning') ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </section>
            <?php else: ?>
                <section class="alert alert-warning"><?= h((string) $dbError) ?></section>
            <?php endif; ?>
        <?php elseif ($page === 'dashboard'): ?>
            <section class="hero">
                <div class="eyebrow">Tenant-Dashboard</div>
                <h1><?= h((string) $auth['tenant_name']) ?> Übersicht</h1>
                <p>Kontostand, Buchungen, Einzahlungen und die letzten Aktivitäten stehen direkt für diesen Tenant bereit.</p>
                <?php if (app_is_platform_admin($auth) && app_admin_user() !== null): ?>
                    <div class="actions" style="margin-top:18px">
                        <a class="button secondary" href="/admin/">Zur zentralen Verwaltung</a>
                        <a class="button" href="/members/">Personen und Admins verwalten</a>
                    </div>
                <?php endif; ?>
            </section>

            <section class="grid grid-4">
                <article class="metric"><strong><?= num($tenantDashboard['active_members'] ?? 0) ?></strong><h3>Aktive Mitglieder</h3><p>Aktive Mitgliedschaften im Tenant.</p></article>
                <article class="metric"><strong><?= money($tenantDashboard['coffee_volume'] ?? 0) ?></strong><h3>Kaffeeverbrauch</h3><p>Summe der Kaffee-Buchungen.</p></article>
                <article class="metric"><strong><?= money($tenantDashboard['payment_volume'] ?? 0) ?></strong><h3>Einzahlungen</h3><p>Summe der Zahlungsbuchungen.</p></article>
                <?php if (!empty($auth['acting_as_platform_admin'])): ?>
                    <article class="metric"><strong>Global</strong><h3>Zugriffsmodus</h3><p>Du verwaltest diesen Mandanten mit Global-Admin-Rechten.</p></article>
                <?php else: ?>
                    <article class="metric"><strong><?= money($memberSummary['balance'] ?? 0) ?></strong><h3>Mein Kontostand</h3><p>Saldo für den aktuell angemeldeten Nutzer.</p></article>
                <?php endif; ?>
            </section>

            <section class="grid grid-3" style="margin-top:18px">
                <article class="card">
                    <div class="eyebrow">Content</div>
                    <h2>Hinweise und FAQ</h2>
                    <p>Tenant-Admins pflegen Meldungen, Standardvorlagen und FAQ direkt im Mandantenkontext.</p>
                    <div class="actions" style="margin-top:14px"><a class="button secondary" href="/content/">Öffnen</a></div>
                </article>
                <article class="card">
                    <div class="eyebrow">Support</div>
                    <h2>Vorgänge mit Status</h2>
                    <p>Benutzer und Verantwortliche sehen Supportanfragen mit Routing, Verlauf und Bearbeitungsstand.</p>
                    <div class="actions" style="margin-top:14px"><a class="button secondary" href="/support/">Öffnen</a></div>
                </article>
                <article class="card">
                    <div class="eyebrow">Surveys</div>
                    <h2>Snapshots und Freigaben</h2>
                    <p>Umfragen werden live bearbeitet, Mitglieder sehen freigegebene Snapshots statt Entwürfe.</p>
                    <div class="actions" style="margin-top:14px"><a class="button secondary" href="/surveys/">Öffnen</a></div>
                </article>
            </section>

            <section class="grid grid-2" style="margin-top:18px">
                <?php if ($canManageTenant): ?>
                    <article class="card">
                        <div class="eyebrow">Kernfunktion</div>
                        <h2>Buchungen für Kaffee erfassen</h2>
                        <form method="post" action="/dashboard/" class="grid">
                            <input type="hidden" name="action" value="record-coffee">
                            <label>Mitglied<select name="member_id"><?php foreach ($members as $member): ?><option value="<?= h((string) $member['id']) ?>" <?= ((string) ($auth['member_id'] ?? '')) === (string) $member['id'] ? 'selected' : '' ?>><?= h((string) $member['display_name']) ?></option><?php endforeach; ?></select></label>
                            <label>Anzahl Striche<input type="number" name="strokes" min="1" step="1" value="1"></label>
                            <label>Preis pro Strich<input type="number" name="unit_price" min="0.01" step="0.01" value="0.50"></label>
                            <label>Buchungszeit<input type="datetime-local" name="booked_at" value="<?= date('Y-m-d\TH:i') ?>"></label>
                            <label>Quelle<input type="text" name="booking_source" value="self-service"></label>
                            <div class="actions"><button type="submit">Striche buchen</button></div>
                        </form>
                    </article>
                    <article class="card">
                        <div class="eyebrow">Kernfunktion</div>
                        <h2>Einzahlung erfassen</h2>
                        <form method="post" action="/dashboard/" class="grid">
                            <input type="hidden" name="action" value="record-payment">
                            <label>Mitglied<select name="member_id"><?php foreach ($members as $member): ?><option value="<?= h((string) $member['id']) ?>" <?= ((string) ($auth['member_id'] ?? '')) === (string) $member['id'] ? 'selected' : '' ?>><?= h((string) $member['display_name']) ?></option><?php endforeach; ?></select></label>
                            <label>Betrag<input type="number" name="amount" min="0.01" step="0.01" value="5.00"></label>
                            <label>Zahlungsart<select name="payment_method"><option value="manual">Manuell</option><option value="paypal">PayPal</option><option value="bank">Bank</option></select></label>
                            <label>Buchungszeit<input type="datetime-local" name="booked_at" value="<?= date('Y-m-d\TH:i') ?>"></label>
                            <div class="actions"><button type="submit">Einzahlung buchen</button></div>
                        </form>
                    </article>
                <?php else: ?>
                    <article class="card">
                        <div class="eyebrow">Mitgliedersicht</div>
                        <h2>Dein Bereich</h2>
                        <ul class="list">
                            <li>Hier siehst du deinen Kontostand, letzte Buchungen und aktuelle Hinweise.</li>
                            <li>Tenant-weite Buchungen und Mitgliederverwaltung bleiben bei den verantwortlichen Admins.</li>
                            <li>Wenn dir etwas fehlt, wende dich an den Betreiber deines Bereichs.</li>
                        </ul>
                    </article>
                    <article class="card">
                        <div class="eyebrow">Nächster Schritt</div>
                        <h2>Womit du direkt weiterkommst</h2>
                        <div class="actions">
                            <a class="button" href="/content/">Hinweise ansehen</a>
                        </div>
                    </article>
                <?php endif; ?>
            </section>

            <section class="card" style="margin-top:18px">
                <h2>Letzte Buchungen</h2>
                <div class="table">
                    <table>
                        <thead><tr><th>Zeit</th><th>Mitglied</th><th>Typ</th><th>Referenz</th><th>Betrag</th></tr></thead>
                        <tbody><?php foreach ($ledger as $entry): ?><tr><td><?= dt((string) ($entry['booked_at'] ?? '')) ?></td><td><?= h((string) ($entry['member_name'] ?? '')) ?></td><td><?= h((string) ($entry['entry_type'] ?? '')) ?></td><td><?= h((string) ($entry['reference_type'] ?? '')) ?></td><td><?= money($entry['amount'] ?? 0) ?></td></tr><?php endforeach; ?></tbody>
                    </table>
                </div>
            </section>
        <?php elseif ($page === 'members'): ?>
            <section class="hero">
                <div class="eyebrow">Mitgliederverwaltung</div>
                <h1>Mitglieder</h1>
                <p>Hier legst du neue Personen an, gibst Zugänge frei und weist bei Bedarf die Rolle als Mandanten-Admin zu.</p>
                <?php if (app_is_platform_admin($auth) && app_admin_user() !== null): ?>
                    <div class="actions" style="margin-top:18px">
                        <a class="button secondary" href="/admin/">Zur zentralen Verwaltung</a>
                        <a class="button secondary" href="/dashboard/">Mandanten-Dashboard</a>
                    </div>
                <?php endif; ?>
            </section>
            <section class="grid grid-2">
                <article class="card">
                    <h2><?= $editingMember !== null ? 'Person bearbeiten' : 'Neue Person anlegen' ?></h2>
                    <form method="post" action="/members/" class="grid">
                        <input type="hidden" name="action" value="save-member">
                        <input type="hidden" name="tenant_user_id" value="<?= h((string) $memberForm['tenant_user_id']) ?>">
                        <label>Name<input name="display_name" value="<?= h((string) $memberForm['display_name']) ?>" required></label>
                        <label>E-Mail-Adresse<input type="email" name="email" value="<?= h((string) $memberForm['email']) ?>" required></label>
                        <label>Status<select name="status"><option value="active"<?= $memberForm['status'] === 'active' ? ' selected' : '' ?>>Aktiv</option><option value="inactive"<?= $memberForm['status'] === 'inactive' ? ' selected' : '' ?>>Inaktiv</option></select></label>
                        <label>Passwort<input type="password" name="password" placeholder="<?= $editingMember !== null ? 'Nur für Passwortwechsel ausfüllen' : 'Für die erste Anmeldung erforderlich' ?>"></label>
                        <label class="checkbox" style="grid-column:1 / -1;display:flex;flex-direction:row;align-items:center;font-weight:600;">
                            <input type="checkbox" name="is_tenant_admin"<?= !empty($memberForm['is_tenant_admin']) ? ' checked' : '' ?> style="width:auto">
                            <span>Diese Person als Mandanten-Admin freischalten</span>
                        </label>
                        <div class="actions">
                            <button type="submit">Speichern</button>
                            <?php if ($editingMember !== null): ?>
                                <a class="button secondary" href="/members/">Neue Person erfassen</a>
                            <?php endif; ?>
                        </div>
                    </form>
                </article>
                <article class="card">
                    <h2>Was der Global-Admin hier sehen kann</h2>
                    <ul class="list">
                        <li>Alle Personen des Mandanten inklusive Rollen und Aktivstatus.</li>
                        <li>Ob ein Zugang nur Mitglied ist oder als Mandanten-Admin arbeiten darf.</li>
                        <li>Den Mandanten aus Sicht der operativen Verwaltung, ohne den Global-Admin als Mitglied anlegen zu müssen.</li>
                    </ul>
                </article>
            </section>
            <section class="card" style="margin-top:18px">
                <div class="table">
                    <table>
                        <thead><tr><th>Name</th><th>E-Mail</th><th>Status</th><th>Benutzer</th><th>Rollen</th><th>Aktion</th></tr></thead>
                        <tbody>
                            <?php foreach ($members as $member): ?>
                                <tr>
                                    <td><strong><?= h((string) $member['display_name']) ?></strong></td>
                                    <td><?= h((string) $member['email']) ?></td>
                                    <td><?= ((string) ($member['status'] ?? 'active')) === 'active' ? badge('Aktiv', 'success') : badge('Inaktiv', 'warning') ?></td>
                                    <td><?= h((string) ($member['user_display_name'] ?? '')) ?></td>
                                    <td><?= str_contains((string) ($member['role_keys'] ?? ''), 'tenant_admin') ? badge('Tenant-Admin', 'success') : badge('Mitglied') ?></td>
                                    <td><a class="button secondary" href="/members/?edit=<?= h((string) ($member['tenant_user_id'] ?? '')) ?>">Bearbeiten</a></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </section>
        <?php elseif ($page === 'ledger'): ?>
            <section class="hero"><div class="eyebrow">Buchungen</div><h1>Striche und Buchungen</h1><p>Kaffeeeinträge und alle zugehörigen Buchungen bleiben tenantweise nachvollziehbar.</p></section>
            <section class="grid grid-2">
                <article class="card">
                    <h2>Neuen Strich eintragen</h2>
                    <form method="post" action="/ledger/" class="grid">
                        <input type="hidden" name="action" value="record-coffee">
                        <label>Mitglied<select name="member_id"><?php foreach ($members as $member): ?><option value="<?= h((string) $member['id']) ?>"><?= h((string) $member['display_name']) ?></option><?php endforeach; ?></select></label>
                        <label>Anzahl Striche<input type="number" name="strokes" min="1" step="1" value="1"></label>
                        <label>Preis pro Strich<input type="number" name="unit_price" min="0.01" step="0.01" value="0.50"></label>
                        <label>Buchungszeit<input type="datetime-local" name="booked_at" value="<?= date('Y-m-d\TH:i') ?>"></label>
                        <div class="actions"><button type="submit">Buchen</button></div>
                    </form>
                </article>
                <article class="card"><h2>Was dieser Bereich abdeckt</h2><ul class="list"><li>Einzel- und Sammelbuchungen laufen in einem gemeinsamen Ablauf zusammen.</li><li>Jeder Verbrauch erzeugt automatisch den passenden Ledger-Eintrag.</li><li>Die letzten Buchungen bleiben je Tenant nachvollziehbar.</li></ul></article>
            </section>
            <section class="card" style="margin-top:18px"><div class="table"><table><thead><tr><th>Zeit</th><th>Mitglied</th><th>Typ</th><th>Referenz</th><th>Betrag</th></tr></thead><tbody><?php foreach ($ledger as $entry): ?><tr><td><?= dt((string) ($entry['booked_at'] ?? '')) ?></td><td><?= h((string) ($entry['member_name'] ?? '')) ?></td><td><?= h((string) ($entry['entry_type'] ?? '')) ?></td><td><?= h((string) ($entry['reference_type'] ?? '')) ?></td><td><?= money($entry['amount'] ?? 0) ?></td></tr><?php endforeach; ?></tbody></table></div></section>
        <?php elseif ($page === 'payments'): ?>
            <section class="hero"><div class="eyebrow">Einzahlungen</div><h1>Zahlungen</h1><p>Einzahlungen werden direkt in Zahlungstabelle und Ledger geschrieben.</p></section>
            <section class="grid grid-2">
                <article class="card">
                    <h2>Einzahlung buchen</h2>
                    <form method="post" action="/payments/" class="grid">
                        <input type="hidden" name="action" value="record-payment">
                        <label>Mitglied<select name="member_id"><?php foreach ($members as $member): ?><option value="<?= h((string) $member['id']) ?>"><?= h((string) $member['display_name']) ?></option><?php endforeach; ?></select></label>
                        <label>Betrag<input type="number" name="amount" min="0.01" step="0.01" value="5.00"></label>
                        <label>Zahlungsart<select name="payment_method"><option value="manual">Manuell</option><option value="paypal">PayPal</option><option value="bank">Bank</option></select></label>
                        <label>Buchungszeit<input type="datetime-local" name="booked_at" value="<?= date('Y-m-d\TH:i') ?>"></label>
                        <div class="actions"><button type="submit">Einzahlung speichern</button></div>
                    </form>
                </article>
                <article class="card"><h2>Wofür dieser Bereich da ist</h2><ul class="list"><li>Manuelle Einzahlungen sind direkt erfasst.</li><li>PayPal oder Bank können getrennt ausgewiesen werden.</li><li>Jede Zahlung erscheint sofort im Ledger.</li></ul></article>
            </section>
            <section class="card" style="margin-top:18px"><div class="table"><table><thead><tr><th>Zeit</th><th>Mitglied</th><th>Methode</th><th>Betrag</th></tr></thead><tbody><?php foreach ($payments as $entry): ?><tr><td><?= dt((string) ($entry['booked_at'] ?? '')) ?></td><td><?= h((string) ($entry['member_name'] ?? '')) ?></td><td><?= h((string) ($entry['payment_method'] ?? '')) ?></td><td><?= money($entry['amount'] ?? 0) ?></td></tr><?php endforeach; ?></tbody></table></div></section>
        <?php elseif ($page === 'content'): ?>
            <section class="hero"><div class="eyebrow">Hinweise und FAQ</div><h1>Hinweise und FAQ</h1><p>Hinweise und häufige Fragen werden pro Tenant gepflegt und direkt an die Mitglieder ausgespielt.</p></section>
            <section class="grid grid-2">
                <article class="card"><h2>Hinweise</h2><div class="stack"><?php if (($content['announcements'] ?? []) === []): ?><div class="metric"><p>Aktuell sind keine Hinweise vorhanden.</p></div><?php endif; ?><?php foreach (($content['announcements'] ?? []) as $entry): ?><div class="metric"><h3><?= h((string) $entry['title']) ?></h3><p><?= nl2br(h((string) $entry['message'])) ?></p><p class="muted">Sichtbar bis <?= dt((string) ($entry['visible_until'] ?? '')) ?></p></div><?php endforeach; ?></div></article>
                <article class="card"><h2>FAQ</h2><div class="stack"><?php if (($content['faq'] ?? []) === []): ?><div class="metric"><p>Aktuell keine FAQ vorhanden.</p></div><?php endif; ?><?php foreach (($content['faq'] ?? []) as $entry): ?><div class="metric"><h3><?= h((string) $entry['question']) ?></h3><p><?= nl2br(h((string) $entry['answer'])) ?></p></div><?php endforeach; ?></div></article>
            </section>
        <?php elseif ($page === 'settings'): ?>
            <section class="hero"><div class="eyebrow">Mandanten-Einstellungen</div><h1>Einstellungen</h1><p>Diese Einstellungen gelten nur für den aktuell geöffneten Mandanten und bleiben unabhängig von anderen Bereichen.</p></section>
            <section class="grid grid-2">
                <article class="card">
                    <h2>Einstellungen speichern</h2>
                    <form method="post" action="/settings/" class="grid">
                        <input type="hidden" name="action" value="save-settings">
                        <label>Standardpreis pro Strich<input type="number" name="default_unit_price" min="0.01" step="0.01" value="<?= h((string) ($tenantSettings['default_unit_price'] ?? '0.50')) ?>"></label>
                        <label>PDF-Listentitel<input name="pdf_list_title" value="<?= h((string) ($tenantSettings['pdf_list_title'] ?? 'Kaffeeliste')) ?>"></label>
                        <label>Beschriftung Vorderseite<input name="front_page_label" value="<?= h((string) ($tenantSettings['front_page_label'] ?? 'Vorderseite')) ?>"></label>
                        <label>Beschriftung Rückseite<input name="back_page_label" value="<?= h((string) ($tenantSettings['back_page_label'] ?? 'Rückseite')) ?>"></label>
                        <label>Zeilenhöhe PDF-Liste in mm<input type="number" name="pdf_row_height_mm" min="3.2" max="12" step="0.1" value="<?= h((string) ($tenantSettings['pdf_row_height_mm'] ?? '4.00')) ?>"></label>
                        <label>Standortbezeichnung<input name="location_label" value="<?= h((string) ($tenantSettings['location_label'] ?? '')) ?>"></label>
                        <label>Support-E-Mail<input type="email" name="support_email" value="<?= h((string) ($tenantSettings['support_email'] ?? '')) ?>"></label>
                        <label>Primärfarbe<input type="color" name="brand_color" value="<?= h((string) ($tenantSettings['brand_color'] ?? '#005e3f')) ?>"></label>
                        <label>Dunkle Primärfarbe<input type="color" name="brand_strong_color" value="<?= h((string) ($tenantSettings['brand_strong_color'] ?? '#00452f')) ?>"></label>
                        <label>Akzentfarbe<input type="color" name="accent_color" value="<?= h((string) ($tenantSettings['accent_color'] ?? '#c18a00')) ?>"></label>
                        <label>Hintergrundfarbe<input type="color" name="background_color" value="<?= h((string) ($tenantSettings['background_color'] ?? '#f4efe4')) ?>"></label>
                        <label>Kartenfarbe<input type="color" name="card_color" value="<?= h((string) ($tenantSettings['card_color'] ?? '#fffdf8')) ?>"></label>
                        <label class="checkbox" style="grid-column:1 / -1;display:flex;flex-direction:row;align-items:center;font-weight:600;">
                            <input type="checkbox" name="allow_self_service_booking"<?= (($tenantSettings['allow_self_service_booking'] ?? '1') === '1') ? ' checked' : '' ?> style="width:auto">
                            <span>Selbstbedienungs-Buchungen im Mandanten aktiv lassen</span>
                        </label>
                        <label style="grid-column:1 / -1;">Hinweis zu Einzahlungen<textarea name="payment_hint"><?= h((string) ($tenantSettings['payment_hint'] ?? '')) ?></textarea></label>
                        <div class="actions"><button type="submit">Einstellungen speichern</button></div>
                    </form>
                </article>
                <article class="card">
                    <h2>Aktuelle Lizenz</h2>
                    <div class="stack">
                        <div class="metric"><h3><?= h((string) ($tenantLicense['plan_name'] ?? 'Free')) ?></h3><p>Freigeschalteter Lizenzplan für diesen Mandanten.</p></div>
                        <div class="metric"><h3>Mitgliederrahmen</h3><p><?= isset($tenantLicense['member_limit']) && (int) $tenantLicense['member_limit'] > 0 ? h((string) $tenantLicense['member_limit']) . ' aktive Mitglieder im Standardumfang.' : 'Individuell vereinbart.' ?></p></div>
                        <div class="metric"><h3>Freigeschaltete Kernfunktionen</h3><ul class="list"><?php foreach (['tenant_settings' => 'Mandanten-Einstellungen', 'pdf_export' => 'PDF-Listen', 'paper_strike_entry' => 'Papierlisten-Erfassung'] as $featureKey => $featureLabel): ?><?php if (!empty($tenantLicense['features'][$featureKey])): ?><li><?= h($featureLabel) ?></li><?php endif; ?><?php endforeach; ?></ul></div>
                    </div>
                </article>
            </section>
            <section class="card" style="margin-top:18px">
                <h2>Farben im Tenant</h2>
                <div class="grid grid-4">
                    <?php foreach ([
                        'Primärfarbe' => $tenantSettings['brand_color'] ?? '#005e3f',
                        'Dunkle Primärfarbe' => $tenantSettings['brand_strong_color'] ?? '#00452f',
                        'Akzentfarbe' => $tenantSettings['accent_color'] ?? '#c18a00',
                        'Hintergrund' => $tenantSettings['background_color'] ?? '#f4efe4',
                    ] as $label => $color): ?>
                        <div class="metric">
                            <div style="width:100%;height:42px;border-radius:12px;border:1px solid var(--line);background:<?= h((string) $color) ?>"></div>
                            <h3 style="margin-top:12px"><?= h($label) ?></h3>
                            <p class="muted"><?= h((string) $color) ?></p>
                        </div>
                    <?php endforeach; ?>
                </div>
            </section>
        <?php elseif ($page === 'exports'): ?>
            <?php if (isset($_GET['view']) && $_GET['view'] === 'print' && is_array($activePrintList)): ?>
                <section class="hero"><div class="eyebrow">PDF-Vorschau</div><h1><?= h((string) $activePrintList['title']) ?></h1><p><?= (($printListGroups['mode'] ?? 'single') === 'single') ? 'Diese Liste wird als einzelne PDF-Seite erzeugt.' : 'Diese Liste wird als Vorder- und Rückseite erzeugt.' ?> Die Zeilenhöhe liegt aktuell bei <?= h((string) ($printListGroups['row_height_mm'] ?? ($tenantSettings['pdf_row_height_mm'] ?? '4.00'))) ?> mm.</p><div class="actions" style="margin-top:18px"><a class="button secondary" href="/exports/?list=<?= h((string) $activePrintList['id']) ?>">Zurück</a><a class="button" href="/exports/?download=print-list-pdf&list=<?= h((string) $activePrintList['id']) ?>">PDF herunterladen</a></div></section>
                <section class="card">
                    <div class="grid<?= (($printListGroups['mode'] ?? 'single') === 'single') ? '' : ' grid-2' ?>">
                        <article>
                            <h2><?= (($printListGroups['mode'] ?? 'single') === 'single') ? h((string) $activePrintList['title']) : h((string) ($tenantSettings['front_page_label'] ?? 'Vorderseite')) . ' / Vieltrinker' ?></h2>
                            <div class="table"><table><thead><tr><th>#</th><th>Person</th><th>Striche</th></tr></thead><tbody><?php foreach (($printListGroups['front'] ?? []) as $item): ?><tr><td><?= h((string) ($item['list_position'] ?? '')) ?></td><td><?= h((string) $item['member_name']) ?></td><td>________</td></tr><?php endforeach; ?></tbody></table></div>
                        </article>
                        <?php if (($printListGroups['mode'] ?? 'single') !== 'single'): ?>
                            <article>
                                <h2><?= h((string) ($tenantSettings['back_page_label'] ?? 'Rückseite')) ?> / Wenigtrinker</h2>
                                <div class="table"><table><thead><tr><th>#</th><th>Person</th><th>Striche</th></tr></thead><tbody><?php foreach (($printListGroups['back'] ?? []) as $item): ?><tr><td><?= h((string) ($item['list_position'] ?? '')) ?></td><td><?= h((string) $item['member_name']) ?></td><td>________</td></tr><?php endforeach; ?></tbody></table></div>
                            </article>
                        <?php endif; ?>
                    </div>
                </section>
            <?php else: ?>
                <section class="hero"><div class="eyebrow">Exporte und Drucklisten</div><h1>Drucklisten</h1><p>Hier erzeugst du druckfertige Listen, speicherst sie als PDF und buchst anschließend die Striche aus Vorder- und Rückseite zurück ins System.</p></section>
                <section class="grid grid-2">
                    <?php if ($hasPdfExportFeature): ?>
                    <article class="card">
                        <h2>Neue Druckliste erzeugen</h2>
                        <form method="post" action="/exports/" class="grid">
                            <input type="hidden" name="action" value="create-print-list">
                            <label>Titel<input name="title" value="<?= h((string) ($tenantSettings['pdf_list_title'] ?? 'Kaffeeliste')) ?>"></label>
                            <label>Preis pro Strich<input type="number" name="unit_price" min="0.01" step="0.01" value="<?= h((string) ($tenantSettings['default_unit_price'] ?? '0.50')) ?>"></label>
                            <label style="grid-column:1 / -1;">Notiz<textarea name="notes"></textarea></label>
                            <div class="actions"><button type="submit">Druckliste erzeugen</button></div>
                        </form>
                    </article>
                    <?php endif; ?>
                    <article class="card">
                        <h2><?= $hasBasicExportsFeature ? 'Basis-Exporte' : 'So funktioniert der PDF-Prozess' ?></h2>
                        <?php if ($hasBasicExportsFeature): ?>
                            <p>Für den laufenden Betrieb kannst du Mitglieder und Buchungen direkt als CSV exportieren.</p>
                            <div class="actions" style="margin-top:18px">
                                <a class="button secondary" href="/exports/?download=members-csv">Mitglieder als CSV</a>
                                <a class="button secondary" href="/exports/?download=ledger-csv">Ledger als CSV</a>
                            </div>
                        <?php else: ?>
                        <ul class="list">
                            <li>Druckliste erzeugen und direkt als saubere PDF-Datei herunterladen.</li>
                            <li>Nur bei vielen Mitgliedern wird automatisch eine Vorder- und Rückseite erzeugt.</li>
                            <li>Die Striche später gesammelt in derselben Liste nachtragen und verbuchen.</li>
                        </ul>
                        <?php endif; ?>
                    </article>
                </section>
                <?php if ($hasPdfExportFeature || $hasPaperStrikeEntryFeature): ?>
                <section class="card" style="margin-top:18px">
                    <h2>Vorhandene Drucklisten</h2>
                    <div class="table">
                        <table>
                            <thead><tr><th>Titel</th><th>Preis</th><th>Status</th><th>Erstellt</th><th>Aktionen</th></tr></thead>
                                <tbody><?php foreach ($printLists as $list): ?><tr><td><strong><?= h((string) $list['title']) ?></strong></td><td><?= money($list['unit_price'] ?? 0) ?></td><td><?= ((string) ($list['status'] ?? 'draft')) === 'imported' ? badge('Verbucht', 'success') : badge('Offen') ?></td><td><?= dt((string) ($list['created_at'] ?? '')) ?></td><td><div class="actions"><a class="button secondary" href="/exports/?list=<?= h((string) $list['id']) ?>">Bearbeiten</a><a class="button secondary" href="/exports/?download=print-list-pdf&list=<?= h((string) $list['id']) ?>">PDF herunterladen</a><a class="button secondary" href="/exports/?list=<?= h((string) $list['id']) ?>&view=print">Vorschau</a></div></td></tr><?php endforeach; ?></tbody>
                        </table>
                    </div>
                </section>
                <?php endif; ?>
                <?php if ($hasPaperStrikeEntryFeature && is_array($activePrintList)): ?>
                    <section class="card" style="margin-top:18px">
                        <h2>Druckliste nachtragen</h2>
                        <form method="post" action="/exports/">
                            <input type="hidden" name="action" value="apply-print-list">
                            <input type="hidden" name="print_list_id" value="<?= h((string) $activePrintList['id']) ?>">
                            <div class="grid grid-2">
                                <label>Buchungszeit<input type="datetime-local" name="booked_at" value="<?= date('Y-m-d\TH:i') ?>"></label>
                                <div class="metric"><h3>Status</h3><p><?= h((string) ($activePrintList['status'] ?? 'draft')) ?></p></div>
                            </div>
                            <div class="grid grid-2" style="margin-top:18px">
                                <article>
                                    <h3><?= (($printListGroups['mode'] ?? 'single') === 'single') ? 'Druckliste' : h((string) ($tenantSettings['front_page_label'] ?? 'Vorderseite')) . ' / Vieltrinker' ?></h3>
                                    <div class="table">
                                        <table>
                                            <thead><tr><th>Person</th><th>Striche</th><th>Bereits erfasst</th></tr></thead>
                                            <tbody><?php foreach (($printListGroups['front'] ?? []) as $item): ?><tr><td><?= h((string) $item['member_name']) ?></td><td><input type="number" min="0" step="1" name="strokes[<?= h((string) $item['id']) ?>][front]" value="<?= h((string) (($printListItemMap[(string) $item['id']]['front_strokes'] ?? 0))) ?>"></td><td><?= h((string) (($printListItemMap[(string) $item['id']]['front_strokes'] ?? 0))) ?></td></tr><?php endforeach; ?></tbody>
                                        </table>
                                    </div>
                                </article>
                                <?php if (($printListGroups['back'] ?? []) !== []): ?>
                                    <article>
                                        <h3><?= h((string) ($tenantSettings['back_page_label'] ?? 'Rückseite')) ?> / Wenigtrinker</h3>
                                        <div class="table">
                                            <table>
                                                <thead><tr><th>Person</th><th>Striche</th><th>Bereits erfasst</th></tr></thead>
                                                <tbody><?php foreach (($printListGroups['back'] ?? []) as $item): ?><tr><td><?= h((string) $item['member_name']) ?></td><td><input type="number" min="0" step="1" name="strokes[<?= h((string) $item['id']) ?>][back]" value="<?= h((string) (($printListItemMap[(string) $item['id']]['back_strokes'] ?? 0))) ?>"></td><td><?= h((string) (($printListItemMap[(string) $item['id']]['back_strokes'] ?? 0))) ?></td></tr><?php endforeach; ?></tbody>
                                            </table>
                                        </div>
                                    </article>
                                <?php endif; ?>
                            </div>
                            <?php if (false): ?><div class="table" style="display:none;margin-top:18px">
                                <table>
                                    <thead><tr><th>#</th><th>Person</th><th>Vorderseite</th><th>Rückseite</th><th>Gesamt</th></tr></thead>
                                    <tbody><?php foreach (($activePrintList['items'] ?? []) as $item): ?><tr><td><?= h((string) $item['list_position']) ?></td><td><?= h((string) $item['member_name']) ?></td><td><input type="number" min="0" step="1" name="strokes[<?= h((string) $item['id']) ?>][front]" value="<?= h((string) ($item['front_strokes'] ?? 0)) ?>"></td><td><input type="number" min="0" step="1" name="strokes[<?= h((string) $item['id']) ?>][back]" value="<?= h((string) ($item['back_strokes'] ?? 0)) ?>"></td><td><?= h((string) ($item['total_strokes'] ?? 0)) ?></td></tr><?php endforeach; ?></tbody>
                                </table>
                            </div><?php endif; ?>
                            <div class="actions" style="margin-top:18px"><button type="submit">Striche verbuchen</button><a class="button secondary" href="/exports/?list=<?= h((string) $activePrintList['id']) ?>&view=print">Zur PDF-Ansicht</a></div>
                        </form>
                    </section>
                <?php endif; ?>
            <?php endif; ?>
        <?php else: ?>
            <section class="alert alert-warning">Die angeforderte Seite konnte nicht gefunden werden.</section>
        <?php endif; ?>

        <p class="footer">Kaffeeliste SaaS | zentrale Anmeldung, Tenant-Verwaltung und alle Kernprozesse der modernen Kaffeeliste</p>
    </main>
</body>
</html>
