<?php

declare(strict_types=1);

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

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

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

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

function admin_badge(string $label, string $tone = 'neutral'): string
{
    $class = 'status';

    if ($tone === 'success') {
        $class .= ' status--success';
    } elseif ($tone === 'warning') {
        $class .= ' status--warning';
    } elseif ($tone === 'error') {
        $class .= ' status--danger';
    }

    return '<span class="' . $class . '">' . admin_h($label) . '</span>';
}

function admin_metric_value(array $metrics, string $label, string $fallback = '0'): string
{
    foreach ($metrics as $metric) {
        if ((string) ($metric['label'] ?? '') === $label) {
            return (string) ($metric['value'] ?? $fallback);
        }
    }

    return $fallback;
}

function admin_update_summary(array $items): array
{
    $summary = [
        'pending' => 0,
        'success' => 0,
        'failed' => 0,
        'running' => 0,
    ];

    foreach ($items as $item) {
        $status = (string) ($item['status'] ?? 'pending');

        if ($status === 'baselined') {
            $status = 'success';
        }

        if (array_key_exists($status, $summary)) {
            $summary[$status]++;
        }
    }

    return $summary;
}

function admin_summary_metrics(array $tenants, array $updates): array
{
    $tenantCount = count($tenants);
    $activeTenants = 0;
    $memberCount = 0;
    $adminCount = 0;
    $providerCount = 0;

    foreach ($tenants as $tenant) {
        if (($tenant['status'] ?? '') === 'active') {
            $activeTenants++;
        }

        $memberCount += (int) ($tenant['member_count'] ?? 0);
        $adminCount += (int) ($tenant['admin_count'] ?? 0);
        $providerCount += (int) ($tenant['provider_count'] ?? 0);
    }

    $updateSummary = admin_update_summary($updates);

    return [
        ['label' => 'Mandanten gesamt', 'value' => (string) $tenantCount, 'detail' => 'Mandanten im zentralen Portfolio.'],
        ['label' => 'Aktive Mandanten', 'value' => (string) $activeTenants, 'detail' => 'Bereiche mit aktivem Status.'],
        ['label' => 'Mitglieder gesamt', 'value' => (string) $memberCount, 'detail' => 'Aktive Zuordnungen über alle Mandanten.'],
        ['label' => 'Tenant-Admins', 'value' => (string) $adminCount, 'detail' => 'Verwaltungszugänge in den Mandanten.'],
        ['label' => 'Offene Updates', 'value' => (string) $updateSummary['pending'], 'detail' => 'Noch nicht eingespielte System-Updates.'],
        ['label' => 'SSO-Provider', 'value' => (string) $providerCount, 'detail' => 'Aktive Identitätsanbieter für die Anmeldung.'],
    ];
}

$path = parse_url((string) ($_SERVER['REQUEST_URI'] ?? '/admin/login/'), PHP_URL_PATH);
$path = is_string($path) ? rtrim($path, '/') : '/admin/login';
$page = match ($path) {
    '/admin', '/admin/' => 'overview',
    '/admin/login' => 'login',
    '/admin/tenants' => 'tenants',
    '/admin/updates' => 'updates',
    '/admin/migration' => 'migration',
    '/admin/logout' => 'logout',
    default => 'login',
};

$flash = app_flash();
$admin = app_admin_user();
$dbError = null;
$pdo = null;
$adminLogin = ['state' => app_admin_login_state(), 'message' => null, 'error' => null];
$tenants = [];
$editingTenant = null;
$summaryMetrics = [];
$licensePlans = [];
$updateItems = [];
$updateSummary = ['pending' => 0, 'success' => 0, 'failed' => 0, 'running' => 0];
$migrationItems = [];
$migrationSummary = ['pending' => 0, 'success' => 0, 'failed' => 0, 'running' => 0];
$appVersion = is_file(dirname(__DIR__) . '/version.php') ? (string) require dirname(__DIR__) . '/version.php' : 'unbekannt';

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST' && $page === 'logout') {
    if (hash_equals($_SESSION['admin_csrf'], (string) ($_POST['csrf'] ?? ''))) {
        app_logout();
        app_flash('Der Global-Admin wurde abgemeldet.', 'success');
    }

    app_redirect('/admin/login/');
}

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

if ($page === 'login' && $pdo instanceof PDO) {
    $adminLogin = app_handle_platform_admin_login($pdo);
    $admin = app_admin_user();
}

if (in_array($page, ['overview', 'tenants', 'updates', 'migration'], true)) {
    $admin = app_require_platform_admin();

    if (!$pdo instanceof PDO) {
        $dbError = $dbError ?? 'Die Zieldatenbank ist aktuell nicht erreichbar.';
    }
}

if (in_array($page, ['overview', 'tenants', 'updates', 'migration'], true) && $pdo instanceof PDO) {
    if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST' && !hash_equals($_SESSION['admin_csrf'], (string) ($_POST['csrf'] ?? ''))) {
        app_flash('Die Sitzung ist abgelaufen. Bitte lade die Seite neu.', 'error');
        app_redirect('/admin/' . ($page === 'overview' ? '' : $page . '/'));
    }

    if ($page === 'tenants') {
        app_handle_platform_tenant_action($pdo);
    }

    if ($page === 'updates' && (string) ($_POST['action'] ?? '') === 'run-updates') {
        try {
            $results = scripts_run_pending_updates(
                scripts_update_config_from_env(app_env()),
                'admin:' . (string) ($admin['email'] ?? 'platform')
            );

            $successful = count(array_filter($results, static fn(array $result): bool => ($result['status'] ?? '') === 'success'));
            $skipped = count(array_filter($results, static fn(array $result): bool => ($result['status'] ?? '') === 'skipped'));

            app_flash(
                $successful . ' Update(s) ausgeführt, ' . $skipped . ' bereits erledigt.',
                'success'
            );
        } catch (Throwable $exception) {
            app_flash('Die Updates konnten nicht abgeschlossen werden: ' . $exception->getMessage(), 'error');
        }

        app_redirect('/admin/updates/');
    }

    if ($page === 'migration' && (string) ($_POST['action'] ?? '') === 'run-migrations') {
        try {
            $results = scripts_run_pending_migrations(
                scripts_update_config_from_env(app_env()),
                'admin:' . (string) ($admin['email'] ?? 'platform')
            );

            $successful = count(array_filter($results, static fn(array $result): bool => in_array(($result['status'] ?? ''), ['success', 'baselined'], true)));
            $skipped = count(array_filter($results, static fn(array $result): bool => ($result['status'] ?? '') === 'skipped'));

            app_flash(
                $successful . ' Migration(en) verarbeitet, ' . $skipped . ' bereits erledigt.',
                'success'
            );
        } catch (Throwable $exception) {
            app_flash('Die Migrationen konnten nicht abgeschlossen werden: ' . $exception->getMessage(), 'error');
        }

        app_redirect('/admin/migration/');
    }

    $tenants = app_admin_tenant_list($pdo);
    $licensePlans = app_license_plan_options($pdo);
    $updateItems = scripts_list_updates_status(scripts_update_config_from_env(app_env()));
    $updateSummary = admin_update_summary($updateItems);
    $migrationItems = scripts_list_migrations_status(scripts_update_config_from_env(app_env()));
    $migrationSummary = admin_update_summary($migrationItems);
    $summaryMetrics = admin_summary_metrics($tenants, $updateItems);

    if ($page === 'tenants' && isset($_GET['edit']) && $_GET['edit'] !== '') {
        $editingTenant = $licensePlans !== []
            ? app_query_one(
                $pdo,
                <<<'SQL'
SELECT
    t.id,
    t.tenant_key,
    t.name,
    t.status,
    COALESCE(lp.plan_key, 'free') AS plan_key
FROM tenants t
LEFT JOIN tenant_licenses tl ON tl.tenant_id = t.id AND tl.status = 'active'
LEFT JOIN license_plans lp ON lp.id = tl.license_plan_id
WHERE t.id = :id
LIMIT 1
SQL,
                ['id' => (string) $_GET['edit']]
            )
            : app_query_one(
                $pdo,
                "SELECT id, tenant_key, name, status, 'free' AS plan_key FROM tenants WHERE id = :id LIMIT 1",
                ['id' => (string) $_GET['edit']]
            );
    }
}

$navItems = $admin === null
    ? [
        ['href' => '/admin/login/', 'label' => 'Login', 'page' => 'login'],
    ]
    : [
        ['href' => '/admin/', 'label' => 'Übersicht', 'page' => 'overview'],
        ['href' => '/admin/tenants/', 'label' => 'Mandanten', 'page' => 'tenants'],
        ['href' => '/admin/updates/', 'label' => 'Updates', 'page' => 'updates'],
        ['href' => '/admin/migration/', 'label' => 'Migrationen', 'page' => 'migration'],
    ];

$pageTitle = match ($page) {
    'login' => 'Kaffeeliste Admin - Login',
    'overview' => 'Kaffeeliste Admin - Übersicht',
    'tenants' => 'Kaffeeliste Admin - Mandanten',
    'updates' => 'Kaffeeliste Admin - Updates',
    'migration' => 'Kaffeeliste Admin - Migrationen',
    default => 'Kaffeeliste Admin',
};

$pageHero = match ($page) {
    'login' => [
        'kicker' => 'Global-Admin',
        'title' => 'Zentrale Administration für die Kaffeeliste.',
        'lead' => 'Dieser Zugang ist ausschließlich für die globale Verwaltung gedacht und bleibt bewusst vom Mitglieder-Login getrennt.',
        'badges' => ['Getrennter Zugang', 'Mandanten', 'Updates & Migrationen'],
        'aside' => [
            ['label' => 'Zugang', 'value' => 'Separat', 'detail' => 'Der Global-Admin bleibt bewusst vom Mitglieder-Login getrennt.'],
            ['label' => 'Oberfläche', 'value' => 'Zentral', 'detail' => 'Mandanten, Lizenzen und Betriebsaufgaben in einer Konsole.'],
            ['label' => 'Version', 'value' => $appVersion, 'detail' => 'Aktuell bereitgestellter Stand der Anwendung.'],
        ],
    ],
    'overview' => [
        'kicker' => 'Zentrale Übersicht',
        'title' => 'Portfolio, Lizenzen und Systemstände in einer Oberfläche.',
        'lead' => 'Die globale Verwaltung bündelt die wichtigsten Betriebsdaten und führt direkt in Lizenzpflege, Mandanten-Einstieg sowie Updates und Migrationen.',
        'badges' => ['Portfolio', 'Betrieb', 'Freischaltungen'],
        'aside' => [
            ['label' => 'Mandanten', 'value' => admin_metric_value($summaryMetrics, 'Mandanten gesamt'), 'detail' => 'Im zentralen Portfolio sichtbar.'],
            ['label' => 'Updates offen', 'value' => (string) $updateSummary['pending'], 'detail' => 'Direkt aus der Weboberfläche ausführbar.'],
            ['label' => 'Version', 'value' => $appVersion, 'detail' => 'Aktuell bereitgestellter Stand der Anwendung.'],
        ],
    ],
    'tenants' => [
        'kicker' => 'Mandanten-Verwaltung',
        'title' => 'Mandanten zentral anlegen, lizenzieren und betreten.',
        'lead' => 'Hier pflegt der Global-Admin die Stammdaten aller Mandanten und steuert, welche Funktionspakete pro Lizenz freigeschaltet sind.',
        'badges' => ['Portfolio', 'Lizenzen', 'Mandantenzugang'],
        'aside' => [
            ['label' => 'Aktiv', 'value' => admin_metric_value($summaryMetrics, 'Aktive Mandanten'), 'detail' => 'Mandanten mit aktivem Status.'],
            ['label' => 'Mitglieder', 'value' => admin_metric_value($summaryMetrics, 'Mitglieder gesamt'), 'detail' => 'Aktive Zuordnungen über alle Mandanten.'],
            ['label' => 'SSO-Provider', 'value' => admin_metric_value($summaryMetrics, 'SSO-Provider'), 'detail' => 'Aktive Identitätsanbieter auf der Plattform.'],
        ],
    ],
    'updates' => [
        'kicker' => 'Update-Center',
        'title' => 'System-Updates zentral prüfen und ausführen.',
        'lead' => 'Schema-Erweiterungen und Datenanpassungen werden versioniert dokumentiert und können direkt über die Weboberfläche angestoßen werden.',
        'badges' => ['Deployment', 'Web-Ausführung', 'Protokoll'],
        'aside' => [
            ['label' => 'Offen', 'value' => (string) $updateSummary['pending'], 'detail' => 'Warten auf Ausführung.'],
            ['label' => 'Erfolgreich', 'value' => (string) $updateSummary['success'], 'detail' => 'Bereits dokumentiert abgeschlossen.'],
            ['label' => 'Fehlgeschlagen', 'value' => (string) $updateSummary['failed'], 'detail' => 'Brauchen Aufmerksamkeit.'],
        ],
    ],
    default => [
        'kicker' => 'Migrations-Center',
        'title' => 'Datenbank-Migrationen zentral prüfen und ausführen.',
        'lead' => 'Die SQL-Migrationen aus database/migrations können hier nachvollziehbar über die zentrale Verwaltung eingespielt werden.',
        'badges' => ['Schema', 'Baseline', 'Web-Ausführung'],
        'aside' => [
            ['label' => 'Offen', 'value' => (string) $migrationSummary['pending'], 'detail' => 'Noch nicht eingespielt.'],
            ['label' => 'Erfolgreich', 'value' => (string) $migrationSummary['success'], 'detail' => 'Bereits protokolliert.'],
            ['label' => 'Fehlgeschlagen', 'value' => (string) $migrationSummary['failed'], 'detail' => 'Brauchen Aufmerksamkeit.'],
        ],
    ],
};

$flashClass = match ((string) ($flash['type'] ?? 'success')) {
    'error' => 'alert--danger',
    'warning' => 'alert--warning',
    default => 'alert--success',
};
?><!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="color-scheme" content="dark">
    <title><?= admin_h($pageTitle) ?></title>
    <style>
        :root {
            --line: rgba(143, 158, 191, 0.16);
            --line-strong: rgba(174, 189, 223, 0.26);
            --shadow: 0 24px 64px rgba(1, 6, 18, 0.36);
            --shadow-soft: 0 16px 34px rgba(1, 6, 18, 0.2);
            --surface-1: rgba(8, 12, 22, 0.84);
            --surface-2: rgba(13, 18, 31, 0.92);
            --surface-3: rgba(17, 24, 40, 0.96);
            --surface-soft: rgba(255, 255, 255, 0.04);
            --text-strong: #f4f7ff;
            --text-soft: rgba(219, 228, 248, 0.74);
            --text-faint: rgba(190, 202, 226, 0.52);
        }

        * { box-sizing: border-box; }

        body {
            margin: 0;
            min-height: 100vh;
            color: var(--text-strong);
            background:
                radial-gradient(circle at top center, rgba(88, 122, 255, 0.2), transparent 26%),
                radial-gradient(circle at 18% 18%, rgba(88, 122, 255, 0.16), transparent 22%),
                linear-gradient(180deg, #05070d 0%, #0a0f1a 48%, #0d1320 100%);
            font-family: "Aptos", "Segoe UI", sans-serif;
            line-height: 1.55;
        }

        h1,
        h2,
        h3,
        .hero__title,
        .brand__title {
            margin: 0;
            font-family: "Inter Tight", "Aptos", "Segoe UI", sans-serif;
            letter-spacing: -0.04em;
        }

        h2,
        h3 { margin-bottom: 0.35rem; }

        a { color: inherit; text-decoration: none; }
        a:hover { text-decoration: none; }

        code,
        .mono {
            font-family: Consolas, "SFMono-Regular", monospace;
        }

        .muted { color: var(--text-soft); }

        .marketing-shell {
            min-height: 100vh;
            padding: 0 0 24px;
        }

        .marketing-bar {
            position: sticky;
            top: 0;
            z-index: 30;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 14px;
            min-height: 80px;
            width: 100vw;
            margin-left: calc(50% - 50vw);
            margin-bottom: 20px;
            padding: 0 18px;
            border-bottom: 1px solid rgba(137, 154, 188, 0.18);
            background: rgba(8, 10, 18, 0.82);
            backdrop-filter: blur(16px);
        }

        .marketing-main {
            display: grid;
            gap: 18px;
            width: min(1240px, calc(100% - 48px));
            margin: 0 auto;
        }

        .marketing-footer {
            padding: 8px 24px 0;
            color: var(--text-faint);
            font-size: 0.9rem;
        }

        .marketing-footer__inner {
            width: min(1240px, calc(100% - 48px));
            margin: 0 auto;
            padding-top: 14px;
            border-top: 1px solid var(--line);
        }

        .brand {
            display: flex;
            align-items: center;
            gap: 10px;
            min-width: 0;
        }

        .brand__mark {
            width: 40px;
            height: 40px;
            border-radius: 10px;
            display: grid;
            place-items: center;
            color: #fff;
            font-weight: 800;
            background: linear-gradient(135deg, #587aff 0%, #243a91 100%);
        }

        .brand__text {
            display: grid;
            gap: 2px;
            min-width: 0;
        }

        .brand__title {
            font-size: 1.08rem;
            line-height: 1;
        }

        .brand__subtitle {
            color: var(--text-soft);
            font-size: 0.84rem;
        }

        .marketing-nav,
        .marketing-actions {
            display: flex;
            align-items: center;
            gap: 10px;
            flex-wrap: wrap;
        }

        .marketing-nav__link {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            min-height: 36px;
            padding: 0 0.3rem;
            border-radius: 6px;
            border: 1px solid transparent;
            color: rgba(231, 238, 255, 0.8);
            font-size: 1rem;
            font-weight: 600;
        }

        .marketing-nav__link:hover,
        .marketing-nav__link.is-active {
            color: #f4f7ff;
            background: rgba(255, 255, 255, 0.06);
            border-color: rgba(201, 214, 255, 0.12);
        }

        .marketing-actions form,
        .toolbar form {
            margin: 0;
        }

        .marketing-mobile {
            display: none;
            position: relative;
        }

        .marketing-mobile[open] { z-index: 40; }

        .marketing-mobile__toggle {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            min-width: 38px;
            min-height: 38px;
            padding: 0.24rem 0.46rem;
            border-radius: 8px;
            border: 1px solid rgba(201, 214, 255, 0.14);
            background: rgba(255, 255, 255, 0.04);
            color: #f4f7ff;
            list-style: none;
            cursor: pointer;
        }

        .marketing-mobile__toggle::-webkit-details-marker { display: none; }

        .marketing-mobile__toggle::before {
            content: "";
            display: block;
            width: 16px;
            height: 2px;
            border-radius: 999px;
            background: currentColor;
            box-shadow: 0 -5px 0 currentColor, 0 5px 0 currentColor;
        }

        .marketing-mobile__panel {
            position: absolute;
            right: 0;
            top: calc(100% + 10px);
            width: min(280px, calc(100vw - 24px));
            padding: 14px;
            border-radius: 16px;
            border: 1px solid rgba(163, 183, 255, 0.14);
            background: rgba(8, 10, 18, 0.96);
            box-shadow: 0 18px 36px rgba(1, 5, 13, 0.45);
        }

        .marketing-mobile__stack {
            display: grid;
            gap: 8px;
        }

        .marketing-mobile__stack .marketing-nav__link {
            justify-content: flex-start;
            padding: 0.55rem 0.7rem;
            background: rgba(255, 255, 255, 0.04);
            border-color: rgba(201, 214, 255, 0.1);
        }

        .marketing-mobile__footer {
            margin-top: 12px;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            flex-wrap: wrap;
        }

        .button,
        button,
        input[type="submit"] {
            appearance: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            border: 0;
            border-radius: 10px;
            padding: 0.72rem 1rem;
            background: linear-gradient(135deg, #587aff 0%, #243a91 100%);
            color: #fff;
            font: inherit;
            font-weight: 700;
            cursor: pointer;
            box-shadow: 0 12px 24px rgba(36, 58, 145, 0.22);
        }

        .button--ghost {
            background: rgba(255, 255, 255, 0.03);
            color: var(--text-strong);
            border: 1px solid rgba(255, 255, 255, 0.12);
            box-shadow: none;
        }

        .hero {
            display: grid;
            gap: 16px;
            padding: 20px;
            border: 1px solid var(--line);
            border-radius: 18px;
            background: linear-gradient(135deg, rgba(14, 20, 34, 0.98), rgba(10, 15, 26, 0.96));
            box-shadow: var(--shadow);
        }

        .hero--split {
            grid-template-columns: minmax(0, 1.2fr) minmax(300px, 0.8fr);
            align-items: stretch;
        }

        .hero__content,
        .hero__aside {
            display: grid;
            gap: 18px;
        }

        .hero__kicker,
        .card__eyebrow {
            margin: 0;
            color: #8aa0d0;
            text-transform: uppercase;
            letter-spacing: 0.15em;
            font-size: 0.8rem;
            font-weight: 700;
        }

        .hero__title {
            font-size: clamp(2rem, 4vw, 3.5rem);
            line-height: 1.05;
        }

        .hero__lead {
            margin: 0;
            max-width: 70ch;
            color: var(--text-soft);
            font-size: 1.02rem;
        }

        .hero__meta,
        .toolbar {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
        }

        .toolbar {
            margin-top: 18px;
            align-items: center;
        }

        .toolbar--compact {
            margin-top: 0;
            gap: 10px;
        }

        .badge,
        .pill {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            border-radius: 999px;
            border: 1px solid var(--line);
            background: var(--surface-soft);
            padding: 0.42rem 0.75rem;
            font-size: 0.82rem;
            font-weight: 600;
            color: var(--text-strong);
        }

        .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--summary { grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); }

        .split {
            display: grid;
            gap: 18px;
            grid-template-columns: minmax(0, 1.2fr) minmax(0, 0.8fr);
        }

        .card,
        .panel,
        .form-panel,
        .table-card {
            border: 1px solid var(--line);
            border-radius: 14px;
            background: var(--surface-2);
            box-shadow: var(--shadow);
            padding: 16px;
        }

        .table-card {
            overflow: hidden;
            padding: 0;
        }

        .table-card__header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 16px;
            padding: 22px 22px 12px;
        }

        .table-card__body {
            padding: 0 22px 22px;
            overflow-x: auto;
        }

        .metric {
            display: grid;
            gap: 8px;
        }

        .metric--compact {
            padding: 18px 20px;
            border-radius: 14px;
            background: rgba(255, 255, 255, 0.04);
            border: 1px solid rgba(255, 255, 255, 0.06);
        }

        .metric__value {
            font-size: clamp(1.6rem, 2.5vw, 2.4rem);
            font-weight: 800;
            letter-spacing: -0.03em;
        }

        .metric__label,
        .note,
        .timeline__meta,
        .table-note,
        table small {
            color: var(--text-soft);
        }

        .stack {
            display: grid;
            gap: 14px;
        }

        .alert {
            padding: 14px 16px;
            border-radius: 14px;
            border: 1px solid var(--line);
            background: rgba(255, 255, 255, 0.04);
            box-shadow: var(--shadow-soft);
        }

        .alert--success {
            background: rgba(58, 182, 116, 0.12);
            border-color: rgba(58, 182, 116, 0.22);
        }

        .alert--warning {
            background: rgba(224, 154, 70, 0.14);
            border-color: rgba(224, 154, 70, 0.22);
        }

        .alert--danger {
            background: rgba(195, 82, 82, 0.16);
            border-color: rgba(195, 82, 82, 0.24);
        }

        .status {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 0.38rem 0.65rem;
            border-radius: 999px;
            background: rgba(88, 122, 255, 0.12);
            color: #d9e2ff;
            font-weight: 700;
            font-size: 0.82rem;
        }

        .status--success {
            background: rgba(58, 182, 116, 0.18);
            color: #ccffe4;
        }

        .status--warning {
            background: rgba(224, 154, 70, 0.14);
            color: #ffd7a1;
        }

        .status--danger {
            background: rgba(195, 82, 82, 0.16);
            color: #ffd1d1;
        }

        .form-grid {
            display: grid;
            gap: 16px;
        }

        .form-grid--2 {
            grid-template-columns: repeat(2, minmax(0, 1fr));
        }

        .form-grid__full {
            grid-column: 1 / -1;
        }

        .field,
        label {
            display: grid;
            gap: 8px;
            font-size: 0.9rem;
            font-weight: 700;
        }

        input,
        select {
            width: 100%;
            border: 1px solid rgba(255, 255, 255, 0.08);
            border-radius: 12px;
            background: rgba(255, 255, 255, 0.04);
            padding: 0.85rem 0.95rem;
            font: inherit;
            color: var(--text-strong);
        }

        input::placeholder {
            color: rgba(219, 228, 248, 0.42);
        }

        .note,
        .callout,
        .timeline__item,
        .feature-list__item {
            padding: 14px 16px;
            border-radius: 14px;
            background: rgba(255, 255, 255, 0.04);
            border: 1px solid rgba(255, 255, 255, 0.06);
        }

        .callout strong,
        .timeline__title,
        .feature-list__title {
            display: block;
            margin: 0 0 4px;
            color: var(--text-strong);
            font-weight: 700;
        }

        .timeline,
        .feature-list {
            display: grid;
            gap: 12px;
        }

        .feature-list__item {
            display: flex;
            gap: 12px;
            align-items: flex-start;
        }

        .feature-list__badge {
            flex: 0 0 auto;
            width: 34px;
            height: 34px;
            border-radius: 12px;
            display: grid;
            place-items: center;
            background: rgba(88, 122, 255, 0.12);
            color: #d9e2ff;
            font-weight: 800;
        }

        .feature-list__copy {
            margin: 0;
            color: var(--text-soft);
            font-size: 0.94rem;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            min-width: 760px;
        }

        th,
        td {
            padding: 0.95rem 0.8rem;
            border-bottom: 1px solid rgba(255, 255, 255, 0.06);
            text-align: left;
            vertical-align: top;
        }

        th {
            font-size: 0.8rem;
            text-transform: uppercase;
            letter-spacing: 0.08em;
            color: var(--text-soft);
            font-weight: 700;
            background: rgba(255, 255, 255, 0.03);
        }

        tr:last-child td { border-bottom: 0; }

        table small {
            display: block;
            margin-top: 4px;
            line-height: 1.5;
        }

        .list-reset {
            margin: 0;
            padding: 0;
            list-style: none;
        }

        .list-reset li + li { margin-top: 12px; }

        @media (max-width: 980px) {
            .marketing-shell {
                padding: 0 0 18px;
            }

            .marketing-main,
            .marketing-footer__inner {
                width: calc(100% - 24px);
            }

            .marketing-bar {
                min-height: 72px;
                margin-bottom: 16px;
                padding: 0 12px;
            }

            .marketing-nav,
            .marketing-actions { display: none; }

            .marketing-mobile { display: block; }

            .hero--split,
            .split,
            .grid--2,
            .grid--3,
            .form-grid--2 {
                grid-template-columns: 1fr;
            }

            .hero,
            .card,
            .panel,
            .form-panel { padding: 16px; }

            .table-card { padding: 0; }

            table { min-width: 0; }
        }
    </style>
</head>
<body>
<div class="marketing-shell">
    <header class="marketing-bar">
        <a class="brand" href="<?= $admin !== null ? '/admin/' : '/admin/login/' ?>">
            <span class="brand__mark">K</span>
            <span class="brand__text">
                <span class="brand__title">Kaffeeliste Admin</span>
                <span class="brand__subtitle">Zentrale Verwaltung für Mandanten und Betrieb</span>
            </span>
        </a>

        <nav class="marketing-nav" aria-label="Admin-Navigation">
            <?php foreach ($navItems as $item): ?>
                <a href="<?= admin_h((string) $item['href']) ?>" class="marketing-nav__link<?= $page === $item['page'] ? ' is-active' : '' ?>">
                    <?= admin_h((string) $item['label']) ?>
                </a>
            <?php endforeach; ?>
        </nav>

        <div class="marketing-actions">
            <?php if ($admin !== null): ?>
                <span class="pill"><?= admin_h((string) ($admin['display_name'] ?? 'Global-Admin')) ?></span>
                <a class="button button--ghost" href="/login/">Mitglieder-Login</a>
                <form method="post" action="/admin/logout/">
                    <input type="hidden" name="csrf" value="<?= admin_h($_SESSION['admin_csrf']) ?>">
                    <button type="submit" class="button--ghost">Abmelden</button>
                </form>
            <?php else: ?>
                <a class="button button--ghost" href="/login/">Mitglieder-Login</a>
            <?php endif; ?>
        </div>

        <details class="marketing-mobile">
            <summary class="marketing-mobile__toggle" aria-label="Menü öffnen"></summary>
            <div class="marketing-mobile__panel">
                <div class="marketing-mobile__stack">
                    <?php foreach ($navItems as $item): ?>
                        <a href="<?= admin_h((string) $item['href']) ?>" class="marketing-nav__link<?= $page === $item['page'] ? ' is-active' : '' ?>">
                            <?= admin_h((string) $item['label']) ?>
                        </a>
                    <?php endforeach; ?>
                </div>
                <div class="marketing-mobile__footer">
                    <a class="button button--ghost" href="/login/">Mitglieder-Login</a>
                    <?php if ($admin !== null): ?>
                        <form method="post" action="/admin/logout/">
                            <input type="hidden" name="csrf" value="<?= admin_h($_SESSION['admin_csrf']) ?>">
                            <button type="submit" class="button--ghost">Abmelden</button>
                        </form>
                    <?php endif; ?>
                </div>
            </div>
        </details>
    </header>

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

        <section class="hero hero--split">
            <div class="hero__content">
                <div>
                    <p class="hero__kicker"><?= admin_h((string) $pageHero['kicker']) ?></p>
                    <h1 class="hero__title"><?= admin_h((string) $pageHero['title']) ?></h1>
                    <p class="hero__lead"><?= admin_h((string) $pageHero['lead']) ?></p>
                </div>
                <div class="hero__meta">
                    <?php foreach (($pageHero['badges'] ?? []) as $badge): ?>
                        <span class="badge"><?= admin_h((string) $badge) ?></span>
                    <?php endforeach; ?>
                </div>
            </div>
            <aside class="hero__aside">
                <?php foreach (($pageHero['aside'] ?? []) as $metric): ?>
                    <article class="card metric metric--compact">
                        <p class="metric__label"><?= admin_h((string) ($metric['label'] ?? '')) ?></p>
                        <div class="metric__value"><?= admin_h((string) ($metric['value'] ?? '')) ?></div>
                        <p class="muted"><?= admin_h((string) ($metric['detail'] ?? '')) ?></p>
                    </article>
                <?php endforeach; ?>
            </aside>
        </section>

        <?php if ($page === 'login' && $adminLogin['error'] !== null): ?>
            <section class="alert alert--danger"><?= admin_h((string) $adminLogin['error']) ?></section>
        <?php endif; ?>

        <?php if ($page === 'login' && $adminLogin['message'] !== null): ?>
            <section class="alert alert--success"><?= admin_h((string) $adminLogin['message']) ?></section>
        <?php endif; ?>

        <?php if ($dbError !== null): ?>
            <section class="alert alert--warning"><?= admin_h($dbError) ?></section>
        <?php endif; ?>

        <?php if ($page === 'login'): ?>
            <section class="split">
                <article class="form-panel">
                    <p class="card__eyebrow">Zugang</p>
                    <h2>Anmelden</h2>
                    <form method="post" action="/admin/login/" class="form-grid" style="margin-top: 18px;">
                        <input type="hidden" name="action" value="admin-login">
                        <input type="hidden" name="csrf" value="<?= admin_h($_SESSION['admin_csrf']) ?>">
                        <label>
                            E-Mail-Adresse
                            <input type="email" name="email" value="<?= admin_h((string) ($adminLogin['state']['email'] ?? '')) ?>" autocomplete="email" placeholder="admin@kaffeeliste.example">
                        </label>
                        <label>
                            Passwort
                            <input type="password" name="password" autocomplete="current-password" placeholder="••••••••">
                        </label>
                        <div class="toolbar">
                            <button type="submit">Als Global-Admin anmelden</button>
                            <a class="button button--ghost" href="/login/">Mitglieder-Login öffnen</a>
                        </div>
                    </form>
                </article>

                <article class="panel">
                    <p class="card__eyebrow">Ablauf</p>
                    <h2>So ist der Zugang gedacht</h2>
                    <div class="timeline" style="margin-top: 18px;">
                        <div class="timeline__item">
                            <p class="timeline__title">1. Globalen Zugang verwenden</p>
                            <p class="timeline__meta">Die Anmeldung prüft gezielt Plattform-Admins und bleibt vom normalen Mitglieder-Login getrennt.</p>
                        </div>
                        <div class="timeline__item">
                            <p class="timeline__title">2. Portfolio öffnen</p>
                            <p class="timeline__meta">Nach dem Login stehen Übersicht, Mandanten-Verwaltung, Updates und Migrationen zentral bereit.</p>
                        </div>
                        <div class="timeline__item">
                            <p class="timeline__title">3. Betrieb steuern</p>
                            <p class="timeline__meta">Mandanten wechseln, Lizenzen anpassen und Systemläufe direkt in der Oberfläche ausführen.</p>
                        </div>
                    </div>
                    <div class="note" style="margin-top: 18px;">
                        Der erste Global-Admin wird im Installer angelegt oder aktualisiert. Grundlage bleibt
                        <code>users.is_platform_admin = 1</code> plus das gespeicherte Passwort.
                    </div>
                </article>
            </section>

            <section class="grid grid--3">
                <article class="card">
                    <p class="card__eyebrow">Einrichtung</p>
                    <h2>Was vorher bereitstehen sollte</h2>
                    <ul class="list-reset" style="margin-top: 18px;">
                        <li>
                            <strong>Datenbank erreichbar</strong><br>
                            <span class="muted">Die Admin-Oberfläche prüft zentrale Tabellen und den Plattform-Admin gegen dieselbe Zielumgebung.</span>
                        </li>
                        <li>
                            <strong>Installer gelaufen</strong><br>
                            <span class="muted">Der erste Zugang wird über den Installer vorbereitet und kann dort später auch aktualisiert werden.</span>
                        </li>
                    </ul>
                </article>

                <article class="card">
                    <p class="card__eyebrow">Trennung</p>
                    <h2>Bewusst eigener Admin-Bereich</h2>
                    <div class="callout" style="margin-top: 18px;">
                        <strong>Kein Mischzugang</strong>
                        Globale Betriebsaufgaben bleiben von den täglichen Mitglieder- und Tenant-Abläufen getrennt.
                    </div>
                </article>

                <article class="card">
                    <p class="card__eyebrow">Systemstand</p>
                    <h2>Aktuell bereitgestellt</h2>
                    <div class="stack" style="margin-top: 18px;">
                        <div class="metric metric--compact">
                            <p class="metric__label">Version</p>
                            <div class="metric__value mono"><?= admin_h($appVersion) ?></div>
                            <p class="muted">Aktueller Anwendungsstand.</p>
                        </div>
                        <div class="metric metric--compact">
                            <p class="metric__label">Bereiche</p>
                            <div class="metric__value">4</div>
                            <p class="muted">Übersicht, Mandanten, Updates und Migrationen stehen nach dem Login bereit.</p>
                        </div>
                    </div>
                </article>
            </section>
        <?php elseif ($page === 'overview'): ?>
            <?php if ($summaryMetrics !== []): ?>
                <section class="grid grid--summary">
                    <?php foreach ($summaryMetrics as $metric): ?>
                        <article class="card metric metric--compact">
                            <p class="metric__label"><?= admin_h((string) $metric['label']) ?></p>
                            <div class="metric__value"><?= admin_h((string) $metric['value']) ?></div>
                            <p class="muted"><?= admin_h((string) $metric['detail']) ?></p>
                        </article>
                    <?php endforeach; ?>
                </section>
            <?php endif; ?>

            <section class="grid grid--3">
                <article class="card">
                    <p class="card__eyebrow">Sitzung</p>
                    <h2>Angemeldet als</h2>
                    <div class="stack" style="margin-top: 18px;">
                        <div class="metric metric--compact">
                            <p class="metric__label">Global-Admin</p>
                            <div class="metric__value"><?= admin_h((string) ($admin['display_name'] ?? '')) ?></div>
                            <p class="muted"><?= admin_h((string) ($admin['email'] ?? '')) ?></p>
                        </div>
                        <div class="metric metric--compact">
                            <p class="metric__label">Version</p>
                            <div class="metric__value mono"><?= admin_h($appVersion) ?></div>
                            <p class="muted">Bereitgestellter Stand der Anwendung.</p>
                        </div>
                    </div>
                </article>

                <article class="card">
                    <p class="card__eyebrow">Schnellzugriffe</p>
                    <h2>Direkt weiterarbeiten</h2>
                    <div class="toolbar">
                        <a class="button" href="/admin/tenants/">Mandanten verwalten</a>
                        <a class="button button--ghost" href="/admin/updates/">Updates prüfen</a>
                        <a class="button button--ghost" href="/admin/migration/">Migrationen prüfen</a>
                        <a class="button button--ghost" href="/login/">Mitglieder-Login</a>
                    </div>
                    <div class="note" style="margin-top: 18px;">
                        Mandanten können direkt mit passendem Lizenzplan angelegt werden. Updates und Migrationen laufen ohne separaten Shell-Zugriff aus derselben Konsole.
                    </div>
                </article>

                <article class="panel">
                    <p class="card__eyebrow">Systemlage</p>
                    <h2>Was gerade wichtig ist</h2>
                    <div class="timeline" style="margin-top: 18px;">
                        <div class="timeline__item">
                            <p class="timeline__title">Updates</p>
                            <p class="timeline__meta"><?= admin_h((string) $updateSummary['pending']) ?> offen, <?= admin_h((string) $updateSummary['failed']) ?> fehlgeschlagen, <?= admin_h((string) $updateSummary['success']) ?> erfolgreich.</p>
                        </div>
                        <div class="timeline__item">
                            <p class="timeline__title">Migrationen</p>
                            <p class="timeline__meta"><?= admin_h((string) $migrationSummary['pending']) ?> offen, <?= admin_h((string) $migrationSummary['failed']) ?> fehlgeschlagen, <?= admin_h((string) $migrationSummary['success']) ?> erfolgreich.</p>
                        </div>
                        <div class="timeline__item">
                            <p class="timeline__title">Mandantenzugriff</p>
                            <p class="timeline__meta">Als Global-Admin kannst du jeden Mandanten öffnen und operative Pfade direkt prüfen.</p>
                        </div>
                    </div>
                </article>
            </section>
        <?php elseif ($page === 'tenants'): ?>
            <section class="split">
                <article class="form-panel">
                    <p class="card__eyebrow">Pflege</p>
                    <h2><?= $editingTenant !== null ? 'Mandanten bearbeiten' : 'Neuen Mandanten anlegen' ?></h2>
                    <form method="post" action="/admin/tenants/" class="form-grid form-grid--2" style="margin-top: 18px;">
                        <input type="hidden" name="csrf" value="<?= admin_h($_SESSION['admin_csrf']) ?>">
                        <input type="hidden" name="action" value="save-tenant">
                        <input type="hidden" name="tenant_id" value="<?= admin_h((string) ($editingTenant['id'] ?? '')) ?>">
                        <label>
                            Mandanten-Key
                            <input name="tenant_key" value="<?= admin_h((string) ($editingTenant['tenant_key'] ?? '')) ?>" placeholder="werk-berlin">
                        </label>
                        <label>
                            Name
                            <input name="name" value="<?= admin_h((string) ($editingTenant['name'] ?? '')) ?>" placeholder="Werk Berlin">
                        </label>
                        <label>
                            Status
                            <select name="status">
                                <?php foreach (['active' => 'Aktiv', 'inactive' => 'Inaktiv', 'sandbox' => 'Sandbox'] as $value => $label): ?>
                                    <option value="<?= admin_h($value) ?>"<?= (($editingTenant['status'] ?? 'active') === $value) ? ' selected' : '' ?>><?= admin_h($label) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </label>
                        <label>
                            Lizenzplan
                            <select name="plan_key">
                                <?php foreach ($licensePlans as $plan): ?>
                                    <option value="<?= admin_h((string) $plan['plan_key']) ?>"<?= ((string) ($editingTenant['plan_key'] ?? 'free') === (string) $plan['plan_key']) ? ' selected' : '' ?>>
                                        <?= admin_h((string) $plan['name']) ?><?= isset($plan['member_limit']) && (int) $plan['member_limit'] > 0 ? ' bis ' . admin_h((string) $plan['member_limit']) . ' Mitglieder' : ' individuell' ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </label>
                        <div class="toolbar form-grid__full">
                            <button type="submit">Speichern</button>
                            <?php if ($editingTenant !== null): ?>
                                <a class="button button--ghost" href="/admin/tenants/">Bearbeitung zurücksetzen</a>
                            <?php endif; ?>
                            <a class="button button--ghost" href="/admin/">Zur Übersicht</a>
                        </div>
                    </form>
                    <?php if ($licensePlans === []): ?>
                        <div class="note" style="margin-top: 18px;">
                            Die Lizenzpläne sind noch nicht verfügbar. Bitte zuerst die System-Updates ausführen.
                        </div>
                    <?php endif; ?>
                </article>

                <article class="panel">
                    <p class="card__eyebrow">Lizenzrahmen</p>
                    <h2>Wie die Pläne gedacht sind</h2>
                    <div class="feature-list" style="margin-top: 18px;">
                        <div class="feature-list__item">
                            <div class="feature-list__badge">F</div>
                            <div>
                                <p class="feature-list__title">Free</p>
                                <p class="feature-list__copy">Bis zu 10 aktive Mitglieder inklusive Mandanten-Einstellungen, PDF-Listen und Papier-Nacherfassung.</p>
                            </div>
                        </div>
                        <div class="feature-list__item">
                            <div class="feature-list__badge">S</div>
                            <div>
                                <p class="feature-list__title">Starter & Team</p>
                                <p class="feature-list__copy">Mehr Mitglieder für wachsende Standorte, weiterhin mit dem Drucklisten-Prozess als Kernfunktion.</p>
                            </div>
                        </div>
                        <div class="feature-list__item">
                            <div class="feature-list__badge">B</div>
                            <div>
                                <p class="feature-list__title">Business & Enterprise</p>
                                <p class="feature-list__copy">Zusätzliche Erweiterungen wie SSO, Benachrichtigungen, Auswertungen und individuelle Freischaltungen.</p>
                            </div>
                        </div>
                    </div>
                </article>
            </section>

            <section class="table-card">
                <div class="table-card__header">
                    <div>
                        <p class="card__eyebrow">Portfolio</p>
                        <h2>Vorhandene Mandanten</h2>
                    </div>
                    <span class="pill"><?= admin_h((string) count($tenants)) ?> sichtbar</span>
                </div>
                <div class="table-card__body">
                    <table>
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Key</th>
                                <th>Status</th>
                                <th>Lizenz</th>
                                <th>Mitglieder</th>
                                <th>Admins</th>
                                <th>SSO</th>
                                <th>Aktionen</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($tenants === []): ?>
                                <tr>
                                    <td colspan="8">Noch keine Mandanten vorhanden.</td>
                                </tr>
                            <?php endif; ?>
                            <?php foreach ($tenants as $tenant): ?>
                                <?php
                                $tenantStatus = (string) ($tenant['status'] ?? 'inactive');
                                $tenantLabel = match ($tenantStatus) {
                                    'active' => 'Aktiv',
                                    'sandbox' => 'Sandbox',
                                    default => 'Inaktiv',
                                };
                                $tenantTone = match ($tenantStatus) {
                                    'active' => 'success',
                                    'sandbox' => 'warning',
                                    default => 'neutral',
                                };
                                ?>
                                <tr>
                                    <td>
                                        <strong><?= admin_h((string) $tenant['name']) ?></strong>
                                        <small class="table-note"><?= admin_h((string) ($tenant['plan_key'] ?? 'free')) ?></small>
                                    </td>
                                    <td class="mono"><?= admin_h((string) $tenant['tenant_key']) ?></td>
                                    <td><?= admin_badge($tenantLabel, $tenantTone) ?></td>
                                    <td><?= admin_badge((string) ($tenant['plan_name'] ?? 'Free')) ?></td>
                                    <td><?= admin_h((string) $tenant['member_count']) ?></td>
                                    <td><?= admin_h((string) $tenant['admin_count']) ?></td>
                                    <td><?= admin_h((string) $tenant['provider_count']) ?></td>
                                    <td>
                                        <div class="toolbar toolbar--compact">
                                            <a class="button button--ghost" href="/admin/tenants/?edit=<?= admin_h((string) $tenant['id']) ?>">Bearbeiten</a>
                                            <form method="post" action="/admin/tenants/">
                                                <input type="hidden" name="csrf" value="<?= admin_h($_SESSION['admin_csrf']) ?>">
                                                <input type="hidden" name="action" value="switch-tenant">
                                                <input type="hidden" name="tenant_id" value="<?= admin_h((string) $tenant['id']) ?>">
                                                <button type="submit">Mandant öffnen</button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </section>
        <?php elseif ($page === 'updates'): ?>
            <section class="grid grid--3">
                <article class="card">
                    <p class="card__eyebrow">Stand der Anwendung</p>
                    <h2>Aktueller Update-Status</h2>
                    <div class="stack" style="margin-top: 18px;">
                        <div class="metric metric--compact">
                            <p class="metric__label">Version</p>
                            <div class="metric__value mono"><?= admin_h($appVersion) ?></div>
                            <p class="muted">Bereitgestellter Stand der Anwendung.</p>
                        </div>
                        <div class="metric metric--compact">
                            <p class="metric__label">Offene Updates</p>
                            <div class="metric__value"><?= admin_h((string) $updateSummary['pending']) ?></div>
                            <p class="muted">Warten auf Ausführung.</p>
                        </div>
                    </div>
                </article>

                <article class="form-panel">
                    <p class="card__eyebrow">Ausführung</p>
                    <h2>Updates direkt anstoßen</h2>
                    <p class="muted" style="margin-top: 12px;">Updates laufen idempotent. Bereits erfolgreiche Updates werden übersprungen und bleiben im Protokoll sichtbar.</p>
                    <form method="post" action="/admin/updates/" class="form-grid" style="margin-top: 18px;">
                        <input type="hidden" name="csrf" value="<?= admin_h($_SESSION['admin_csrf']) ?>">
                        <input type="hidden" name="action" value="run-updates">
                        <button type="submit">Ausstehende Updates jetzt ausführen</button>
                    </form>
                    <div class="callout" style="margin-top: 18px;">
                        <strong>Web-Ausführung</strong>
                        Derselbe Prozess kann lokal weiterhin per <code>php scripts/run-updates.php</code> laufen.
                    </div>
                </article>

                <article class="panel">
                    <p class="card__eyebrow">Betriebsmodell</p>
                    <h2>Was dabei protokolliert wird</h2>
                    <div class="timeline" style="margin-top: 18px;">
                        <div class="timeline__item">
                            <p class="timeline__title">Quelle</p>
                            <p class="timeline__meta">Updates liegen versioniert unter <code>saas-app/updates/</code>.</p>
                        </div>
                        <div class="timeline__item">
                            <p class="timeline__title">Protokoll</p>
                            <p class="timeline__meta">Jede Ausführung wird in <code>app_updates</code> dokumentiert.</p>
                        </div>
                        <div class="timeline__item">
                            <p class="timeline__title">Verhalten</p>
                            <p class="timeline__meta">Erfolgreiche Einträge bleiben sichtbar und werden nicht erneut ausgeführt.</p>
                        </div>
                    </div>
                </article>
            </section>

            <section class="table-card">
                <div class="table-card__header">
                    <div>
                        <p class="card__eyebrow">Protokoll</p>
                        <h2>Update-Laufhistorie</h2>
                    </div>
                    <span class="pill"><?= admin_h((string) count($updateItems)) ?> Einträge</span>
                </div>
                <div class="table-card__body">
                    <table>
                        <thead>
                            <tr>
                                <th>Update</th>
                                <th>Status</th>
                                <th>Beschreibung</th>
                                <th>Ausgeführt</th>
                                <th>Durch</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($updateItems === []): ?>
                                <tr>
                                    <td colspan="5">Aktuell liegen keine Update-Einträge vor.</td>
                                </tr>
                            <?php endif; ?>
                            <?php foreach ($updateItems as $item): ?>
                                <?php
                                $status = (string) ($item['status'] ?? 'pending');
                                $tone = match ($status) {
                                    'success' => 'success',
                                    'failed' => 'error',
                                    'running' => 'warning',
                                    default => 'neutral',
                                };
                                $label = match ($status) {
                                    'pending' => 'Offen',
                                    'running' => 'Läuft',
                                    'failed' => 'Fehler',
                                    default => ucfirst($status),
                                };
                                ?>
                                <tr>
                                    <td>
                                        <strong><?= admin_h((string) $item['title']) ?></strong>
                                        <small class="mono"><?= admin_h((string) $item['key']) ?></small>
                                    </td>
                                    <td><?= admin_badge($label, $tone) ?></td>
                                    <td>
                                        <?= admin_h((string) ($item['description'] ?? '')) ?>
                                        <?php if (!empty($item['error_message'])): ?>
                                            <small><?= admin_h((string) $item['error_message']) ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= admin_h((string) ($item['executed_at'] ?? '-')) ?></td>
                                    <td><?= admin_h((string) ($item['executed_by'] ?? '-')) ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </section>
        <?php else: ?>
            <section class="grid grid--3">
                <article class="card">
                    <p class="card__eyebrow">Schema-Stand</p>
                    <h2>Aktueller Migrationsstatus</h2>
                    <div class="stack" style="margin-top: 18px;">
                        <div class="metric metric--compact">
                            <p class="metric__label">Offene Migrationen</p>
                            <div class="metric__value"><?= admin_h((string) $migrationSummary['pending']) ?></div>
                            <p class="muted">Noch nicht eingespielt.</p>
                        </div>
                        <div class="metric metric--compact">
                            <p class="metric__label">Erfolgreich</p>
                            <div class="metric__value"><?= admin_h((string) $migrationSummary['success']) ?></div>
                            <p class="muted">Bereits protokolliert.</p>
                        </div>
                    </div>
                </article>

                <article class="form-panel">
                    <p class="card__eyebrow">Ausführung</p>
                    <h2>Migrationen direkt anstoßen</h2>
                    <p class="muted" style="margin-top: 12px;">Vorhandene Tabellen werden automatisch als bestehender Stand übernommen. Neue Migrationen werden nur einmal ausgeführt und protokolliert.</p>
                    <form method="post" action="/admin/migration/" class="form-grid" style="margin-top: 18px;">
                        <input type="hidden" name="csrf" value="<?= admin_h($_SESSION['admin_csrf']) ?>">
                        <input type="hidden" name="action" value="run-migrations">
                        <button type="submit">Ausstehende Migrationen jetzt ausführen</button>
                    </form>
                    <div class="callout" style="margin-top: 18px;">
                        <strong>Baseline inklusive</strong>
                        Bereits vorhandene Zieltabellen werden als Baseline protokolliert statt doppelt angelegt.
                    </div>
                </article>

                <article class="panel">
                    <p class="card__eyebrow">Hinweise</p>
                    <h2>Wie der Ablauf gedacht ist</h2>
                    <div class="timeline" style="margin-top: 18px;">
                        <div class="timeline__item">
                            <p class="timeline__title">Quelle</p>
                            <p class="timeline__meta">Migrationen liegen unter <code>saas-app/database/migrations/</code>.</p>
                        </div>
                        <div class="timeline__item">
                            <p class="timeline__title">Verhalten</p>
                            <p class="timeline__meta">Die Weboberfläche führt nur fehlende Migrationen aus.</p>
                        </div>
                        <div class="timeline__item">
                            <p class="timeline__title">Dokumentation</p>
                            <p class="timeline__meta">Baseline, Fehler und erfolgreiche Läufe bleiben in der Historie nachvollziehbar.</p>
                        </div>
                    </div>
                </article>
            </section>

            <section class="table-card">
                <div class="table-card__header">
                    <div>
                        <p class="card__eyebrow">Protokoll</p>
                        <h2>Migrations-Historie</h2>
                    </div>
                    <span class="pill"><?= admin_h((string) count($migrationItems)) ?> Einträge</span>
                </div>
                <div class="table-card__body">
                    <table>
                        <thead>
                            <tr>
                                <th>Migration</th>
                                <th>Status</th>
                                <th>Zieltabellen</th>
                                <th>Ausgeführt</th>
                                <th>Durch</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($migrationItems === []): ?>
                                <tr>
                                    <td colspan="5">Aktuell liegen keine Migrations-Einträge vor.</td>
                                </tr>
                            <?php endif; ?>
                            <?php foreach ($migrationItems as $item): ?>
                                <?php
                                $status = (string) ($item['status'] ?? 'pending');
                                $tone = match ($status) {
                                    'success' => 'success',
                                    'baselined' => 'success',
                                    'failed' => 'error',
                                    'running' => 'warning',
                                    default => 'neutral',
                                };
                                $label = match ($status) {
                                    'pending' => 'Offen',
                                    'baselined' => 'Baseline',
                                    'running' => 'Läuft',
                                    'failed' => 'Fehler',
                                    default => ucfirst($status),
                                };
                                ?>
                                <tr>
                                    <td>
                                        <strong><?= admin_h((string) $item['title']) ?></strong>
                                        <small class="mono"><?= admin_h((string) $item['key']) ?></small>
                                        <?php if (!empty($item['notes'])): ?>
                                            <small><?= admin_h((string) $item['notes']) ?></small>
                                        <?php endif; ?>
                                        <?php if (!empty($item['error_message'])): ?>
                                            <small><?= admin_h((string) $item['error_message']) ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= admin_badge($label, $tone) ?></td>
                                    <td><?= admin_h(implode(', ', array_map('strval', $item['tables'] ?? [])) ?: '-') ?></td>
                                    <td><?= admin_h((string) ($item['executed_at'] ?? '-')) ?></td>
                                    <td><?= admin_h((string) ($item['executed_by'] ?? '-')) ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </section>
        <?php endif; ?>
    </main>

    <footer class="marketing-footer">
        <div class="marketing-footer__inner">
            Kaffeeliste Admin | zentrale Mandanten-Verwaltung, Lizenzsteuerung und Update-Prozesse in einer Oberfläche
        </div>
    </footer>
</div>
</body>
</html>
