<?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
{
    return '<span class="badge badge-' . admin_h($tone) . '">' . admin_h($label) . '</span>';
}

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 (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/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];
$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'], 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'], 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/');
    }

    $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);
    $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, 'team') 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, 'team' AS plan_key FROM tenants WHERE id = :id LIMIT 1",
                ['id' => (string) $_GET['edit']]
            );
    }
}
?><!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Kaffeeliste Admin</title>
    <style>
        :root{--bg:#f4efe7;--card:#fffaf4;--ink:#24160e;--muted:#675546;--brand:#0c6b66;--accent:#a34b12;--line:rgba(36,22,14,.12);--radius:24px;--shadow:0 24px 54px rgba(57,35,22,.11)}
        *{box-sizing:border-box}body{margin:0;font-family:"Aptos","Segoe UI",sans-serif;color:var(--ink);background:linear-gradient(180deg,#fbf8f2 0%,var(--bg) 100%)}a{color:inherit}.shell{width:min(1240px,calc(100vw - 32px));margin:24px 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:18px}.hero,.card{padding:24px}.hero{margin-bottom:18px}.grid{display:grid;gap:18px}.grid-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-6{grid-template-columns:repeat(6,minmax(0,1fr))}.links a,.button,button{display:inline-flex;align-items:center;justify-content:center;padding:11px 16px;border-radius:999px;text-decoration:none;font-weight:700;border:0;cursor:pointer}.links a{background:rgba(12,107,102,.08);color:var(--brand)}.links a.active{background:linear-gradient(135deg,var(--brand),#084d49);color:#fff}.button,button{background:linear-gradient(135deg,var(--brand),#084d49);color:#fff}.button.secondary{background:transparent;color:var(--brand);border:1px solid rgba(12,107,102,.18)}h1,h2,h3{margin:0 0 12px;font-family:Georgia,serif}h1{font-size:clamp(2rem,4vw,3.4rem)}h2{font-size:1.35rem}h3{font-size:1.02rem}.eyebrow{display:inline-block;margin-bottom:12px;color:var(--accent);font-size:.82rem;font-weight:800;letter-spacing:.14em;text-transform:uppercase}p,.muted{margin:0;color:var(--muted);line-height:1.65}.stack{display:grid;gap:12px}.metric{padding:18px;border:1px solid var(--line);border-radius:18px;background:#fffdf9}.metric strong{display:block;font-size:1.8rem;margin-bottom:8px}.alert{padding:16px 18px;margin-bottom:18px}.alert-success{background:rgba(17,98,61,.08)}.alert-warning{background:rgba(163,75,18,.08)}.alert-error{background:rgba(154,31,31,.08)}.badge{display:inline-flex;align-items:center;padding:7px 12px;border-radius:999px;font-size:.86rem;font-weight:700}.badge-neutral{background:rgba(12,107,102,.1);color:var(--brand)}.badge-success{background:rgba(17,98,61,.12);color:#11623d}.badge-warning{background:rgba(163,75,18,.12);color:#98510c}.badge-error{background:rgba(154,31,31,.12);color:#9a1f1f}.table{overflow-x:auto}.table table{width:100%;border-collapse:collapse;min-width:820px}.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{width:100%;padding:12px 14px;border-radius:16px;border:1px solid rgba(36,22,14,.15);font:inherit;background:#fffdfa;color:var(--ink)}ul{margin:0;padding-left:18px;color:var(--muted);line-height:1.7}.footer{margin-top:18px;text-align:center;color:var(--muted);font-size:.92rem}code{font-family:Consolas,monospace}.mono{font-family:Consolas,monospace;font-size:.92rem}.status-block{display:grid;gap:8px}.table small{display:block;color:var(--muted);margin-top:4px;line-height:1.5}@media(max-width:980px){.grid-2,.grid-3,.grid-6,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>
            <strong style="font-family:Georgia,serif;font-size:1.28rem;">Kaffeeliste Admin</strong>
            <p>Zentrale Verwaltung für Mandanten, Lizenzen, Updates und Betriebsstatus.</p>
        </div>
        <nav class="links">
            <a href="/admin/login/" class="<?= $page === 'login' ? 'active' : '' ?>">Login</a>
            <?php if ($admin !== null): ?>
                <a href="/admin/" class="<?= $page === 'overview' ? 'active' : '' ?>">Übersicht</a>
                <a href="/admin/tenants/" class="<?= $page === 'tenants' ? 'active' : '' ?>">Mandanten</a>
                <a href="/admin/updates/" class="<?= $page === 'updates' ? 'active' : '' ?>">Updates</a>
                <form method="post" action="/admin/logout/">
                    <input type="hidden" name="csrf" value="<?= admin_h($_SESSION['admin_csrf']) ?>">
                    <button type="submit" class="button secondary">Abmelden</button>
                </form>
            <?php endif; ?>
        </nav>
    </header>

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

    <?php if ($page === 'login'): ?>
        <section class="hero">
            <div class="eyebrow">Global-Admin</div>
            <h1>Zentrale Administration für die Kaffeeliste.</h1>
            <p>Dieser Zugang ist ausschließlich für die globale Verwaltung gedacht und bleibt bewusst vom Mitglieder-Login getrennt.</p>
        </section>
        <?php if ($adminLogin['error'] !== null): ?><section class="alert alert-error"><?= admin_h((string) $adminLogin['error']) ?></section><?php endif; ?>
        <?php if ($dbError !== null): ?><section class="alert alert-warning"><?= admin_h($dbError) ?></section><?php endif; ?>
        <section class="grid grid-2">
            <article class="card">
                <h2>Anmelden</h2>
                <form method="post" action="/admin/login/" class="stack">
                    <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"></label>
                    <label>Passwort<input type="password" name="password" autocomplete="current-password"></label>
                    <div class="actions"><button type="submit">Als Global-Admin anmelden</button></div>
                </form>
            </article>
            <article class="card">
                <h2>Hinweise zur Einrichtung</h2>
                <ul>
                    <li>Der erste Global-Admin wird im Installer angelegt oder aktualisiert.</li>
                    <li>Die Anmeldung prüft <code>users.is_platform_admin = 1</code> und das gespeicherte Passwort.</li>
                    <li>Nach dem Login stehen Übersicht, Mandanten-Verwaltung und Update-Center zentral bereit.</li>
                </ul>
            </article>
        </section>
    <?php elseif ($page === 'overview'): ?>
        <section class="hero">
            <div class="eyebrow">Zentrale Übersicht</div>
            <h1>Alle Mandanten, Lizenzen und Systemstände an einer Stelle.</h1>
            <p>Die globale Verwaltung bündelt die wichtigsten Betriebsdaten und führt direkt in Lizenzpflege, Mandanten-Einstieg und Updates.</p>
        </section>
        <?php if ($dbError !== null): ?><section class="alert alert-warning"><?= admin_h($dbError) ?></section><?php endif; ?>
        <section class="grid grid-6">
            <?php foreach ($summaryMetrics as $metric): ?>
                <article class="metric">
                    <strong><?= admin_h((string) $metric['value']) ?></strong>
                    <h3><?= admin_h((string) $metric['label']) ?></h3>
                    <p><?= admin_h((string) $metric['detail']) ?></p>
                </article>
            <?php endforeach; ?>
        </section>
        <section class="grid grid-3" style="margin-top:18px">
            <article class="card">
                <h2>Angemeldet als</h2>
                <div class="stack">
                    <div class="metric">
                        <h3><?= admin_h((string) ($admin['display_name'] ?? '')) ?></h3>
                        <p><?= admin_h((string) ($admin['email'] ?? '')) ?></p>
                    </div>
                    <div class="metric">
                        <h3>Aktuelle Version</h3>
                        <p class="mono"><?= admin_h($appVersion) ?></p>
                    </div>
                </div>
            </article>
            <article class="card">
                <h2>Schnellzugriffe</h2>
                <div class="actions">
                    <a class="button" href="/admin/tenants/">Mandanten verwalten</a>
                    <a class="button secondary" href="/admin/updates/">Updates prüfen</a>
                    <a class="button secondary" href="/login/">Mitglieder-Login prüfen</a>
                </div>
                <ul style="margin-top:16px">
                    <li>Mandanten können direkt mit einem passenden Lizenzplan angelegt werden.</li>
                    <li>Als Global-Admin kannst du jeden Mandanten öffnen und operativ prüfen.</li>
                    <li>System-Updates laufen über die Weboberfläche ohne Shell-Zugriff.</li>
                </ul>
            </article>
            <article class="card">
                <h2>Update-Lage</h2>
                <div class="stack">
                    <div class="metric"><h3>Offen</h3><p><?= admin_h((string) $updateSummary['pending']) ?> Update(s) warten auf Ausführung.</p></div>
                    <div class="metric"><h3>Fehlgeschlagen</h3><p><?= admin_h((string) $updateSummary['failed']) ?> Update(s) brauchen Aufmerksamkeit.</p></div>
                    <div class="metric"><h3>Erfolgreich</h3><p><?= admin_h((string) $updateSummary['success']) ?> Update(s) sind bereits dokumentiert.</p></div>
                </div>
            </article>
        </section>
    <?php elseif ($page === 'tenants'): ?>
        <section class="hero">
            <div class="eyebrow">Mandanten-Verwaltung</div>
            <h1>Mandanten zentral anlegen, lizenzieren und betreten.</h1>
            <p>Hier pflegt der Global-Admin die Stammdaten aller Mandanten und steuert, welche Funktionspakete pro Lizenz freigeschaltet sind.</p>
        </section>
        <?php if ($dbError !== null): ?><section class="alert alert-warning"><?= admin_h($dbError) ?></section><?php endif; ?>
        <section class="grid grid-2">
            <article class="card">
                <h2><?= $editingTenant !== null ? 'Mandanten bearbeiten' : 'Neuen Mandanten anlegen' ?></h2>
                <form method="post" action="/admin/tenants/" class="grid">
                    <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'] ?? 'team') === (string) $plan['plan_key']) ? ' selected' : '' ?>><?= admin_h((string) $plan['name']) ?></option><?php endforeach; ?></select></label>
                    <div class="actions">
                        <button type="submit">Speichern</button>
                        <a class="button secondary" href="/admin/">Zur Übersicht</a>
                    </div>
                </form>
                <?php if ($licensePlans === []): ?>
                    <p style="margin-top:14px">Die Lizenzpläne sind noch nicht verfügbar. Bitte zuerst die System-Updates ausführen.</p>
                <?php endif; ?>
            </article>
            <article class="card">
                <h2>Lizenzrahmen</h2>
                <div class="stack">
                    <div class="metric"><h3>Starter</h3><p>Basisfunktionen wie Mitglieder, Buchungen, Einzahlungen und Inhalte.</p></div>
                    <div class="metric"><h3>Team</h3><p>Zusätzlich Mandanten-Einstellungen, PDF-Listen, Papierlisten-Erfassung und Basis-Exporte.</p></div>
                    <div class="metric"><h3>Business & Enterprise</h3><p>Vorbereitung für SSO, Importe, erweiterte Exporte, Benachrichtigungen und priorisierte Updates.</p></div>
                </div>
            </article>
        </section>
        <section class="card" style="margin-top:18px">
            <h2>Vorhandene Mandanten</h2>
            <div class="table">
                <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 foreach ($tenants as $tenant): ?>
                            <tr>
                                <td><strong><?= admin_h((string) $tenant['name']) ?></strong></td>
                                <td><?= admin_h((string) $tenant['tenant_key']) ?></td>
                                <td><?= admin_badge(((string) $tenant['status']) === 'active' ? 'Aktiv' : ucfirst((string) $tenant['status']), ((string) $tenant['status']) === 'active' ? 'success' : 'warning') ?></td>
                                <td><?= admin_badge((string) ($tenant['plan_name'] ?? 'Starter')) ?></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="actions">
                                        <a class="button secondary" 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 else: ?>
        <section class="hero">
            <div class="eyebrow">Update-Center</div>
            <h1>System-Updates zentral prüfen und ausführen.</h1>
            <p>Schema-Erweiterungen und Datenanpassungen werden versioniert dokumentiert und können direkt über die Weboberfläche angestoßen werden.</p>
        </section>
        <?php if ($dbError !== null): ?><section class="alert alert-warning"><?= admin_h($dbError) ?></section><?php endif; ?>
        <section class="grid grid-3">
            <article class="card">
                <h2>Stand der Anwendung</h2>
                <div class="stack">
                    <div class="metric"><h3>Version</h3><p class="mono"><?= admin_h($appVersion) ?></p></div>
                    <div class="metric"><h3>Offene Updates</h3><p><?= admin_h((string) $updateSummary['pending']) ?></p></div>
                    <div class="metric"><h3>Fehlgeschlagen</h3><p><?= admin_h((string) $updateSummary['failed']) ?></p></div>
                </div>
            </article>
            <article class="card">
                <h2>Update-Ausführung</h2>
                <p>Updates laufen idempotent. Bereits erfolgreiche Updates werden übersprungen und bleiben im Protokoll sichtbar.</p>
                <form method="post" action="/admin/updates/" 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>
            </article>
            <article class="card">
                <h2>Betriebsmodell</h2>
                <ul>
                    <li>Updates liegen versioniert unter <code>saas-app/updates/</code>.</li>
                    <li>Jede Ausführung wird in <code>app_updates</code> dokumentiert.</li>
                    <li>Dasselbe Verfahren kann lokal auch per <code>php scripts/run-updates.php</code> laufen.</li>
                </ul>
            </article>
        </section>
        <section class="card" style="margin-top:18px">
            <h2>Update-Protokoll</h2>
            <div class="table">
                <table>
                    <thead><tr><th>Update</th><th>Status</th><th>Beschreibung</th><th>Ausgeführt</th><th>Durch</th></tr></thead>
                    <tbody>
                        <?php foreach ($updateItems as $item): ?>
                            <?php
                            $status = (string) ($item['status'] ?? 'pending');
                            $tone = match ($status) {
                                'success' => 'success',
                                'failed' => 'error',
                                'running' => 'warning',
                                default => 'neutral',
                            };
                            ?>
                            <tr>
                                <td><strong><?= admin_h((string) $item['title']) ?></strong><small class="mono"><?= admin_h((string) $item['key']) ?></small></td>
                                <td><?= admin_badge($status === 'pending' ? 'Offen' : ucfirst($status), $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 endif; ?>

    <p class="footer">Kaffeeliste Admin | zentrale Mandanten-Verwaltung, Lizenzsteuerung und Update-Prozess über PHP-Webseiten</p>
</main>
</body>
</html>
