<?php

declare(strict_types=1);

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

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

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

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

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

function dt(?string $value): string
{
    if ($value === null || trim($value) === '') {
        return '-';
    }

    $time = strtotime($value);

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

function dt_local(?string $value): string
{
    if ($value === null || trim($value) === '') {
        return '';
    }

    $time = strtotime($value);

    return $time === false ? '' : date('Y-m-d\TH:i', $time);
}

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

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

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

$page = (string) $requestedPage;
$requestMethod = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$tenantPages = ['dashboard', 'members', 'ledger', 'payments', 'content', 'imports', 'reports', 'year-end', 'support', 'surveys', 'notifications', 'profile', 'settings', 'exports'];

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

$flash = app_flash();
$auth = app_auth_user();
$pdo = null;
$dbError = null;
$tenantOverview = null;
$tenantDashboard = null;
$members = [];
$ledger = [];
$payments = [];
$content = ['announcements' => [], 'faq' => []];
$dashboardAnnouncements = [];
$memberSummary = null;
$memberReport = null;
$ledgerScope = 'all';
$paymentScope = 'all';
$ledgerMembers = [];
$paymentMembers = [];
$reportRows = [];
$importResult = ['rows' => [], 'summary' => ['imported' => 0, 'duplicates' => 0, 'unmatched' => 0]];
$scanImportJobs = [];
$scanTemplates = [];
$activeScanJob = null;
$activeScanRows = [];
$surveyBoard = ['all' => [], 'published' => []];
$activeSurvey = null;
$surveyResults = [];
$loginFlow = ['state' => app_login_state(), 'message' => null, 'error' => null];
$editingMember = null;
$editingAnnouncement = null;
$editingFaq = null;
$memberForm = app_member_form_defaults();
$tenantLicense = ['plan_key' => 'free', 'plan_name' => 'Free', 'member_limit' => 10, 'features' => app_feature_defaults()];
$tenantSettings = app_tenant_settings_defaults();
$printLists = [];
$activePrintList = null;
$printListGroups = ['front' => [], 'back' => []];
$printListItemMap = [];
$hasTenantSettingsFeature = false;
$hasPdfExportFeature = false;
$hasPaperStrikeEntryFeature = false;
$hasBasicExportsFeature = false;
$yearEndPreview = null;
$yearEndPreviewError = null;
$yearEndRuns = [];
$notificationStorageReady = false;
$notificationMessages = [];
$notificationLogs = [];
$notificationPreview = [];
$editingNotification = null;
$notificationSummary = [
    'total' => 0,
    'draft' => 0,
    'scheduled' => 0,
    'sent' => 0,
    'recipient_count' => 0,
    'log_count' => 0,
];
$notificationForm = [
    'notification_id' => '',
    'title' => '',
    'message' => '',
    'channel' => 'email',
    'recipient_scope' => 'all',
    'scheduled_at' => '',
];
$notificationScopeOptions = [
    ['value' => 'all', 'label' => 'Alle Mitglieder'],
    ['value' => 'front', 'label' => 'Vorderseite'],
    ['value' => 'back', 'label' => 'Rückseite'],
];
$notificationChannelOptions = [
    ['value' => 'email', 'label' => 'E-Mail'],
    ['value' => 'inapp', 'label' => 'In-App'],
    ['value' => 'sms', 'label' => 'SMS'],
];
$yearEndForm = [
    'year' => (int) date('Y') - 1,
    'bonus_mode' => 'proportional',
    'bonus_pool_amount' => '100.00',
    'bonus_per_member_amount' => '2.50',
    'booked_at' => sprintf('%04d-12-31T23:59', (int) date('Y') - 1),
    'notes' => '',
];
$yearEndExistingRun = null;

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

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

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

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

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

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

        if ($page === 'profile') {
            app_handle_profile_action($pdo, $auth);
        }

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

        if ($page === 'content') {
            app_handle_content_action($pdo, $auth);
        }

        if ($page === 'imports') {
            if (function_exists('app_handle_scan_import_action')) {
                app_handle_scan_import_action($pdo, $auth);
            }
            $importResult = app_handle_csv_import($pdo, $auth);
            if (function_exists('app_scan_templates_for_tenant')) {
                $scanTemplates = app_scan_templates_for_tenant($pdo, (string) $auth['tenant_id']);
            }
            if (function_exists('app_scan_import_jobs_for_tenant')) {
                $scanImportJobs = app_scan_import_jobs_for_tenant($pdo, (string) $auth['tenant_id']);
            }
            $activeScanJobId = trim((string) ($_GET['scan_job'] ?? ''));
            if ($activeScanJobId !== '') {
                if (function_exists('app_scan_import_job_for_tenant')) {
                    $activeScanJob = app_scan_import_job_for_tenant($pdo, (string) $auth['tenant_id'], $activeScanJobId);
                }
                if (is_array($activeScanJob) && function_exists('app_scan_import_rows_for_job')) {
                    $activeScanRows = app_scan_import_rows_for_job($pdo, (string) $auth['tenant_id'], $activeScanJobId);
                }
            }
        }

        if ($page === 'surveys') {
            app_handle_survey_action($pdo, $auth);
        }

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

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

            $notificationStorageReady = app_notifications_supports_storage($pdo);
            app_handle_notifications_action($pdo, $auth);
            $notificationMessages = app_notifications_for_tenant($pdo, (string) $auth['tenant_id']);
            $notificationLogs = app_notification_logs_for_tenant($pdo, (string) $auth['tenant_id']);
            $notificationSummary['total'] = count($notificationMessages);
            $notificationSummary['draft'] = count(array_filter($notificationMessages, static fn(array $row): bool => (string) ($row['status'] ?? '') === 'draft'));
            $notificationSummary['scheduled'] = count(array_filter($notificationMessages, static fn(array $row): bool => (string) ($row['status'] ?? '') === 'scheduled'));
            $notificationSummary['sent'] = count(array_filter($notificationMessages, static fn(array $row): bool => (string) ($row['status'] ?? '') === 'sent'));
            $notificationSummary['recipient_count'] = array_sum(array_map(static fn(array $row): int => (int) ($row['recipient_count'] ?? 0), $notificationMessages));
            $notificationSummary['log_count'] = count($notificationLogs);

            $editNotificationId = trim((string) ($_GET['edit'] ?? ''));
            if ($editNotificationId !== '') {
                $editingNotification = app_notification_message_by_id($pdo, (string) $auth['tenant_id'], $editNotificationId);
            }

            if ($editingNotification !== null) {
                $notificationForm = [
                    'notification_id' => (string) ($editingNotification['id'] ?? ''),
                    'title' => (string) ($editingNotification['title'] ?? ''),
                    'message' => (string) ($editingNotification['message'] ?? ''),
                    'channel' => (string) ($editingNotification['channel'] ?? 'email'),
                    'recipient_scope' => (string) ($editingNotification['recipient_scope'] ?? 'all'),
                    'scheduled_at' => dt_local((string) ($editingNotification['scheduled_at'] ?? '')),
                ];
            } else {
                $notificationForm['scheduled_at'] = date('Y-m-d\TH:i', time() + 3600);
            }

            $selectedScope = in_array((string) ($_GET['scope'] ?? $notificationForm['recipient_scope']), ['all', 'front', 'back'], true)
                ? (string) ($_GET['scope'] ?? $notificationForm['recipient_scope'])
                : 'all';
            $notificationPreview = app_notification_recipients_for_scope($pdo, (string) $auth['tenant_id'], $selectedScope);
            $notificationForm['recipient_scope'] = $selectedScope;
        }

        if ($page === 'year-end') {
            if ($requestMethod === 'POST') {
                $yearEndForm = array_merge($yearEndForm, [
                    'year' => max(2000, (int) ($_POST['year'] ?? $yearEndForm['year'])),
                    'bonus_mode' => in_array((string) ($_POST['bonus_mode'] ?? 'proportional'), ['proportional', 'flat'], true)
                        ? (string) ($_POST['bonus_mode'] ?? 'proportional')
                        : 'proportional',
                    'bonus_pool_amount' => number_format(max(0.0, (float) ($_POST['bonus_pool_amount'] ?? 0)), 2, '.', ''),
                    'bonus_per_member_amount' => number_format(max(0.0, (float) ($_POST['bonus_per_member_amount'] ?? 0)), 2, '.', ''),
                    'booked_at' => str_replace(' ', 'T', (string) ($_POST['booked_at'] ?? $yearEndForm['booked_at'])),
                    'notes' => trim((string) ($_POST['notes'] ?? '')),
                ]);

                $yearEndForm['booked_at'] = substr($yearEndForm['booked_at'], 0, 16);

                if ((string) ($_POST['action'] ?? '') === 'preview-year-end') {
                    try {
                        $yearEndPreview = app_year_end_preview($pdo, (string) $auth['tenant_id'], [
                            'year' => $yearEndForm['year'],
                            'bonus_mode' => $yearEndForm['bonus_mode'],
                            'bonus_pool_amount' => $yearEndForm['bonus_pool_amount'],
                            'bonus_per_member_amount' => $yearEndForm['bonus_per_member_amount'],
                            'booked_at' => $yearEndForm['booked_at'],
                            'notes' => $yearEndForm['notes'],
                        ]);
                    } catch (Throwable $exception) {
                        $yearEndPreviewError = $exception->getMessage();
                    }
                }

                if ((string) ($_POST['action'] ?? '') === 'execute-year-end') {
                    try {
                        $result = app_year_end_execute($pdo, $auth, [
                            'year' => $yearEndForm['year'],
                            'bonus_mode' => $yearEndForm['bonus_mode'],
                            'bonus_pool_amount' => $yearEndForm['bonus_pool_amount'],
                            'bonus_per_member_amount' => $yearEndForm['bonus_per_member_amount'],
                            'booked_at' => $yearEndForm['booked_at'],
                            'notes' => $yearEndForm['notes'],
                        ]);
                        app_flash('Der Jahresabschluss wurde verbucht. ' . (string) ($result['payment_count'] ?? 0) . ' Auszahlungen wurden erzeugt.', 'success');
                        app_redirect('/year-end/');
                    } catch (Throwable $exception) {
                        app_flash($exception->getMessage(), 'error');
                        app_redirect('/year-end/');
                    }
                }
            }

            $yearEndRuns = app_year_end_runs_for_tenant($pdo, (string) $auth['tenant_id']);
            $yearEndExistingRun = app_year_end_run_exists($pdo, (string) $auth['tenant_id'], (int) $yearEndForm['year']);
        }

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

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

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

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

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

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

        if ($page === 'ledger') {
            $ledgerScope = in_array((string) ($_GET['scope'] ?? 'all'), ['all', 'front', 'back'], true)
                ? (string) ($_GET['scope'] ?? 'all')
                : 'all';
            $ledgerMembers = app_members_for_scope($pdo, (string) $auth['tenant_id'], $ledgerScope);
            if ($ledgerMembers === [] && $members !== []) {
                $ledgerMembers = array_map(
                    static function (array $member): array {
                        $member['recent_strokes'] = (int) ($member['recent_strokes'] ?? 0);
                        return $member;
                    },
                    array_values(array_filter(
                        $members,
                        static function (array $member): bool {
                            $status = strtolower(trim((string) ($member['status'] ?? 'active')));
                            return !in_array($status, ['inactive', 'disabled', 'archived'], true);
                        }
                    ))
                );
            }
        }

        if ($page === 'payments') {
            $paymentScope = in_array((string) ($_GET['scope'] ?? 'all'), ['all', 'front', 'back'], true)
                ? (string) ($_GET['scope'] ?? 'all')
                : 'all';
            $paymentMembers = app_members_for_scope($pdo, (string) $auth['tenant_id'], $paymentScope);
            if ($paymentMembers === [] && $members !== []) {
                $paymentMembers = array_map(
                    static function (array $member): array {
                        $member['recent_strokes'] = (int) ($member['recent_strokes'] ?? 0);
                        return $member;
                    },
                    array_values(array_filter(
                        $members,
                        static function (array $member): bool {
                            $status = strtolower(trim((string) ($member['status'] ?? 'active')));
                            return !in_array($status, ['inactive', 'disabled', 'archived'], true);
                        }
                    ))
                );
            }
        }

        if ($page === 'content' || $page === 'dashboard') {
            $content = app_content_for_tenant($pdo, (string) $auth['tenant_id']);
            $dashboardAnnouncements = array_slice(
                array_values(
                    array_filter(
                        $content['announcements'] ?? [],
                        static fn(array $announcement): bool => (int) ($announcement['is_active'] ?? 0) === 1
                    )
                ),
                0,
                3
            );
        }

        if ($page === 'content') {

            if (isset($_GET['edit_announcement']) && $_GET['edit_announcement'] !== '') {
                foreach (($content['announcements'] ?? []) as $announcement) {
                    if ((string) ($announcement['id'] ?? '') === (string) $_GET['edit_announcement']) {
                        $editingAnnouncement = $announcement;
                        break;
                    }
                }
            }

            if (isset($_GET['edit_faq']) && $_GET['edit_faq'] !== '') {
                foreach (($content['faq'] ?? []) as $faq) {
                    if ((string) ($faq['id'] ?? '') === (string) $_GET['edit_faq']) {
                        $editingFaq = $faq;
                        break;
                    }
                }
            }
        }

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

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

        if ($page === 'members' && isset($_GET['edit']) && $_GET['edit'] !== '') {
            $editingMember = app_tenant_user_by_id($pdo, (string) $_GET['edit'], (string) $auth['tenant_id']);
            $memberForm = app_member_form_defaults($editingMember);
        }

        if ($page === 'members' && isset($_GET['member']) && $_GET['member'] !== '') {
            $memberReport = app_member_report($pdo, (string) $auth['tenant_id'], (string) $_GET['member']);
        }

        if ($page === 'reports') {
            $reportRows = app_reporting_rows($pdo, (string) $auth['tenant_id']);
            if ($memberReport === null && isset($_GET['member']) && $_GET['member'] !== '') {
                $memberReport = app_member_report($pdo, (string) $auth['tenant_id'], (string) $_GET['member']);
            }
        }

        if ($page === 'surveys') {
            $surveyBoard = app_surveys_for_tenant($pdo, (string) $auth['tenant_id']);
            if (isset($_GET['survey']) && $_GET['survey'] !== '') {
                $activeSurvey = app_survey_by_id($pdo, (string) $auth['tenant_id'], (string) $_GET['survey']);
                if (is_array($activeSurvey) && app_can_manage_surveys($auth)) {
                    $surveyResults = app_survey_results($pdo, (string) $activeSurvey['id']);
                }
            }
        }
    } catch (Throwable $exception) {
        $dbError = $exception->getMessage();
    }
}

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

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

$canManageTenant = app_can_manage_tenant($auth);
$tenantNavItems = app_tenant_navigation_items($auth, $tenantLicense);
$guestNavItems = [
    ['key' => 'home', 'href' => '/', 'label' => 'Start'],
    ['key' => 'login', 'href' => '/login/', 'label' => 'Anmeldung'],
    ['key' => 'tenants', 'href' => '/admin/login/', 'label' => 'Admin'],
];
$primaryNavItems = $auth === null ? $guestNavItems : $tenantNavItems;
$navGroups = $auth === null ? [] : app_tenant_navigation_groups($primaryNavItems);
$accountNavItems = $auth === null ? [] : app_tenant_account_items($auth);
$headerNavItems = $primaryNavItems;
if ($auth !== null) {
    $headerNavItems = [];
    $primaryKeys = ['dashboard', 'ledger', 'payments'];
    foreach ($primaryNavItems as $item) {
        if (in_array((string) ($item['key'] ?? ''), $primaryKeys, true)) {
            $headerNavItems[] = $item;
        }
    }
}
$themeMode = app_normalize_theme_mode((string) ($auth['theme_mode'] ?? 'dark'));
$ledgerViewMode = in_array((string) ($_GET['mode'] ?? 'capture'), ['capture', 'journal'], true)
    ? (string) ($_GET['mode'] ?? 'capture')
    : 'capture';
$mobileBottomNavItems = [];
$mobileDrawerPrimaryItems = [];
if ($auth !== null) {
    foreach (['dashboard', 'ledger', 'payments'] as $mobileKey) {
        foreach ($primaryNavItems as $item) {
            if ((string) ($item['key'] ?? '') === $mobileKey) {
                $mobileBottomNavItems[] = $item;
                break;
            }
        }
    }
}
$currentNavLabel = 'Start';
foreach ($primaryNavItems as $item) {
    if ($page === (string) ($item['key'] ?? '')) {
        $currentNavLabel = (string) ($item['label'] ?? $currentNavLabel);
        break;
    }
}
if ($page === 'profile') {
    $currentNavLabel = 'Persönliche Einstellungen';
}
$themeCss = app_tenant_theme_root_css($tenantSettings);
$isMarketingHome = $page === 'home' && $auth === null;
$heroEyebrow = 'Für Teams, Büros und Standorte';
$heroTitle = 'Die Kaffeeliste für einen klaren Kaffee-Alltag.';
$heroCopy = 'Mitglieder, Buchungen, Rollen und Hinweise laufen in einer klaren Oberfläche zusammen. Für Teams, die weniger Listen-Chaos und weniger Rückfragen wollen.';
$landingPreview = [
    ['label' => 'Mitglieder', 'value' => '48 aktiv'],
    ['label' => 'Buchungen', 'value' => 'Heute 12'],
    ['label' => 'Support', 'value' => '2 offen'],
];
$landingFeatures = [
    ['title' => 'Dashboard', 'copy' => 'Wichtige Zahlen, Hinweise und offene Themen direkt auf der Startseite.'],
    ['title' => 'Mitglieder und Rollen', 'copy' => 'Zugänge, Zuständigkeiten und Bereiche sauber an einem Ort verwalten.'],
    ['title' => 'Buchungen', 'copy' => 'Einzahlungen, Verbrauch und Korrekturen nachvollziehbar dokumentieren.'],
    ['title' => 'Support und Exporte', 'copy' => 'Rückfragen, Listen und Auswertungen ohne Wechsel zwischen mehreren Tools.'],
];
$landingSteps = [
    ['number' => '01', 'title' => 'Anmelden und Bereich öffnen', 'copy' => 'Ohne Installation direkt im Browser starten.'],
    ['number' => '02', 'title' => 'Mitglieder und Zuständigkeiten ordnen', 'copy' => 'Rollen, Standorte und Zugänge klar strukturieren.'],
    ['number' => '03', 'title' => 'Im Alltag damit arbeiten', 'copy' => 'Buchungen pflegen, Fragen klären und den Überblick behalten.'],
];
$landingUseCases = [
    ['title' => 'Für Mitglieder', 'copy' => 'Schnell sehen, was wichtig ist, ohne sich durch Verwaltungsthemen zu arbeiten.'],
    ['title' => 'Für Verantwortliche', 'copy' => 'Buchungen prüfen, Bereiche steuern und Abläufe sauber organisieren.'],
    ['title' => 'Für mehrere Standorte', 'copy' => 'Getrennte Bereiche bleiben übersichtlich, folgen aber derselben Logik.'],
];
$landingProof = [
    ['title' => 'Schnell verständlich', 'copy' => 'Die wichtigsten Bereiche sind sofort erkennbar und klar benannt.'],
    ['title' => 'Im Browser und mobil', 'copy' => 'Die Oberfläche funktioniert ohne Installation auf Desktop und Handy.'],
    ['title' => 'Für den Alltag gebaut', 'copy' => 'Kaffeeliste, Support, Buchungen und Verwaltung greifen sinnvoll ineinander.'],
];
$marketing = app_marketing_messages();

?><!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Die Kaffeeliste</title>
    <style>
        :root{<?= $themeCss ?>--radius:14px;--brand-glow:rgba(var(--brand-rgb),.22);--accent-glow:rgba(var(--accent-rgb),.16)}
        :root,[data-theme="dark"]{--line:rgba(143,158,191,.16);--line-strong:rgba(174,189,223,.26);--shadow:0 24px 64px rgba(1,6,18,.30);--shadow-soft:0 16px 34px rgba(1,6,18,.16);--surface-0:#0f1720;--surface-1:rgba(18,26,36,.84);--surface-2:rgba(23,32,45,.92);--surface-3:rgba(29,40,55,.96);--surface-soft:rgba(255,255,255,.05);--text-strong:#f4f7ff;--text-soft:rgba(219,228,248,.74);--text-faint:rgba(190,202,226,.56)}
        [data-theme="light"]{--line:rgba(61,84,126,.14);--line-strong:rgba(61,84,126,.2);--shadow:0 20px 48px rgba(20,36,68,.12);--shadow-soft:0 12px 24px rgba(20,36,68,.08);--surface-0:#eef2f6;--surface-1:rgba(255,253,248,.88);--surface-2:rgba(255,255,255,.94);--surface-3:#ffffff;--surface-soft:rgba(var(--brand-rgb),.08);--text-strong:#17212f;--text-soft:rgba(37,49,72,.76);--text-faint:rgba(58,72,98,.58)}
        *{box-sizing:border-box}
        body{margin:0;min-height:100vh;font-family:"Aptos","Segoe UI",sans-serif;color:var(--text-strong);background:radial-gradient(circle at top center,var(--brand-glow),transparent 26%),radial-gradient(circle at 18% 18%,rgba(var(--brand-rgb),.16),transparent 22%),linear-gradient(180deg,var(--surface-0) 0%,color-mix(in srgb,var(--surface-0) 82%, black 18%) 100%)}
        a{color:inherit;text-decoration:none}
        h1,h2,h3{font-family:"Inter Tight","Aptos","Segoe UI",sans-serif;letter-spacing:-.04em}
        .button,button{display:inline-flex;align-items:center;justify-content:center;padding:.72rem 1rem;border-radius:10px;border:1px solid transparent;background:linear-gradient(135deg,var(--brand) 0%,var(--brand-strong) 100%);color:#fff;font:inherit;font-weight:700;cursor:pointer;box-shadow:0 12px 24px rgba(var(--brand-rgb),.22)}
        .button.secondary,.button--ghost{background:rgba(255,255,255,.03);color:var(--text-strong);border-color:rgba(255,255,255,.12)}
        .page-shell{width:100%;margin:0 0 34px;display:grid;gap:16px}
        .site-header{position:sticky;top:0;z-index:30;width:100%;margin-left:0;margin-bottom:24px}
        .site-header__inner{display:flex;align-items:center;justify-content:space-between;gap:16px;min-height:74px;width:100%;margin:0;padding:0 24px;border:0;border-bottom:1px solid var(--line);border-radius:0;background:color-mix(in srgb,var(--surface-1) 88%, rgba(var(--brand-rgb),.12) 12%);box-shadow:var(--shadow);backdrop-filter:blur(18px)}
        .site-brand{display:flex;align-items:center;gap:12px;min-width:0}
        .site-brand__mark{width:38px;height:38px;border-radius:10px;display:grid;place-items:center;background:linear-gradient(135deg,var(--brand) 0%,var(--brand-strong) 100%);color:#fff;font-weight:800;box-shadow:none}
        .site-brand__title{margin:0;font-size:1rem;color:var(--text-strong);letter-spacing:-.03em}
        .site-brand__subtitle{margin:2px 0 0;color:var(--text-soft);font-size:.88rem}
        .site-nav,.site-actions,.actions,.context{display:flex;flex-wrap:wrap;gap:10px;align-items:center}
        .site-nav__link{display:inline-flex;align-items:center;justify-content:center;min-height:34px;padding:0 .34rem;border-radius:6px;border:1px solid transparent;background:transparent;color:var(--text-soft);font-size:.96rem;font-weight:600}
        .site-nav__link:hover{text-decoration:none;color:var(--text-strong);background:rgba(var(--brand-rgb),.09);border-color:rgba(var(--brand-rgb),.18)}
        .site-nav__link.active{background:rgba(var(--brand-rgb),.16);color:var(--text-strong);border-color:rgba(var(--brand-rgb),.28)}
        .site-more{position:relative}
        .site-more[open]{z-index:25}
        .site-more__toggle{display:inline-flex;align-items:center;justify-content:center;min-height:34px;padding:0 .6rem;border-radius:8px;border:1px solid rgba(255,255,255,.08);background:rgba(255,255,255,.03);color:var(--text-soft);font-size:.96rem;font-weight:600;cursor:pointer;list-style:none}
        .site-more__toggle::-webkit-details-marker{display:none}
        .site-more__panel{position:absolute;right:0;top:calc(100% + 10px);min-width:240px;padding:12px;border-radius:14px;border:1px solid var(--line);background:var(--surface-3);box-shadow:var(--shadow);display:grid;gap:8px}
        .site-more__group{display:grid;gap:8px;padding:8px;border-radius:12px;background:var(--surface-soft)}
        .site-more__label{font-size:.76rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase;color:var(--text-faint)}
        .site-mobile{display:none}
        .site-mobile__toggle{display:none;align-items:center;gap:10px;cursor:pointer;min-height:38px;padding:.45rem .72rem;border-radius:10px;border:1px solid var(--line-strong);background:rgba(255,255,255,.04);color:var(--text-strong);font-weight:600}
        .site-mobile__toggle::before{content:"";display:block;width:18px;height:2px;border-radius:999px;background:currentColor;box-shadow:0 -6px 0 currentColor,0 6px 0 currentColor}
        .mobile-drawer{position:fixed;inset:0;display:none;z-index:55}
        .mobile-drawer.is-open{display:block}
        .mobile-drawer__scrim{position:absolute;inset:0;background:rgba(4,10,18,.58);backdrop-filter:blur(6px)}
        .mobile-drawer__panel{position:absolute;right:0;top:0;bottom:0;width:min(100vw,420px);max-width:100%;padding:18px 16px calc(28px + env(safe-area-inset-bottom));background:var(--surface-3);border-left:1px solid var(--line);box-shadow:var(--shadow);display:grid;grid-template-rows:auto 1fr auto;gap:18px;overflow:auto}
        .mobile-drawer__header{display:flex;align-items:flex-start;justify-content:space-between;gap:12px}
        .mobile-drawer__title{margin:0;font-size:1.08rem}
        .mobile-drawer__subtitle{margin:4px 0 0;color:var(--text-soft);font-size:.9rem}
        .mobile-drawer__close{display:inline-flex;align-items:center;justify-content:center;width:40px;height:40px;border-radius:999px;border:1px solid var(--line);background:rgba(255,255,255,.04);color:var(--text-strong);font-size:1.15rem;font-weight:700;cursor:pointer}
        .mobile-drawer__section{display:grid;gap:10px}
        .mobile-drawer__label{font-size:.76rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase;color:var(--text-faint)}
        .mobile-drawer__links{display:grid;gap:8px}
        .mobile-drawer__link{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:.9rem 1rem;border-radius:14px;border:1px solid var(--line);background:rgba(255,255,255,.04);color:var(--text-strong);font-weight:700}
        .mobile-drawer__link.active{background:rgba(var(--brand-rgb),.16);border-color:rgba(var(--brand-rgb),.28)}
        .mobile-drawer__footer{display:grid;gap:12px;padding-top:8px;border-top:1px solid var(--line)}
        .mobile-drawer__meta{display:grid;gap:4px}
        .mobile-bottom-nav{display:none}
        .mobile-bottom-nav__link,.mobile-bottom-nav__toggle{display:inline-flex;align-items:center;justify-content:center;gap:6px;min-height:56px;padding:0 8px;border:0;background:transparent;color:var(--text-soft);font:inherit;font-weight:700}
        .mobile-bottom-nav__link.active,.mobile-bottom-nav__toggle.active{color:var(--text-strong)}
        .mobile-bottom-nav__icon{font-size:1rem;line-height:1}
        .mobile-bottom-nav__label{font-size:.74rem}
        .desktop-ledger-shell{display:grid;gap:18px}
        .mobile-ledger-shell{display:none}
        .mobile-screen-head{display:grid;gap:12px}
        .mobile-screen-head__top{display:flex;align-items:flex-start;justify-content:space-between;gap:12px}
        .mobile-screen-head__title{margin:0;font-size:1.55rem;line-height:1.02}
        .mobile-screen-head__copy{margin:0;color:var(--text-soft);font-size:.96rem}
        .mobile-chip-row{display:flex;gap:8px;overflow:auto;padding-bottom:2px}
        .mobile-chip-row .button{white-space:nowrap;min-height:38px;padding:.55rem .8rem}
        .mobile-segmented{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}
        .mobile-segmented .button{width:100%}
        .mobile-capture-card,.mobile-journal-card{display:grid;gap:14px}
        .mobile-form-grid{display:grid;gap:12px}
        .mobile-entry-list{display:grid;gap:10px}
        .mobile-entry-row{display:grid;grid-template-columns:minmax(0,1fr) 82px;gap:12px;align-items:center;padding:14px;border:1px solid var(--line);border-radius:14px;background:rgba(255,255,255,.04)}
        .mobile-entry-row strong{display:block;font-size:1rem}
        .mobile-entry-row span{display:block;color:var(--text-soft);font-size:.84rem;line-height:1.45}
        .mobile-entry-row input{padding:11px 10px;text-align:center}
        .mobile-sticky-submit{position:sticky;bottom:84px;z-index:8;display:flex;gap:10px;align-items:center;justify-content:space-between;padding:12px 14px;border:1px solid var(--line);border-radius:16px;background:color-mix(in srgb,var(--surface-3) 90%, rgba(var(--brand-rgb),.12) 10%);box-shadow:var(--shadow-soft)}
        .mobile-sticky-submit .button{flex:0 0 auto}
        .mobile-journal-list{display:grid;gap:12px}
        .mobile-journal-item{display:grid;gap:8px;padding:14px;border:1px solid var(--line);border-radius:14px;background:rgba(255,255,255,.04)}
        .mobile-journal-item__head{display:flex;align-items:flex-start;justify-content:space-between;gap:12px}
        .mobile-journal-item__meta{display:grid;gap:4px;color:var(--text-soft);font-size:.86rem}
        .hero,.card,.alert{border:1px solid var(--line);border-radius:var(--radius);background:var(--surface-2);box-shadow:var(--shadow)}
        .sidebar__eyebrow,.eyebrow{display:inline-block;color:#8aa0d0;text-transform:uppercase;letter-spacing:.14em;font-size:.8rem;font-weight:800}
        .sidebar__eyebrow{margin:0}
        .sidebar__title{margin:0;font-size:1.32rem;line-height:1.04}
        .sidebar__subtitle,.muted,p{color:var(--text-soft)}
        .content{width:min(1320px,calc(100vw - 32px));margin:0 auto;min-width:0;display:grid;gap:16px}
        .hero,.card{padding:18px}
        .hero{margin-bottom:0;background:linear-gradient(135deg,rgba(var(--brand-rgb),.20),var(--surface-2) 26%,var(--surface-1) 100%)}
        .grid{display:grid;gap:18px}.grid-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-4{grid-template-columns:repeat(4,minmax(0,1fr))}
        h1{font-size:clamp(1.9rem,4vw,2.8rem);margin:0 0 10px}h2{font-size:1.2rem;margin:0 0 10px}h3{font-size:1rem;margin:0 0 8px}p{margin:0;line-height:1.55}
        .metric{padding:18px;border:1px solid var(--line);border-radius:14px;background:color-mix(in srgb,var(--surface-3) 88%, rgba(var(--brand-rgb),.12) 12%)}.metric strong{display:block;font-size:1.55rem;margin-bottom:6px}
        .list{margin:14px 0 0;padding-left:18px;color:var(--text-soft);line-height:1.7}
        .alert{padding:16px 18px;margin-bottom:0}.alert-success{background:rgba(var(--brand-rgb),.08)}.alert-warning{background:rgba(var(--accent-rgb),.1)}.alert-error{background:rgba(154,31,31,.1)}.alert-info{background:rgba(var(--brand-rgb),.08)}
        .badge{display:inline-flex;align-items:center;padding:7px 12px;border-radius:999px;font-size:.86rem;font-weight:700}
        .badge-neutral{background:rgba(var(--brand-rgb),.12);color:var(--text-strong)}.badge-success{background:rgba(var(--brand-rgb),.12);color:var(--text-strong)}.badge-warning{background:rgba(var(--accent-rgb),.16);color:var(--text-strong)}
        .table{overflow-x:auto}.table table{width:100%;border-collapse:collapse;min-width:720px}.table th,.table td{padding:12px 10px;border-bottom:1px solid var(--line);text-align:left;vertical-align:top}.table th{font-size:.78rem;letter-spacing:.08em;text-transform:uppercase;color:var(--text-soft);background:rgba(255,255,255,.03)}
        .bulk-shell{display:grid;gap:18px}
        .bulk-toolbar,.bulk-footer{display:flex;flex-wrap:wrap;gap:12px;align-items:center;justify-content:space-between}
        .bulk-summary{display:flex;flex-wrap:wrap;gap:10px;align-items:center;color:var(--text-soft);font-weight:600}
        .bulk-chip{display:inline-flex;align-items:center;padding:6px 10px;border-radius:999px;background:rgba(var(--brand-rgb),.12);color:var(--text-strong);font-size:.88rem;font-weight:700}
        form.grid{grid-template-columns:repeat(2,minmax(0,1fr))}label{display:flex;flex-direction:column;gap:8px;font-weight:700}input,select,textarea{width:100%;padding:12px 14px;border-radius:12px;border:1px solid rgba(255,255,255,.08);font:inherit;background:rgba(255,255,255,.04);color:var(--text-strong)}select{color-scheme:dark;background-color:var(--surface-3)}select option,select optgroup{background:var(--surface-3);color:var(--text-strong)}textarea{min-height:120px}
        .footer{margin-top:0;text-align:center;color:var(--text-faint);font-size:.92rem}
        .section-mini{display:grid;gap:10px}
        .section-mini__title{margin:0;font-size:1rem;color:var(--text-strong)}
        .section-mini__copy{margin:0;color:var(--text-soft)}
        body.landing-preview{background:radial-gradient(circle at top center,rgba(88,122,255,.22),transparent 28%),radial-gradient(circle at 20% 20%,rgba(42,72,170,.18),transparent 24%),linear-gradient(180deg,#05070d 0%,#0a0f1a 52%,#0d1320 100%);color:#f4f7ff}
        body.landing-preview h1,body.landing-preview h2,body.landing-preview h3{font-family:"Inter Tight","Aptos","Segoe UI",sans-serif;letter-spacing:-.04em}
        .marketing-shell{min-height:100vh;padding:0 0 92px;display:grid;gap:12px}
        .marketing-main{width:min(1240px,calc(100vw - 48px));margin:0 auto}
        .marketing-bar{position:sticky;top:0;z-index:30;display:flex;align-items:center;justify-content:space-between;gap:14px;height:88px;min-height:88px;width:100vw;margin-left:calc(50% - 50vw);margin-bottom:20px;padding:0 18px;border:0;border-bottom:1px solid rgba(137,154,188,.18);border-radius:0;background:rgba(8,10,18,.82);box-shadow:none;backdrop-filter:blur(16px)}
        .marketing-brand{display:flex;align-items:center;gap:8px;flex:0 0 auto}
        .marketing-brand__mark{width:40px;height:40px;border-radius:10px;display:grid;place-items:center;background:linear-gradient(135deg,#587aff 0%,#243a91 100%);color:#fff;font-size:1rem;font-weight:800;box-shadow:none}
        .marketing-brand__title{margin:0;font-size:1.08rem;line-height:1;color:#f4f7ff}
        .marketing-brand__copy{display:none}
        .marketing-nav,.marketing-actions,.landing-actions{display:flex;flex-wrap:wrap;gap:12px;align-items:center}
        .marketing-nav{gap:6px}
        .marketing-nav a{display:inline-flex;align-items:center;justify-content:center;min-height:36px;padding:0 .3rem;border-radius:6px;border:1px solid transparent;font-size:1rem;font-weight:600;color:rgba(231,238,255,.8)}
        .marketing-nav a:hover{text-decoration:none;color:#f4f7ff;background:rgba(255,255,255,.06);border-color:rgba(201,214,255,.12)}
        .marketing-actions .button{min-height:38px;padding:.42rem .8rem;border-radius:8px;font-size:.94rem}
        .marketing-actions .button.secondary,.marketing-mobile__footer .button.secondary{background:transparent;color:#f4f7ff;border-color:rgba(201,214,255,.16);box-shadow:none}
        .marketing-mobile{display:none;position:relative}
        .marketing-mobile[open]{z-index:40}
        .marketing-mobile__toggle{display:inline-flex;align-items:center;justify-content:center;gap:10px;list-style:none;cursor:pointer;min-width:38px;min-height:38px;padding:.24rem .46rem;border-radius:8px;border:1px solid rgba(201,214,255,.14);background:rgba(255,255,255,.04);color:#f4f7ff}
        .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,.14);background:rgba(8,10,18,.96);box-shadow:0 18px 36px rgba(1,5,13,.45)}
        .marketing-mobile__stack{display:grid;gap:8px}
        .marketing-mobile__stack .marketing-nav__link{justify-content:flex-start;padding:.55rem .7rem;background:rgba(255,255,255,.04);border-color:rgba(201,214,255,.1)}
        .marketing-mobile__footer{margin-top:12px;display:flex;justify-content:flex-end}
        .landing-wrap{display:grid;gap:28px;padding:8px 0 12px}
        .landing-hero{display:grid;grid-template-columns:minmax(0,1.12fr) minmax(290px,.88fr);gap:36px;align-items:start;padding-top:8px}
        .landing-copy{display:grid;gap:12px}
        .landing-copy__eyebrow{margin:0;text-transform:uppercase;letter-spacing:.16em;font-size:.78rem;font-weight:700;color:#8aa0d0}
        .landing-copy h1{margin:0;font-size:clamp(3.2rem,7vw,6.4rem);line-height:.9;letter-spacing:-.06em;color:#f4f7ff}
        .landing-copy__lead{margin:0;max-width:34rem;font-size:1.08rem;line-height:1.65;color:rgba(219,228,248,.74)}
        .landing-copy__note{margin:0;max-width:32rem;color:rgba(193,205,232,.78);font-size:.96rem}
        .landing-actions{margin-top:10px}
        .landing-preview,.landing-section,.landing-callout{border:1px solid rgba(163,183,255,.12);border-radius:20px;background:rgba(14,20,34,.86);box-shadow:0 16px 40px rgba(2,5,12,.34)}
        .landing-preview{padding:20px;display:grid;gap:12px}
        .landing-preview__header{display:flex;align-items:center;justify-content:space-between;gap:12px;padding-bottom:12px;border-bottom:1px solid rgba(163,183,255,.12)}
        .landing-preview__title{margin:0;font-size:1.1rem;color:#f4f7ff}
        .landing-preview__line{display:flex;justify-content:space-between;gap:12px;align-items:center;padding:12px 14px;border-radius:16px;background:rgba(255,255,255,.04);color:rgba(216,225,246,.74);font-weight:600}
        .landing-preview__line strong{color:#f4f7ff}
        .landing-preview__stack{display:grid;gap:12px}
        .landing-section{padding:24px 26px}
        .landing-section__head{display:grid;gap:8px;margin-bottom:18px}
        .landing-section__eyebrow{margin:0;color:#8aa0d0;font-size:.78rem;font-weight:700;letter-spacing:.14em;text-transform:uppercase}
        .landing-section__title{margin:0;font-size:1.9rem;color:#f4f7ff}
        .landing-section__lead{margin:0;max-width:48rem;color:rgba(217,226,246,.8)}
        .landing-feature-grid,.landing-step-grid,.landing-use-grid,.landing-proof-grid{display:grid;gap:12px}
        .landing-feature-grid{grid-template-columns:repeat(4,minmax(0,1fr))}
        .landing-step-grid,.landing-use-grid,.landing-proof-grid{grid-template-columns:repeat(3,minmax(0,1fr))}
        .landing-card{padding:18px;border-radius:18px;border:1px solid rgba(163,183,255,.12);background:rgba(255,255,255,.035)}
        .landing-card__number{display:inline-flex;align-items:center;justify-content:center;min-width:2.15rem;height:2.15rem;margin-bottom:14px;border-radius:999px;background:rgba(88,122,255,.16);color:#dfe8ff;font-size:.78rem;font-weight:800;letter-spacing:.06em}
        .landing-card h3{margin:0 0 8px;font-size:1.12rem;color:#f4f7ff}
        .landing-card p{margin:0;color:rgba(219,228,246,.74)}
        .landing-callout{padding:24px 26px}
        .landing-cta{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:16px;padding-top:20px;margin-top:22px;border-top:1px solid rgba(163,183,255,.12)}
        .landing-cta__copy{display:grid;gap:6px}
        .landing-cta__copy strong{font-size:1.05rem;color:#f4f7ff}
        .landing-cta__copy span{color:rgba(217,226,246,.72)}
        .marketing-footer{position:fixed;left:0;right:0;bottom:0;z-index:25;margin-top:0;padding:10px 24px;border-top:1px solid rgba(137,154,188,.14);background:rgba(8,10,18,.88);backdrop-filter:blur(18px);color:rgba(209,217,235,.68);font-size:.92rem}
        .marketing-footer__inner{display:flex;justify-content:space-between;gap:16px;flex-wrap:wrap;width:min(1240px,calc(100% - 48px));margin:0 auto}
        @media(max-width:960px){.marketing-main,.landing-hero,.landing-section,.landing-callout{width:calc(100vw - 24px)}.marketing-bar{height:72px;min-height:72px;margin-bottom:16px;padding:0 12px}.marketing-nav,.marketing-actions{display:none}.marketing-mobile{display:block}.landing-hero,.landing-feature-grid,.landing-step-grid,.landing-use-grid,.landing-proof-grid{grid-template-columns:1fr}.landing-hero{gap:24px;padding-top:0}.landing-section,.landing-callout{padding:20px}.marketing-shell{padding:0 0 88px}.marketing-footer{padding:10px 12px}.marketing-footer__inner{width:100%}}
        @media(max-width:1180px){body.mobile-drawer-open{overflow:hidden}.page-shell{padding-bottom:94px}.site-header{margin-bottom:14px}.site-header__inner{min-height:68px;width:100%;align-items:center;padding:10px 16px}.site-brand__subtitle{font-size:.8rem}.site-nav{display:none}.site-mobile{display:block}.site-actions{gap:8px}.site-actions .site-more{display:none}.site-mobile__toggle{display:inline-flex}.content{width:min(100vw - 20px,1460px);gap:14px}.hero{padding:16px}.hero .eyebrow,.hero p{display:none}.hero h1{font-size:1.5rem;margin:0}.grid-2,.grid-3,.grid-4,form.grid{grid-template-columns:1fr}.table table{min-width:0}.desktop-ledger-shell{display:none}.mobile-ledger-shell{display:grid;gap:14px}.mobile-bottom-nav{position:fixed;left:10px;right:10px;bottom:max(10px,env(safe-area-inset-bottom));z-index:45;display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:4px;padding:6px;border:1px solid var(--line);border-radius:18px;background:color-mix(in srgb,var(--surface-3) 92%, rgba(var(--brand-rgb),.12) 8%);box-shadow:var(--shadow)}}
        @media(min-width:1181px){.site-mobile{display:none}}
    </style>
</head>
<body class="<?= $isMarketingHome ? 'landing-preview' : '' ?>" data-theme="<?= h($themeMode) ?>">
    <?php if ($isMarketingHome): ?>
        <main class="marketing-shell">
            <header class="marketing-bar">
                <div class="marketing-brand">
                    <div class="marketing-brand__mark">K</div>
                    <div>
                        <h1 class="marketing-brand__title">Die Kaffeeliste</h1>
                    </div>
                </div>

                <nav class="marketing-nav" aria-label="Startseiten-Navigation">
                    <a href="/">Start</a>
                    <a href="/login/">Anmeldung</a>
                    <a href="/admin/login/">Admin</a>
                </nav>

                <div class="marketing-actions">
                    <a class="button secondary" href="/login/">Anmelden</a>
                </div>

                <details class="marketing-mobile">
                    <summary class="marketing-mobile__toggle" aria-label="Menü"></summary>
                    <div class="marketing-mobile__panel">
                        <nav class="marketing-mobile__stack" aria-label="Mobile Startseiten-Navigation">
                            <a href="/" class="marketing-nav__link">Start</a>
                            <a href="/login/" class="marketing-nav__link">Anmeldung</a>
                            <a href="/admin/login/" class="marketing-nav__link">Admin</a>
                        </nav>
                        <div class="marketing-mobile__footer">
                            <a class="button secondary" href="/login/">Anmelden</a>
                        </div>
                    </div>
                </details>
            </header>

            <?php if ($flash !== null): ?>
                <section class="alert alert-<?= h((string) ($flash['type'] ?? 'info')) ?>" style="width:min(1240px,calc(100vw - 48px));margin:0 auto;"><?= h((string) ($flash['message'] ?? '')) ?></section>
            <?php endif; ?>

            <section class="landing-hero">
                <div class="landing-copy">
                    <p class="landing-copy__eyebrow"><?= h($heroEyebrow) ?></p>
                    <h1><?= h($heroTitle) ?></h1>
                    <p class="landing-copy__lead"><?= h($heroCopy) ?></p>
                    <p class="landing-copy__note">Für Mitglieder, Verantwortliche und Standorte. Mobil nutzbar, klar geführt und ohne unnötige Umwege.</p>
                    <div class="landing-actions">
                        <a class="button" href="/login/">Anmelden</a>
                        <a class="button secondary" href="#funktionen">Funktionen ansehen</a>
                    </div>
                </div>

                <aside class="landing-preview" aria-label="Vorschau">
                    <div class="landing-preview__header">
                        <h2 class="landing-preview__title">Übersicht</h2>
                        <span>Heute</span>
                    </div>
                    <div class="landing-preview__stack">
                        <?php foreach ($landingPreview as $item): ?>
                            <div class="landing-preview__line">
                                <span><?= h((string) ($item['label'] ?? '')) ?></span>
                                <strong><?= h((string) ($item['value'] ?? '')) ?></strong>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </aside>
            </section>

            <section class="landing-section" id="funktionen" aria-label="Funktionen">
                <div class="landing-section__head">
                    <p class="landing-section__eyebrow">Produkt</p>
                    <h2 class="landing-section__title">Was die Kaffeeliste im Alltag abdeckt</h2>
                    <p class="landing-section__lead">Vom Überblick bis zur Auswertung bleibt alles in einer Oberfläche, die sofort verständlich wirkt.</p>
                </div>

                <div class="landing-feature-grid">
                    <?php foreach ($landingFeatures as $feature): ?>
                        <article class="landing-card">
                            <h3><?= h((string) ($feature['title'] ?? '')) ?></h3>
                            <p><?= h((string) ($feature['copy'] ?? '')) ?></p>
                        </article>
                    <?php endforeach; ?>
                </div>
            </section>

            <section class="landing-section" id="ablauf" aria-label="Ablauf">
                <div class="landing-section__head">
                    <p class="landing-section__eyebrow">Ablauf</p>
                    <h2 class="landing-section__title">So funktioniert es</h2>
                    <p class="landing-section__lead">Vom ersten Login bis zum täglichen Einsatz bleibt der Weg kurz und nachvollziehbar.</p>
                </div>

                <div class="landing-step-grid">
                    <?php foreach ($landingSteps as $step): ?>
                        <article class="landing-card">
                            <span class="landing-card__number"><?= h((string) ($step['number'] ?? '')) ?></span>
                            <h3><?= h((string) ($step['title'] ?? '')) ?></h3>
                            <p><?= h((string) ($step['copy'] ?? '')) ?></p>
                        </article>
                    <?php endforeach; ?>
                </div>
            </section>

            <section class="landing-section" id="zielgruppen" aria-label="Zielgruppen">
                <div class="landing-section__head">
                    <p class="landing-section__eyebrow">Für wen</p>
                    <h2 class="landing-section__title">Für Mitglieder, Verantwortliche und Standorte</h2>
                    <p class="landing-section__lead">Jede Rolle bekommt genau die Informationen und Wege, die sie im Alltag braucht.</p>
                </div>

                <div class="landing-use-grid">
                    <?php foreach ($landingUseCases as $useCase): ?>
                        <article class="landing-card">
                            <h3><?= h((string) ($useCase['title'] ?? '')) ?></h3>
                            <p><?= h((string) ($useCase['copy'] ?? '')) ?></p>
                        </article>
                    <?php endforeach; ?>
                </div>
            </section>

            <section class="landing-section" id="vertrauen" aria-label="Vertrauen">
                <div class="landing-section__head">
                    <p class="landing-section__eyebrow">Warum es passt</p>
                    <h2 class="landing-section__title">Klar genug für den Alltag, ruhig genug für gutes Produktdesign</h2>
                    <p class="landing-section__lead">Reduziert gestaltet, aber mit genug Tiefe für Teams, die mehr als nur eine einfache Liste brauchen.</p>
                </div>

                <div class="landing-proof-grid">
                    <?php foreach ($landingProof as $item): ?>
                        <article class="landing-card">
                            <h3><?= h((string) ($item['title'] ?? '')) ?></h3>
                            <p><?= h((string) ($item['copy'] ?? '')) ?></p>
                        </article>
                    <?php endforeach; ?>
                </div>
            </section>

            <section class="landing-callout">
                <p class="landing-section__eyebrow">Zum Start</p>
                <h2>Ein gemeinsamer Einstieg für Teams, die Kaffee einfach organisieren wollen.</h2>
                <p>Klar im Aufbau, direkt in der Nutzung und bereit für den täglichen Einsatz im Team.</p>
                <div class="landing-cta">
                    <div class="landing-cta__copy">
                        <strong>Direkt loslegen</strong>
                        <span>Ohne Umwege zur Anmeldung.</span>
                    </div>
                    <div class="actions">
                        <a class="button" href="/login/">Anmelden</a>
                        <a class="button secondary" href="#funktionen">Funktionen ansehen</a>
                    </div>
                </div>
            </section>

            <footer class="marketing-footer">
                <div class="marketing-footer__inner">
                    <span>Die Kaffeeliste</span>
                    <span>Ein ruhiger Einstieg für Teams</span>
                </div>
            </footer>
        </main>
    <?php else: ?>
    <main class="page-shell">
        <header class="site-header">
            <div class="site-header__inner">
                <a href="<?= $auth === null ? '/' : '/dashboard/' ?>" class="site-brand">
                    <div class="site-brand__mark">K</div>
                    <div>
                        <h1 class="site-brand__title">Die Kaffeeliste</h1>
                        <p class="site-brand__subtitle"><?= $auth === null ? h($currentNavLabel) : h((string) ($auth['tenant_name'] ?? 'Bereich')) ?></p>
                    </div>
                </a>

                <nav class="site-nav" aria-label="Hauptnavigation">
                    <?php foreach ($headerNavItems as $item): ?>
                        <a href="<?= h((string) ($item['href'] ?? '/')) ?>" class="site-nav__link <?= $page === (string) ($item['key'] ?? '') ? 'active' : '' ?>" <?= $page === (string) ($item['key'] ?? '') ? 'aria-current="page"' : '' ?>><?= h((string) ($item['label'] ?? 'Link')) ?></a>
                    <?php endforeach; ?>
                    <?php foreach ($navGroups as $group): ?>
                        <details class="site-more">
                            <summary class="site-more__toggle"><?= h((string) ($group['label'] ?? 'Mehr')) ?></summary>
                            <div class="site-more__panel">
                                <div class="site-more__group">
                                    <div class="site-more__label"><?= h((string) ($group['label'] ?? 'Mehr')) ?></div>
                                    <?php foreach (($group['items'] ?? []) as $item): ?>
                                        <a href="<?= h((string) ($item['href'] ?? '/')) ?>" class="site-nav__link <?= $page === (string) ($item['key'] ?? '') ? 'active' : '' ?>" <?= $page === (string) ($item['key'] ?? '') ? 'aria-current="page"' : '' ?>><?= h((string) ($item['label'] ?? 'Link')) ?></a>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </details>
                    <?php endforeach; ?>
                </nav>

                <div class="site-actions">
                    <?php if ($auth === null): ?>
                        <a class="button secondary" href="/login/">Anmelden</a>
                    <?php else: ?>
                        <details class="site-more">
                            <summary class="site-more__toggle">Konto</summary>
                            <div class="site-more__panel">
                                <div class="site-more__group">
                                    <div class="site-more__label">Konto</div>
                                    <?php foreach ($accountNavItems as $item): ?>
                                        <a href="<?= h((string) ($item['href'] ?? '/')) ?>" class="site-nav__link <?= $page === (string) ($item['key'] ?? '') ? 'active' : '' ?>" <?= $page === (string) ($item['key'] ?? '') ? 'aria-current="page"' : '' ?>><?= h((string) ($item['label'] ?? 'Link')) ?></a>
                                    <?php endforeach; ?>
                                    <form method="post" action="/logout/"><button type="submit" class="button secondary" style="width:100%">Abmelden</button></form>
                                </div>
                            </div>
                        </details>
                        <button type="button" class="site-mobile__toggle" data-mobile-drawer-open>Menü</button>
                    <?php endif; ?>
                </div>
            </div>
        </header>

        <?php if ($auth !== null): ?>
            <div class="mobile-drawer" data-mobile-drawer>
                <button type="button" class="mobile-drawer__scrim" aria-label="Menü schließen" data-mobile-drawer-close></button>
                <aside class="mobile-drawer__panel" aria-label="Menü">
                    <div class="mobile-drawer__header">
                        <div>
                            <h2 class="mobile-drawer__title">Menü</h2>
                            <p class="mobile-drawer__subtitle"><?= h((string) ($auth['tenant_name'] ?? 'Bereich')) ?></p>
                        </div>
                        <button type="button" class="mobile-drawer__close" aria-label="Schließen" data-mobile-drawer-close>&times;</button>
                    </div>
                    <?php if ($headerNavItems !== []): ?>
                        <div class="mobile-drawer__section">
                            <div class="mobile-drawer__label">Kernnavigation</div>
                            <div class="mobile-drawer__links">
                                <?php foreach ($headerNavItems as $item): ?>
                                    <a href="<?= h((string) ($item['href'] ?? '/')) ?>" class="mobile-drawer__link <?= $page === (string) ($item['key'] ?? '') ? 'active' : '' ?>" <?= $page === (string) ($item['key'] ?? '') ? 'aria-current="page"' : '' ?>><?= h((string) ($item['label'] ?? 'Link')) ?></a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endif; ?>
                    <?php foreach ($navGroups as $group): ?>
                        <div class="mobile-drawer__section">
                            <div class="mobile-drawer__label"><?= h((string) ($group['label'] ?? 'Mehr')) ?></div>
                            <div class="mobile-drawer__links">
                                <?php foreach (($group['items'] ?? []) as $item): ?>
                                    <a href="<?= h((string) ($item['href'] ?? '/')) ?>" class="mobile-drawer__link <?= $page === (string) ($item['key'] ?? '') ? 'active' : '' ?>"><?= h((string) ($item['label'] ?? 'Link')) ?></a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                    <div class="mobile-drawer__footer">
                        <div class="mobile-drawer__section">
                            <div class="mobile-drawer__label">Konto</div>
                            <div class="mobile-drawer__links">
                                <?php foreach ($accountNavItems as $item): ?>
                                    <a href="<?= h((string) ($item['href'] ?? '/')) ?>" class="mobile-drawer__link <?= $page === (string) ($item['key'] ?? '') ? 'active' : '' ?>" <?= $page === (string) ($item['key'] ?? '') ? 'aria-current="page"' : '' ?>><?= h((string) ($item['label'] ?? 'Link')) ?></a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <form method="post" action="/logout/"><button type="submit" class="button secondary" style="width:100%">Abmelden</button></form>
                    </div>
                </aside>
            </div>
        <?php endif; ?>

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

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

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

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

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

            <?php if ($dbError !== null): ?>
                <section class="alert alert-warning">Die Datenbank konnte noch nicht gelesen werden: <?= h($dbError) ?></section>
            <?php endif; ?>
        <?php elseif ($page === 'login'): ?>
            <section class="hero">
                <div class="eyebrow">Anmeldung</div>
                <h1>Anmeldung</h1>
                <p>Mit deiner E-Mail weiter.</p>
                <div class="context" style="margin-top:16px">
                    <?= badge('Einfach') ?>
                    <?= badge('Direkt') ?>
                    <?= badge('Klar') ?>
                </div>
            </section>

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

            <section class="grid grid-2">
                <article class="card">
                    <?php if ($loginStep === 'choose-tenant'): ?>
                        <div class="eyebrow">Schritt 2</div>
                        <h2>Bereich wählen</h2>
                        <div class="stack">
                            <?php foreach (($loginState['memberships'] ?? []) as $membership): ?>
                                <form method="post" action="/login/" class="card">
                                    <input type="hidden" name="action" value="choose-tenant">
                                    <input type="hidden" name="tenant_user_id" value="<?= h((string) ($membership['tenant_user_id'] ?? '')) ?>">
                                    <h3><?= h((string) ($membership['tenant_name'] ?? 'Tenant')) ?></h3>
                                    <p><?= h((string) ($membership['display_name'] ?? $membership['user_email'] ?? '')) ?></p>
                                    <p class="muted"><?= h((string) ($membership['role_keys'] ?? 'Mitglied')) ?></p>
                                    <p class="muted"><?= (int) ($membership['oidc_provider_count'] ?? 0) > 0 ? 'Anmeldung per Passwort oder ADFS/OIDC vorbereitet.' : 'Lokale Passwort-Anmeldung.' ?></p>
                                    <div class="actions" style="margin-top:12px"><button type="submit">Diesen Tenant öffnen</button></div>
                                </form>
                            <?php endforeach; ?>
                        </div>
                    <?php elseif ($loginStep === 'password' && is_array($selectedMembership)): ?>
                        <div class="eyebrow">Schritt 2</div>
                        <h2>Passwort eingeben</h2>
                        <p><?= h((string) ($selectedMembership['tenant_name'] ?? '')) ?></p>
                        <form method="post" action="/login/" class="stack" style="margin-top:16px">
                            <input type="hidden" name="action" value="authenticate">
                            <label>Passwort<input type="password" name="password" autocomplete="current-password" placeholder="Passwort eingeben"></label>
                            <div class="actions">
                                <button type="submit">Anmelden</button>
                                <a class="button secondary" href="/login/">Neu starten</a>
                            </div>
                        </form>
                        <?php if ((int) ($selectedMembership['oidc_provider_count'] ?? 0) > 0): ?>
                            <div class="metric" style="margin-top:16px">
                                <h3>ADFS / OIDC im Tenant</h3>
                                <p>Für diesen Bereich ist Single-Sign-on vorbereitet. Die produktive Weiterleitung hängt von der aktivierten Provider-Konfiguration des Tenants ab; die lokale Passwort-Anmeldung bleibt als Fallback verfügbar.</p>
                            </div>
                        <?php endif; ?>
                    <?php else: ?>
                        <div class="eyebrow">Schritt 1</div>
                        <h2>E-Mail eingeben</h2>
                        <form method="post" action="/login/" class="stack" style="margin-top:16px">
                            <input type="hidden" name="action" value="discover">
                            <label>E-Mail-Adresse<input type="email" name="email" value="<?= h((string) ($loginState['email'] ?? '')) ?>" autocomplete="email" placeholder="mitglied@unternehmen.de"></label>
                            <div class="actions"><button type="submit">Weiter</button></div>
                        </form>
                    <?php endif; ?>
                </article>
                <article class="card">
                    <div class="eyebrow">Hilfe</div>
                    <h2>Wenn es nicht direkt klappt</h2>
                    <ul class="list">
                        <li>Prüfe zuerst, ob du die richtige berufliche E-Mail-Adresse verwendest.</li>
                        <li>Wenn du in mehreren Bereichen arbeitest, wähle den passenden aus.</li>
                        <li>Falls kein Zugang gefunden wird, brauchst du meist nur eine Einladung oder den Kontakt zur verantwortlichen Person.</li>
                    </ul>
                </article>
            </section>
        <?php elseif ($page === 'tenants'): ?>
            <section class="hero">
                <div class="eyebrow">Betreiber-Sicht</div>
                <h1>Mandanten</h1>
                <p>Hier sehen Betreiber, wie viele Tenants aktiv sind, wie die Anmeldung funktioniert und wo Mehrfachzuordnungen sauber abgefangen werden.</p>
            </section>

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

                <section class="card" style="margin-top:18px">
                    <div class="table">
                        <table>
                            <thead><tr><th>Tenant</th><th>Domain</th><th>Mitglieder</th><th>Admins</th><th>Login</th><th>Status</th></tr></thead>
                            <tbody>
                                <?php foreach (($tenantOverview['tenants'] ?? []) as $tenant): ?>
                                    <tr>
                                        <td><strong><?= h((string) $tenant['name']) ?></strong><br><span class="muted"><?= h((string) $tenant['tenant_key']) ?></span></td>
                                        <td><?= h((string) $tenant['domain']) ?></td>
                                        <td><?= num($tenant['member_count'] ?? 0) ?></td>
                                        <td><?= num($tenant['admin_count'] ?? 0) ?></td>
                                        <td><?= h((string) $tenant['login_mode']) ?></td>
                                        <td><?= ((string) ($tenant['status'] ?? 'active')) === 'active' ? badge('Aktiv', 'success') : badge('Prüfen', 'warning') ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </section>
            <?php else: ?>
                <section class="alert alert-warning"><?= h((string) $dbError) ?></section>
            <?php endif; ?>
        <?php elseif ($page === 'dashboard'): ?>
            <?php if ($dashboardAnnouncements !== []): ?>
                <section class="card" style="margin-bottom:18px">
                    <div class="eyebrow">Aktuelle Hinweise</div>
                    <h2>Wichtige Informationen</h2>
                    <div class="stack">
                        <?php foreach ($dashboardAnnouncements as $announcement): ?>
                            <article class="metric">
                                <h3><?= h((string) ($announcement['title'] ?? 'Hinweis')) ?></h3>
                                <p><?= nl2br(h((string) ($announcement['message'] ?? ''))) ?></p>
                                <?php if ((string) ($announcement['visible_until'] ?? '') !== ''): ?>
                                    <p class="muted">Sichtbar bis <?= dt((string) ($announcement['visible_until'] ?? '')) ?></p>
                                <?php endif; ?>
                            </article>
                        <?php endforeach; ?>
                    </div>
                </section>
            <?php endif; ?>

            <section class="hero">
                <div class="eyebrow">Kaffeeliste aktuell</div>
                <h1><?= h((string) $auth['tenant_name']) ?></h1>
                <p>Aktueller Stand der Kaffeeliste mit Salden, Jahreswerten, letzter Aktivität und den wichtigsten Arbeitswegen.</p>
                <?php if (app_is_platform_admin($auth) && app_admin_user() !== null): ?>
                    <div class="actions" style="margin-top:18px">
                        <a class="button secondary" href="/admin/">Zur Verwaltung</a>
                    </div>
                <?php endif; ?>
            </section>

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

            <section class="grid grid-2" style="margin-top:18px">
                <article class="card">
                    <div class="eyebrow">Jahresübersicht</div>
                    <h2>Stand im laufenden Jahr</h2>
                    <div class="grid grid-3">
                        <article class="metric">
                            <strong><?= num($tenantDashboard['year_strokes'] ?? 0) ?></strong>
                            <h3>Striche</h3>
                            <p>Gebuchte Striche im aktuellen Jahr.</p>
                        </article>
                        <article class="metric">
                            <strong><?= money($tenantDashboard['year_spend'] ?? 0) ?></strong>
                            <h3>Ausgaben</h3>
                            <p>Gesamtkosten aus Kaffeeeinträgen.</p>
                        </article>
                        <article class="metric">
                            <strong><?= money($tenantDashboard['year_payments'] ?? 0) ?></strong>
                            <h3>Einzahlungen</h3>
                            <p>Alle verbuchten Einzahlungen im Jahr.</p>
                        </article>
                    </div>
                </article>
                <article class="card">
                    <div class="eyebrow">Status</div>
                    <h2>Kaffeeliste im Überblick</h2>
                    <div class="grid grid-2">
                        <article class="metric">
                            <strong><?= money($tenantDashboard['open_balance'] ?? 0) ?></strong>
                            <h3>Offener Gesamtsaldo</h3>
                            <p>Aktueller Saldo über alle Ledger-Einträge.</p>
                        </article>
                        <article class="metric">
                            <strong><?= num($tenantDashboard['year_active_members'] ?? 0) ?></strong>
                            <h3>Aktive im Jahr</h3>
                            <p>Mitglieder mit mindestens einem Kaffeeeintrag.</p>
                        </article>
                    </div>
                    <div class="actions" style="margin-top:18px">
                        <a class="button secondary" href="/ledger/">Buchungen öffnen</a>
                        <a class="button secondary" href="/payments/">Zahlungen öffnen</a>
                    </div>
                </article>
            </section>

            <?php if ($canManageTenant): ?>
                <section class="card" style="margin-top:18px">
                    <div class="eyebrow">Saldo-Lage</div>
                    <h2>Auffällige Kontostände</h2>
                    <div class="grid grid-2">
                        <div>
                            <h3 style="margin-bottom:10px">Höchste Rückstände</h3>
                            <ul class="list">
                                <?php foreach (($tenantDashboard['largest_debtors'] ?? []) as $row): ?>
                                    <li><?= h((string) ($row['display_name'] ?? 'Mitglied')) ?> · <?= money($row['balance'] ?? 0) ?></li>
                                <?php endforeach; ?>
                                <?php if (($tenantDashboard['largest_debtors'] ?? []) === []): ?><li>Aktuell keine negativen Salden.</li><?php endif; ?>
                            </ul>
                        </div>
                        <div>
                            <h3 style="margin-bottom:10px">Größte Guthaben</h3>
                            <ul class="list">
                                <?php foreach (($tenantDashboard['largest_credits'] ?? []) as $row): ?>
                                    <li><?= h((string) ($row['display_name'] ?? 'Mitglied')) ?> · <?= money($row['balance'] ?? 0) ?></li>
                                <?php endforeach; ?>
                                <?php if (($tenantDashboard['largest_credits'] ?? []) === []): ?><li>Aktuell keine Guthaben über 0 EUR.</li><?php endif; ?>
                            </ul>
                        </div>
                    </div>
                </section>
            <?php else: ?>
                <section class="grid grid-2" style="margin-top:18px">
                    <article class="card">
                        <div class="eyebrow">Self-Service</div>
                        <h2>Mein Bereich</h2>
                        <?php if (($tenantSettings['allow_self_service_booking'] ?? '1') === '1' && !empty($auth['member_id'])): ?>
                            <form method="post" action="/dashboard/" class="grid">
                                <input type="hidden" name="action" value="record-coffee">
                                <input type="hidden" name="member_id" value="<?= h((string) ($auth['member_id'] ?? '')) ?>">
                                <label>Anzahl Striche<input type="number" name="strokes" min="1" max="2" step="1" value="1"></label>
                                <label>Preis pro Strich<input type="number" name="unit_price" min="0.01" step="0.01" value="<?= h((string) ($tenantSettings['default_unit_price'] ?? '0.50')) ?>"></label>
                                <label>Buchungszeit<input type="datetime-local" name="booked_at" value="<?= date('Y-m-d\TH:i') ?>"></label>
                                <input type="hidden" name="booking_source" value="self-service">
                                <div class="actions"><button type="submit">Eigene Striche buchen</button></div>
                            </form>
                        <?php else: ?>
                            <ul class="list">
                                <li>Hier siehst du deinen Kontostand und aktuelle Hinweise.</li>
                                <li>Self-Service-Striche sind in diesem Mandanten aktuell deaktiviert.</li>
                                <li>Wenn dir etwas fehlt, wende dich an den Betreiber deines Bereichs.</li>
                            </ul>
                        <?php endif; ?>
                    </article>

                    <article class="card">
                        <div class="eyebrow">Konto</div>
                        <h2>Persönliche Einstellungen</h2>
                        <p>Profil, Passwort und Anzeigemodus liegen in deiner persönlichen Einstellungsseite.</p>
                        <div class="actions" style="margin-top:18px">
                            <a class="button secondary" href="/profile/">Persönliche Einstellungen öffnen</a>
                        </div>
                        <p class="muted" style="margin-top:12px">Aktuell aktiv: <?= h($themeMode === 'dark' ? 'Dunkelmodus' : 'Hellmodus') ?></p>
                    </article>
                </section>
            <?php endif; ?>

            <?php if ($canManageTenant): ?>
                <section class="card" style="margin-top:18px">
                    <div class="actions" style="justify-content:space-between;margin-bottom:14px">
                        <div>
                            <div class="eyebrow">Kaffeelisten-Stand</div>
                            <h2 style="margin:0">Aktive Mitglieder im Überblick</h2>
                        </div>
                        <div class="actions">
                            <a class="button secondary" href="/members/">Mitgliederverwaltung öffnen</a>
                            <?php if ($hasPdfExportFeature || $hasPaperStrikeEntryFeature): ?>
                                <a class="button secondary" href="/exports/">PDF-Export öffnen</a>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="table">
                        <table>
                            <thead><tr><th>Mitglied</th><th>Saldo</th><th>Striche Jahr</th><th>Einzahlungen Jahr</th><th>Letzte Aktivität</th></tr></thead>
                            <tbody>
                                <?php foreach (($tenantDashboard['member_rows'] ?? []) as $row): ?>
                                    <tr>
                                        <td><?= h((string) ($row['display_name'] ?? '')) ?></td>
                                        <td><?= money($row['balance'] ?? 0) ?></td>
                                        <td><?= num($row['year_strokes'] ?? 0) ?></td>
                                        <td><?= money($row['year_payments'] ?? 0) ?></td>
                                        <td><?= dt((string) ($row['last_booking_at'] ?? '')) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </section>
            <?php endif; ?>
        <?php elseif ($page === 'members'): ?>
            <section class="hero">
                <div class="eyebrow">Mitgliederverwaltung</div>
                <h1>Mitglieder</h1>
                <p>Hier legst du neue Personen an, gibst Zugänge frei und weist Rollen für Verwaltung, Finanzen, Support und Umfragen zu.</p>
                <?php if (app_is_platform_admin($auth) && app_admin_user() !== null): ?>
                    <div class="actions" style="margin-top:18px">
                        <a class="button secondary" href="/admin/">Zur zentralen Verwaltung</a>
                        <span class="badge">Übersicht im Menü</span>
                    </div>
                <?php endif; ?>
            </section>
            <section class="grid grid-2">
                <article class="card">
                    <h2><?= $editingMember !== null ? 'Person bearbeiten' : 'Neue Person anlegen' ?></h2>
                    <form method="post" action="/members/" class="grid">
                        <input type="hidden" name="action" value="save-member">
                        <input type="hidden" name="tenant_user_id" value="<?= h((string) $memberForm['tenant_user_id']) ?>">
                        <label>Name<input name="display_name" value="<?= h((string) $memberForm['display_name']) ?>" required></label>
                        <label>E-Mail-Adresse<input type="email" name="email" value="<?= h((string) $memberForm['email']) ?>" required></label>
                        <label>Zahlungsreferenz<input name="payment_reference" value="<?= h((string) ($memberForm['payment_reference'] ?? '')) ?>" placeholder="PayPal-Name oder Referenz"></label>
                        <label>Status<select name="status"><option value="active"<?= $memberForm['status'] === 'active' ? ' selected' : '' ?>>Aktiv</option><option value="inactive"<?= $memberForm['status'] === 'inactive' ? ' selected' : '' ?>>Inaktiv</option></select></label>
                        <label>Passwort<input type="password" name="password" placeholder="<?= $editingMember !== null ? 'Nur für Passwortwechsel ausfüllen' : 'Für die erste Anmeldung erforderlich' ?>"></label>
                        <label class="checkbox" style="display:flex;flex-direction:row;align-items:center;font-weight:600;"><input type="checkbox" name="tenant_admin"<?= !empty($memberForm['is_tenant_admin']) ? ' checked' : '' ?> style="width:auto"><span>Tenant-Admin</span></label>
                        <label class="checkbox" style="display:flex;flex-direction:row;align-items:center;font-weight:600;"><input type="checkbox" name="finance_admin"<?= !empty($memberForm['is_finance_admin']) ? ' checked' : '' ?> style="width:auto"><span>Finanzen</span></label>
                        <label class="checkbox" style="display:flex;flex-direction:row;align-items:center;font-weight:600;"><input type="checkbox" name="support_contact"<?= !empty($memberForm['is_support_contact']) ? ' checked' : '' ?> style="width:auto"><span>Support</span></label>
                        <label class="checkbox" style="display:flex;flex-direction:row;align-items:center;font-weight:600;"><input type="checkbox" name="survey_manager"<?= !empty($memberForm['is_survey_manager']) ? ' checked' : '' ?> style="width:auto"><span>Umfragen</span></label>
                        <div class="actions">
                            <button type="submit">Speichern</button>
                            <?php if ($editingMember !== null): ?>
                                <a class="button secondary" href="/members/">Neue Person erfassen</a>
                            <?php endif; ?>
                        </div>
                    </form>
                </article>
                <article class="card">
                    <?php if (is_array($memberReport)): ?>
                        <h2>Mitgliedsdetail</h2>
                        <div class="stack">
                            <div class="metric"><h3><?= h((string) ($memberReport['display_name'] ?? '')) ?></h3><p><?= h((string) ($memberReport['email'] ?? '')) ?></p></div>
                            <div class="metric"><h3>Saldo</h3><p><?= money($memberReport['summary']['balance'] ?? 0) ?></p></div>
                            <div class="metric"><h3>Dieses Jahr</h3><p><?= num($memberReport['summary']['year_strokes'] ?? 0) ?> Striche, <?= money($memberReport['summary']['year_payments'] ?? 0) ?> Einzahlungen</p></div>
                            <div class="actions"><a class="button secondary" href="/members/">Auswahl zurücksetzen</a></div>
                        </div>
                    <?php else: ?>
                        <h2>Mitglied auswählen</h2>
                        <ul class="list">
                            <li>Öffne eine Person aus der Tabelle, um Jahreswerte und letzte Buchungen zu sehen.</li>
                            <li>Rollen können hier direkt differenziert nach Verwaltung, Finanzen, Support und Umfragen vergeben werden.</li>
                            <li>So bildet die neue Webseite die Rollenmatrix der Roadmap sichtbar im Tenant ab.</li>
                        </ul>
                    <?php endif; ?>
                </article>
            </section>
            <section class="card" style="margin-top:18px">
                <div class="table">
                    <table>
                        <thead><tr><th>Name</th><th>E-Mail</th><th>Referenz</th><th>Status</th><th>Saldo</th><th>Rollen</th><th>Aktion</th></tr></thead>
                        <tbody>
                            <?php foreach ($members as $member): ?>
                                <tr>
                                    <td><strong><?= h((string) $member['display_name']) ?></strong></td>
                                    <td><?= h((string) $member['email']) ?></td>
                                    <td><?= h((string) ($member['payment_reference'] ?? '-')) ?></td>
                                    <td><?= ((string) ($member['status'] ?? 'active')) === 'active' ? badge('Aktiv', 'success') : badge('Inaktiv', 'warning') ?></td>
                                    <td><?= money($member['current_balance'] ?? 0) ?></td>
                                    <td><?= h((string) (($member['roles'] ?? '') !== '' ? $member['roles'] : 'Mitglied')) ?></td>
                                    <td><div class="actions"><a class="button secondary" href="/members/?edit=<?= h((string) ($member['tenant_user_id'] ?? '')) ?>">Bearbeiten</a><a class="button secondary" href="/members/?member=<?= h((string) ($member['id'] ?? '')) ?>">Details</a></div></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </section>
            <?php if (is_array($memberReport) && ($memberReport['recent_entries'] ?? []) !== []): ?>
                <section class="card" style="margin-top:18px">
                    <h2>Letzte Buchungen der ausgewählten Person</h2>
                    <div class="table">
                        <table>
                            <thead><tr><th>Zeit</th><th>Typ</th><th>Referenz</th><th>Betrag</th></tr></thead>
                            <tbody><?php foreach (($memberReport['recent_entries'] ?? []) as $entry): ?><tr><td><?= dt((string) ($entry['booked_at'] ?? '')) ?></td><td><?= h((string) ($entry['entry_type'] ?? '')) ?></td><td><?= h((string) ($entry['reference_type'] ?? '')) ?></td><td><?= money($entry['amount'] ?? 0) ?></td></tr><?php endforeach; ?></tbody>
                        </table>
                    </div>
                </section>
            <?php endif; ?>
        <?php elseif ($page === 'ledger'): ?>
            <div class="mobile-ledger-shell">
                <section class="mobile-screen-head card">
                    <div class="mobile-screen-head__top">
                        <div>
                            <div class="eyebrow">Buchungen</div>
                            <h1 class="mobile-screen-head__title">Buchungen</h1>
                        </div>
                        <span class="bulk-chip"><?= num(count($ledger)) ?> Journal</span>
                    </div>
                    <p class="mobile-screen-head__copy">Mobil steht die Erfassung im Vordergrund. Das Journal bleibt als zweite Sicht direkt erreichbar.</p>
                    <div class="mobile-segmented">
                        <a class="button <?= $ledgerViewMode === 'capture' ? '' : 'secondary' ?>" href="/ledger/?scope=<?= h($ledgerScope) ?>&mode=capture">Erfassen</a>
                        <a class="button <?= $ledgerViewMode === 'journal' ? '' : 'secondary' ?>" href="/ledger/?scope=<?= h($ledgerScope) ?>&mode=journal">Journal</a>
                    </div>
                </section>
                <?php if ($ledgerViewMode === 'capture'): ?>
                    <section class="card mobile-capture-card">
                        <div class="bulk-summary">
                            <span class="bulk-chip"><?= num(count($ledgerMembers)) ?> Teilnehmer</span>
                            <span><?= h(['all' => 'Alle', 'front' => 'Vorderseite', 'back' => 'Rückseite'][$ledgerScope] ?? 'Alle') ?></span>
                        </div>
                        <div class="mobile-chip-row">
                            <?php foreach (['all' => 'Alle', 'front' => 'Vorderseite', 'back' => 'Rückseite'] as $scopeKey => $scopeLabel): ?>
                                <a class="button <?= $ledgerScope === $scopeKey ? '' : 'secondary' ?>" href="/ledger/?scope=<?= h($scopeKey) ?>&mode=capture"><?= h($scopeLabel) ?></a>
                            <?php endforeach; ?>
                        </div>
                        <form method="post" action="/ledger/" class="mobile-form-grid">
                            <input type="hidden" name="action" value="bulk-record-coffee">
                            <input type="hidden" name="scope" value="<?= h($ledgerScope) ?>">
                            <label>Preis pro Strich<input type="number" name="unit_price" min="0.01" step="0.01" value="<?= h((string) ($tenantSettings['default_unit_price'] ?? '0.50')) ?>"></label>
                            <label>Buchungszeit<input type="datetime-local" name="booked_at" value="<?= date('Y-m-d\TH:i') ?>"></label>
                            <div class="mobile-entry-list">
                                <?php foreach ($ledgerMembers as $member): ?>
                                    <label class="mobile-entry-row">
                                        <div>
                                            <strong><?= h((string) ($member['display_name'] ?? '')) ?></strong>
                                            <span><?= num($member['recent_strokes'] ?? 0) ?> Striche in 100 Tagen</span>
                                        </div>
                                        <input type="number" name="strokes[<?= h((string) ($member['id'] ?? '')) ?>]" min="0" step="1" value="0">
                                    </label>
                                <?php endforeach; ?>
                            </div>
                            <div class="mobile-sticky-submit">
                                <span class="muted">Lokaler Batch fuer alle Werte > 0</span>
                                <button type="submit">Speichern</button>
                            </div>
                        </form>
                    </section>
                <?php else: ?>
                    <section class="card mobile-journal-card">
                        <div class="bulk-summary">
                            <span class="bulk-chip"><?= num(count($ledger)) ?> Einträge</span>
                            <span>Prüfen und korrigieren</span>
                        </div>
                        <div class="mobile-journal-list">
                            <?php foreach ($ledger as $entry): ?>
                                <article class="mobile-journal-item">
                                    <div class="mobile-journal-item__head">
                                        <div>
                                            <strong><?= h((string) ($entry['member_name'] ?? '')) ?></strong>
                                            <div class="mobile-journal-item__meta">
                                                <span><?= h((string) ($entry['entry_type'] ?? '')) ?> · <?= h((string) ($entry['reference_type'] ?? '')) ?></span>
                                                <span><?= dt((string) ($entry['booked_at'] ?? '')) ?></span>
                                            </div>
                                        </div>
                                        <strong><?= money($entry['amount'] ?? 0) ?></strong>
                                    </div>
                                    <?php if ((string) ($entry['reference_status'] ?? 'booked') === 'cancelled'): ?>
                                        <span class="muted">Storniert am <?= dt((string) ($entry['reference_cancelled_at'] ?? '')) ?></span>
                                    <?php elseif ((string) ($entry['reference_type'] ?? '') === 'coffee_entry' && (string) ($entry['reference_id'] ?? '') !== ''): ?>
                                        <form method="post" action="/ledger/">
                                            <input type="hidden" name="action" value="delete-coffee">
                                            <input type="hidden" name="reference_id" value="<?= h((string) ($entry['reference_id'] ?? '')) ?>">
                                            <button type="submit" class="button secondary">Stornieren</button>
                                        </form>
                                    <?php endif; ?>
                                </article>
                            <?php endforeach; ?>
                        </div>
                    </section>
                <?php endif; ?>
            </div>
            <div class="desktop-ledger-shell">
                <section class="hero"><div class="eyebrow">Buchungen</div><h1>Striche und Buchungen</h1><p>Kaffeeeinträge und alle zugehörigen Buchungen bleiben tenantweise nachvollziehbar.</p></section>
                <section class="card bulk-shell">
                    <div class="bulk-toolbar">
                        <div>
                            <h2>Sammelerfassung wie in der Kaffeeliste</h2>
                            <div class="bulk-summary">
                                <span class="bulk-chip"><?= num(count($ledgerMembers)) ?> Teilnehmer</span>
                                <span>Ansicht: <?= h(['all' => 'Alle', 'front' => 'Vorderseite', 'back' => 'Rückseite'][$ledgerScope] ?? 'Alle') ?></span>
                            </div>
                        </div>
                        <div class="actions">
                            <?php foreach (['all' => 'Alle', 'front' => 'Vorderseite', 'back' => 'Rückseite'] as $scopeKey => $scopeLabel): ?>
                                <a class="button <?= $ledgerScope === $scopeKey ? '' : 'secondary' ?>" href="/ledger/?scope=<?= h($scopeKey) ?>"><?= h($scopeLabel) ?></a>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <form method="post" action="/ledger/" class="stack">
                        <input type="hidden" name="action" value="bulk-record-coffee">
                        <input type="hidden" name="scope" value="<?= h($ledgerScope) ?>">
                        <div class="grid">
                            <label>Preis pro Strich<input type="number" name="unit_price" min="0.01" step="0.01" value="<?= h((string) ($tenantSettings['default_unit_price'] ?? '0.50')) ?>"></label>
                            <label>Buchungszeit<input type="datetime-local" name="booked_at" value="<?= date('Y-m-d\TH:i') ?>"></label>
                        </div>
                        <div class="table">
                            <table>
                                <thead><tr><th>Mitglied</th><th>Striche</th><th>100 Tage</th></tr></thead>
                                <tbody>
                                    <?php foreach ($ledgerMembers as $member): ?>
                                        <tr>
                                            <td><strong><?= h((string) ($member['display_name'] ?? '')) ?></strong></td>
                                            <td><input type="number" name="strokes[<?= h((string) ($member['id'] ?? '')) ?>]" min="0" step="1" value="0"></td>
                                            <td><?= num($member['recent_strokes'] ?? 0) ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        <div class="bulk-footer"><span class="muted">Die Eingabe gilt nur für Werte größer als 0.</span><button type="submit">Sammel-Striche eintragen</button></div>
                    </form>
                </section>
                <section class="card" style="margin-top:18px">
                    <h2>Einzelbuchung</h2>
                    <form method="post" action="/ledger/" class="grid">
                        <input type="hidden" name="action" value="record-coffee">
                        <label>Mitglied<select name="member_id"><?php foreach ($members as $member): ?><option value="<?= h((string) $member['id']) ?>"><?= h((string) $member['display_name']) ?></option><?php endforeach; ?></select></label>
                        <label>Anzahl Striche<input type="number" name="strokes" min="1" step="1" value="1"></label>
                        <label>Preis pro Strich<input type="number" name="unit_price" min="0.01" step="0.01" value="0.50"></label>
                        <label>Buchungszeit<input type="datetime-local" name="booked_at" value="<?= date('Y-m-d\TH:i') ?>"></label>
                        <div class="actions"><button type="submit">Buchen</button></div>
                    </form>
                </section>
                <section class="card" style="margin-top:18px"><div class="table"><table><thead><tr><th>Zeit</th><th>Mitglied</th><th>Typ</th><th>Referenz</th><th>Betrag</th><th>Aktion</th></tr></thead><tbody><?php foreach ($ledger as $entry): ?><tr><td><?= dt((string) ($entry['booked_at'] ?? '')) ?></td><td><?= h((string) ($entry['member_name'] ?? '')) ?></td><td><?= h((string) ($entry['entry_type'] ?? '')) ?></td><td><?= h((string) ($entry['reference_type'] ?? '')) ?><?php if ((string) ($entry['reference_status'] ?? 'booked') === 'cancelled'): ?><br><span class="muted">Storniert</span><?php endif; ?></td><td><?= money($entry['amount'] ?? 0) ?></td><td><?php if ((string) ($entry['reference_status'] ?? 'booked') === 'cancelled'): ?><span class="muted">Bereits storniert</span><?php elseif ((string) ($entry['reference_type'] ?? '') === 'coffee_entry' && (string) ($entry['reference_id'] ?? '') !== ''): ?><form method="post" action="/ledger/"><input type="hidden" name="action" value="delete-coffee"><input type="hidden" name="reference_id" value="<?= h((string) ($entry['reference_id'] ?? '')) ?>"><button type="submit" class="button secondary">Stornieren</button></form><?php else: ?><span class="muted">-</span><?php endif; ?></td></tr><?php endforeach; ?></tbody></table></div></section>
            </div>
        <?php elseif ($page === 'payments'): ?>
            <section class="hero"><div class="eyebrow">Einzahlungen</div><h1>Zahlungen</h1><p>Einzahlungen werden direkt in Zahlungstabelle und Ledger geschrieben.</p></section>
            <section class="card bulk-shell">
                <div class="bulk-toolbar">
                    <div>
                        <h2>Sammel-Einzahlungen</h2>
                        <div class="bulk-summary">
                            <span class="bulk-chip"><?= num(count($paymentMembers)) ?> Teilnehmer</span>
                            <span>Ansicht: <?= h(['all' => 'Alle', 'front' => 'Vorderseite', 'back' => 'Rückseite'][$paymentScope] ?? 'Alle') ?></span>
                        </div>
                    </div>
                    <div class="actions">
                        <?php foreach (['all' => 'Alle', 'front' => 'Vorderseite', 'back' => 'Rückseite'] as $scopeKey => $scopeLabel): ?>
                            <a class="button <?= $paymentScope === $scopeKey ? '' : 'secondary' ?>" href="/payments/?scope=<?= h($scopeKey) ?>"><?= h($scopeLabel) ?></a>
                        <?php endforeach; ?>
                        <a class="button secondary" href="/imports/">CSV-Import</a>
                    </div>
                </div>
                <form method="post" action="/payments/" class="stack">
                    <input type="hidden" name="action" value="bulk-record-payment">
                    <input type="hidden" name="scope" value="<?= h($paymentScope) ?>">
                    <div class="grid">
                        <label>Zahlungsart<select name="payment_method"><option value="manual">Manuell</option><option value="paypal">PayPal</option><option value="bank">Bank</option></select></label>
                        <label>Buchungszeit<input type="datetime-local" name="booked_at" value="<?= date('Y-m-d\TH:i') ?>"></label>
                    </div>
                    <div class="table">
                        <table>
                            <thead><tr><th>Mitglied</th><th>Betrag</th><th>100 Tage</th></tr></thead>
                            <tbody>
                                <?php foreach ($paymentMembers as $member): ?>
                                    <tr>
                                        <td><strong><?= h((string) ($member['display_name'] ?? '')) ?></strong></td>
                                        <td><input type="number" name="amounts[<?= h((string) ($member['id'] ?? '')) ?>]" min="0" step="0.01" value="0.00"></td>
                                        <td><?= num($member['recent_strokes'] ?? 0) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <div class="bulk-footer"><span class="muted">Die Eingabe gilt nur für Werte größer als 0.</span><button type="submit">Sammel-Einzahlungen eintragen</button></div>
                </form>
                <p><?= h((string) ($tenantSettings['payment_hint'] ?? '')) ?></p>
            </section>
            <section class="card" style="margin-top:18px">
                <h2>Einzelzahlung</h2>
                <form method="post" action="/payments/" class="grid">
                    <input type="hidden" name="action" value="record-payment">
                    <label>Mitglied<select name="member_id"><?php foreach ($members as $member): ?><option value="<?= h((string) $member['id']) ?>"><?= h((string) $member['display_name']) ?></option><?php endforeach; ?></select></label>
                    <label>Betrag<input type="number" name="amount" min="0.01" step="0.01" value="5.00"></label>
                    <label>Zahlungsart<select name="payment_method"><option value="manual">Manuell</option><option value="paypal">PayPal</option><option value="bank">Bank</option></select></label>
                    <label>Buchungszeit<input type="datetime-local" name="booked_at" value="<?= date('Y-m-d\TH:i') ?>"></label>
                    <div class="actions"><button type="submit">Einzahlung speichern</button></div>
                </form>
            </section>
            <section class="card" style="margin-top:18px"><div class="table"><table><thead><tr><th>Zeit</th><th>Mitglied</th><th>Methode</th><th>Betrag</th><th>Status</th><th>Aktion</th></tr></thead><tbody><?php foreach ($payments as $entry): ?><tr><td><?= dt((string) ($entry['booked_at'] ?? '')) ?></td><td><?= h((string) ($entry['member_name'] ?? '')) ?></td><td><?= h((string) ($entry['payment_method'] ?? '')) ?></td><td><?= money($entry['amount'] ?? 0) ?></td><td><?php if ((string) ($entry['status'] ?? 'booked') === 'cancelled'): ?><?= badge('Storniert', 'warning') ?><?php else: ?><?= badge('Aktiv', 'success') ?><?php endif; ?><?php if ((string) ($entry['status'] ?? 'booked') === 'cancelled' && (string) ($entry['cancelled_at'] ?? '') !== ''): ?><br><span class="muted"><?= dt((string) ($entry['cancelled_at'] ?? '')) ?></span><?php endif; ?></td><td><?php if ((string) ($entry['status'] ?? 'booked') === 'cancelled'): ?><span class="muted">Bereits storniert</span><?php else: ?><form method="post" action="/payments/"><input type="hidden" name="action" value="delete-payment"><input type="hidden" name="payment_id" value="<?= h((string) ($entry['id'] ?? '')) ?>"><button type="submit" class="button secondary">Stornieren</button></form><?php endif; ?></td></tr><?php endforeach; ?></tbody></table></div></section>
        <?php elseif ($page === 'imports'): ?>
            <section class="hero">
                <div class="eyebrow">Importe</div>
                <h1>Importe</h1>
                <p>CSV-Zahlungen und PDF-Scan-Jobs werden hier zusammen gebündelt, damit der Importweg im Tenant an einer Stelle landet.</p>
            </section>

            <section class="grid grid-2">
                <article class="card">
                    <div class="eyebrow">CSV-Import</div>
                    <h2>PayPal-CSV hochladen</h2>
                    <p>Importiert eine bestehende PayPal-CSV und ordnet passende Mitglieder automatisch zu.</p>
                    <form method="post" action="/imports/" enctype="multipart/form-data" class="grid" style="margin-top:16px">
                        <input type="hidden" name="action" value="import-paypal-csv">
                        <label>CSV-Datei<input type="file" name="csv_file" accept=".csv,text/csv" required></label>
                        <div class="actions" style="grid-column:1 / -1"><button type="submit">CSV importieren</button></div>
                    </form>
                </article>
                <article class="card">
                    <div class="eyebrow">PDF-Scan</div>
                    <h2>Scan-Import anlegen</h2>
                    <p>Lade ein PDF hoch und wähle bei Bedarf eine Vorlage für die spätere Auswertung aus.</p>
                    <form method="post" action="/imports/" enctype="multipart/form-data" class="grid" style="margin-top:16px">
                        <input type="hidden" name="action" value="create-scan-import-job">
                        <label>PDF-Datei<input type="file" name="scan_pdf" accept="application/pdf" required></label>
                        <label>Template
                            <select name="template_id">
                                <option value="">Ohne Template</option>
                                <?php foreach ($scanTemplates as $template): ?>
                                    <?php
                                        $templateId = (string) ($template['id'] ?? $template['template_id'] ?? $template['key'] ?? '');
                                        $templateLabel = (string) ($template['title'] ?? $template['label'] ?? $template['name'] ?? $template['template_name'] ?? $templateId);
                                    ?>
                                    <option value="<?= h($templateId) ?>"><?= h($templateLabel) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </label>
                        <div class="actions" style="grid-column:1 / -1"><button type="submit">Scan-Job erstellen</button></div>
                    </form>
                </article>
            </section>

            <?php
                $csvSummary = (array) ($importResult['summary'] ?? []);
                $csvImported = (int) ($csvSummary['imported'] ?? 0);
                $csvDuplicates = (int) ($csvSummary['duplicates'] ?? 0);
                $csvUnmatched = (int) ($csvSummary['unmatched'] ?? 0);
                $csvSummaryTotal = $csvImported + $csvDuplicates + $csvUnmatched;
                $selectedScanJobId = is_array($activeScanJob) ? (string) ($activeScanJob['id'] ?? '') : '';
            ?>
            <?php if ($csvSummaryTotal > 0): ?>
                <section class="metric" style="margin-top:18px">
                    <strong><?= num($csvImported) ?></strong>
                    <h3>CSV-Import Ergebnis</h3>
                    <p><?= num($csvImported) ?> importiert, <?= num($csvDuplicates) ?> Dubletten, <?= num($csvUnmatched) ?> ohne Zuordnung.</p>
                </section>
            <?php endif; ?>

            <section class="card" style="margin-top:18px">
                <div class="actions" style="justify-content:space-between;margin-bottom:14px">
                    <div>
                        <div class="eyebrow">Scan-Jobs</div>
                        <h2 style="margin:0">Letzte PDF-Scans</h2>
                    </div>
                </div>
                <div class="table">
                    <table>
                        <thead>
                            <tr>
                                <th>Erstellt</th>
                                <th>Datei</th>
                                <th>Status</th>
                                <th>Template</th>
                                <th>Fehler</th>
                                <th>Aktion</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($scanImportJobs as $job): ?>
                                <?php
                                    $jobId = (string) ($job['id'] ?? '');
                                    $jobCreatedAt = (string) ($job['created_at'] ?? $job['created_at_local'] ?? '');
                                    $jobFileName = (string) ($job['file_name'] ?? $job['filename'] ?? $job['original_filename'] ?? $job['source_filename'] ?? '-');
                                    $jobStatus = (string) ($job['status'] ?? $job['state'] ?? '-');
                                    $jobTemplate = (string) ($job['template_name'] ?? $job['template_label'] ?? $job['template_title'] ?? $job['template_id'] ?? '-');
                                    $jobError = (string) ($job['error_message'] ?? $job['error'] ?? $job['last_error'] ?? '');
                                    $jobStatusNormalized = strtolower(trim($jobStatus));
                                    $canProcessJob = in_array($jobStatusNormalized, ['uploaded', 'failed'], true);
                                    $isSelectedScanJob = $selectedScanJobId !== '' && $selectedScanJobId === $jobId;
                                ?>
                                <tr>
                                    <td><?= dt($jobCreatedAt !== '' ? $jobCreatedAt : null) ?></td>
                                    <td><?= h($jobFileName !== '' ? $jobFileName : '-') ?></td>
                                    <td><?= h($jobStatus !== '' ? $jobStatus : '-') ?></td>
                                    <td><?= h($jobTemplate !== '' ? $jobTemplate : '-') ?></td>
                                    <td><?= h($jobError !== '' ? $jobError : '-') ?></td>
                                    <td>
                                        <div class="actions">
                                            <?php if ($canProcessJob && $jobId !== ''): ?>
                                                <form method="post" action="/imports/">
                                                    <input type="hidden" name="action" value="process-scan-import-job">
                                                    <input type="hidden" name="job_id" value="<?= h($jobId) ?>">
                                                    <button type="submit" class="button secondary">Verarbeiten</button>
                                                </form>
                                            <?php endif; ?>
                                            <?php if ($jobId !== ''): ?>
                                                <a class="button <?= $isSelectedScanJob ? '' : 'secondary' ?>" href="/imports/?scan_job=<?= h($jobId) ?>">Review öffnen</a>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                            <?php if ($scanImportJobs === []): ?>
                                <tr><td colspan="6">Noch keine Scan-Jobs vorhanden.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </section>

            <?php if (is_array($activeScanJob)): ?>
                <?php
                    $activeJobId = (string) ($activeScanJob['id'] ?? '');
                    $activeJobStatus = (string) ($activeScanJob['status'] ?? $activeScanJob['state'] ?? '-');
                    $activeJobFileName = (string) ($activeScanJob['file_name'] ?? $activeScanJob['filename'] ?? $activeScanJob['original_filename'] ?? $activeScanJob['source_filename'] ?? '-');
                ?>
                <section class="card" style="margin-top:18px">
                    <div class="actions" style="justify-content:space-between;align-items:flex-start;margin-bottom:14px">
                        <div>
                            <div class="eyebrow">Review</div>
                            <h2 style="margin:0">Scan-Import prüfen</h2>
                        </div>
                    </div>

                    <section class="grid grid-3" style="margin-bottom:18px">
                        <article class="metric">
                            <strong><?= h($activeJobId !== '' ? $activeJobId : '-') ?></strong>
                            <h3>Job-ID</h3>
                            <p>Aktiver Review-Kontext.</p>
                        </article>
                        <article class="metric">
                            <strong><?= h($activeJobStatus !== '' ? $activeJobStatus : '-') ?></strong>
                            <h3>Status</h3>
                            <p>Aktueller Verarbeitungsstand des Jobs.</p>
                        </article>
                        <article class="metric">
                            <strong><?= h($activeJobFileName !== '' ? $activeJobFileName : '-') ?></strong>
                            <h3>Datei</h3>
                            <p>Quelle des Scan-Imports.</p>
                        </article>
                    </section>

                    <form method="post" action="/imports/">
                        <input type="hidden" name="action" value="save-scan-import-review">
                        <input type="hidden" name="job_id" value="<?= h($activeJobId) ?>">
                        <div class="table">
                            <table>
                                <thead>
                                    <tr>
                                        <th>Mitglied</th>
                                        <th>erkannt front</th>
                                        <th>erkannt back</th>
                                        <th>confidence</th>
                                        <th>korrigiert front</th>
                                        <th>korrigiert back</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($activeScanRows as $row): ?>
                                        <?php
                                            $rowId = (string) ($row['id'] ?? '');
                                            $rowMemberName = trim((string) ($row['member_name_raw'] ?? ''));
                                            if ($rowMemberName === '') {
                                                $rowMemberName = trim((string) ($row['display_name'] ?? $row['member_display_name'] ?? ''));
                                            }
                                            $rowFrontDetected = (string) ($row['front_strokes_detected'] ?? $row['detected_front'] ?? $row['front_detected'] ?? '0');
                                            $rowBackDetected = (string) ($row['back_strokes_detected'] ?? $row['detected_back'] ?? $row['back_detected'] ?? '0');
                                            $rowConfidence = $row['confidence'] ?? null;
                                            $rowCorrectedFront = (string) ($row['corrected_front_strokes'] ?? $row['corrected_front'] ?? $rowFrontDetected);
                                            $rowCorrectedBack = (string) ($row['corrected_back_strokes'] ?? $row['corrected_back'] ?? $rowBackDetected);
                                        ?>
                                        <tr>
                                            <td><?= h($rowMemberName !== '' ? $rowMemberName : 'Unbekannt') ?></td>
                                            <td><?= h($rowFrontDetected) ?></td>
                                            <td><?= h($rowBackDetected) ?></td>
                                            <td><?= $rowConfidence === null || $rowConfidence === '' ? '-' : h((string) $rowConfidence) ?></td>
                                            <td>
                                                <input
                                                    type="number"
                                                    name="corrected_front[<?= h($rowId) ?>]"
                                                    min="0"
                                                    step="1"
                                                    value="<?= h($rowCorrectedFront) ?>"
                                                >
                                            </td>
                                            <td>
                                                <input
                                                    type="number"
                                                    name="corrected_back[<?= h($rowId) ?>]"
                                                    min="0"
                                                    step="1"
                                                    value="<?= h($rowCorrectedBack) ?>"
                                                >
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                    <?php if ($activeScanRows === []): ?>
                                        <tr><td colspan="6">Für diesen Job liegen noch keine Review-Zeilen vor.</td></tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                        <div class="actions" style="margin-top:16px">
                            <button type="submit" class="button secondary">Review speichern</button>
                        </div>
                    </form>

                    <form method="post" action="/imports/" style="margin-top:12px">
                        <input type="hidden" name="action" value="approve-scan-import-review">
                        <input type="hidden" name="job_id" value="<?= h($activeJobId) ?>">
                        <div class="actions">
                            <button type="submit">Review freigeben</button>
                        </div>
                    </form>
                </section>
            <?php endif; ?>
        <?php elseif ($page === 'content'): ?>
            <section class="hero"><div class="eyebrow">Hinweise und FAQ</div><h1>Hinweise und FAQ</h1><p>Hinweise und häufige Fragen werden pro Tenant gepflegt und direkt an die Mitglieder ausgespielt.</p></section>
            <section class="grid grid-2">
                <article class="card">
                    <h2>Hinweise</h2>
                    <?php if ($canManageTenant): ?>
                        <form method="post" action="/content/" class="grid" style="margin-bottom:18px">
                            <input type="hidden" name="action" value="save-announcement">
                            <input type="hidden" name="announcement_id" value="<?= h((string) ($editingAnnouncement['id'] ?? '')) ?>">
                            <label>Titel<input name="title" value="<?= h((string) ($editingAnnouncement['title'] ?? '')) ?>" required></label>
                            <label>Sichtbar bis<input type="datetime-local" name="visible_until" value="<?= !empty($editingAnnouncement['visible_until']) ? h(date('Y-m-d\TH:i', strtotime((string) $editingAnnouncement['visible_until']))) : '' ?>"></label>
                            <label style="grid-column:1 / -1;">Hinweis<textarea name="message" required><?= h((string) ($editingAnnouncement['message'] ?? '')) ?></textarea></label>
                            <div class="actions"><button type="submit">Hinweis speichern</button><?php if ($editingAnnouncement !== null): ?><a class="button secondary" href="/content/">Neu anlegen</a><?php endif; ?></div>
                        </form>
                    <?php endif; ?>
                    <div class="stack"><?php if (($content['announcements'] ?? []) === []): ?><div class="metric"><p>Aktuell sind keine Hinweise vorhanden.</p></div><?php endif; ?><?php foreach (($content['announcements'] ?? []) as $entry): ?><div class="metric"><h3><?= h((string) $entry['title']) ?></h3><p><?= nl2br(h((string) $entry['message'])) ?></p><p class="muted">Sichtbar bis <?= dt((string) ($entry['visible_until'] ?? '')) ?></p><?php if ($canManageTenant): ?><div class="actions" style="margin-top:12px"><a class="button secondary" href="/content/?edit_announcement=<?= h((string) ($entry['id'] ?? '')) ?>">Bearbeiten</a><form method="post" action="/content/"><input type="hidden" name="action" value="archive-announcement"><input type="hidden" name="announcement_id" value="<?= h((string) ($entry['id'] ?? '')) ?>"><button type="submit" class="button secondary"><?= !empty($entry['is_active']) ? 'Archivieren' : 'Ausblenden' ?></button></form></div><?php endif; ?></div><?php endforeach; ?></div>
                </article>
                <article class="card">
                    <h2>FAQ</h2>
                    <?php if ($canManageTenant): ?>
                        <form method="post" action="/content/" class="grid" style="margin-bottom:18px">
                            <input type="hidden" name="action" value="save-faq">
                            <input type="hidden" name="faq_id" value="<?= h((string) ($editingFaq['id'] ?? '')) ?>">
                            <label>Frage<input name="question" value="<?= h((string) ($editingFaq['question'] ?? '')) ?>" required></label>
                            <label>Sortierung<input type="number" name="sort_order" min="0" step="1" value="<?= h((string) ($editingFaq['sort_order'] ?? '10')) ?>"></label>
                            <label style="grid-column:1 / -1;">Antwort<textarea name="answer" required><?= h((string) ($editingFaq['answer'] ?? '')) ?></textarea></label>
                            <div class="actions"><button type="submit">FAQ speichern</button><?php if ($editingFaq !== null): ?><a class="button secondary" href="/content/">Neu anlegen</a><?php endif; ?></div>
                        </form>
                    <?php endif; ?>
                    <div class="stack"><?php if (($content['faq'] ?? []) === []): ?><div class="metric"><p>Aktuell keine FAQ vorhanden.</p></div><?php endif; ?><?php foreach (($content['faq'] ?? []) as $entry): ?><div class="metric"><h3><?= h((string) $entry['question']) ?></h3><p><?= nl2br(h((string) $entry['answer'])) ?></p><?php if ($canManageTenant): ?><div class="actions" style="margin-top:12px"><a class="button secondary" href="/content/?edit_faq=<?= h((string) ($entry['id'] ?? '')) ?>">Bearbeiten</a><form method="post" action="/content/"><input type="hidden" name="action" value="archive-faq"><input type="hidden" name="faq_id" value="<?= h((string) ($entry['id'] ?? '')) ?>"><button type="submit" class="button secondary"><?= !empty($entry['is_active']) ? 'Archivieren' : 'Ausblenden' ?></button></form></div><?php endif; ?></div><?php endforeach; ?></div>
                </article>
            </section>
        <?php elseif ($page === 'notifications'): ?>
            <section class="hero"><div class="eyebrow">Benachrichtigungen</div><h1>Massenkommunikation pro Tenant</h1><p>Hinweise, Erinnerungen und Service-Meldungen werden als Entwurf, geplanter Versand oder direkte Auslieferung pro Tenant geführt.</p></section>
            <?php if (!$notificationStorageReady): ?><section class="alert alert-warning">Die Tabelle für Benachrichtigungen fehlt noch. Solange die Migration nicht gelaufen ist, werden Demo-Daten gezeigt und kein echter Versand gespeichert.</section><?php endif; ?>
            <section class="grid grid-4">
                <article class="metric"><strong><?= num((int) ($notificationSummary['total'] ?? 0)) ?></strong><h3>Kampagnen</h3><p>Gespeicherte Benachrichtigungen im Tenant.</p></article>
                <article class="metric"><strong><?= num((int) ($notificationSummary['draft'] ?? 0)) ?></strong><h3>Entwürfe</h3><p>Noch nicht ausgelöste Nachrichten.</p></article>
                <article class="metric"><strong><?= num((int) ($notificationSummary['scheduled'] ?? 0)) ?></strong><h3>Geplant</h3><p>Nachrichten mit Versandzeitpunkt.</p></article>
                <article class="metric"><strong><?= num((int) ($notificationSummary['recipient_count'] ?? 0)) ?></strong><h3>Empfänger</h3><p>Geplante oder erreichte Mitglieder.</p></article>
            </section>
            <section class="grid grid-2" style="margin-top:18px">
                <article class="card">
                    <h2><?= $editingNotification !== null ? 'Benachrichtigung bearbeiten' : 'Neue Benachrichtigung' ?></h2>
                    <form method="post" action="/notifications/" class="grid">
                        <input type="hidden" name="csrf" value="<?= h((string) ($_SESSION['notifications_csrf'] ?? '')) ?>">
                        <input type="hidden" name="notification_id" value="<?= h((string) ($notificationForm['notification_id'] ?? '')) ?>">
                        <label>Titel<input type="text" name="title" value="<?= h((string) ($notificationForm['title'] ?? '')) ?>" placeholder="Saldo-Erinnerung"></label>
                        <label>Kanal<select name="channel"><?php foreach ($notificationChannelOptions as $option): ?><option value="<?= h((string) $option['value']) ?>"<?= (($notificationForm['channel'] ?? 'email') === $option['value']) ? ' selected' : '' ?>><?= h((string) $option['label']) ?></option><?php endforeach; ?></select></label>
                        <label>Empfänger<select name="recipient_scope"><?php foreach ($notificationScopeOptions as $option): ?><option value="<?= h((string) $option['value']) ?>"<?= (($notificationForm['recipient_scope'] ?? 'all') === $option['value']) ? ' selected' : '' ?>><?= h((string) $option['label']) ?></option><?php endforeach; ?></select></label>
                        <label>Geplanter Versand<input type="datetime-local" name="scheduled_at" value="<?= h((string) ($notificationForm['scheduled_at'] ?? '')) ?>"></label>
                        <label style="grid-column:1 / -1;">Nachricht<textarea name="message" rows="8" placeholder="Freundliche Erinnerung oder Service-Hinweis"><?= h((string) ($notificationForm['message'] ?? '')) ?></textarea></label>
                        <div class="actions" style="grid-column:1 / -1;"><button type="submit" name="action" value="save-notification" class="button secondary">Entwurf speichern</button><button type="submit" name="action" value="send-notification">Jetzt senden</button></div>
                    </form>
                </article>
                <article class="card">
                    <h2>Empfängervorschau</h2>
                    <div class="actions" style="margin-bottom:18px"><?php foreach ($notificationScopeOptions as $option): ?><a class="button <?= (($notificationForm['recipient_scope'] ?? 'all') === $option['value']) ? '' : 'secondary' ?>" href="/notifications/?scope=<?= h((string) $option['value']) ?><?= !empty($notificationForm['notification_id']) ? '&edit=' . h((string) $notificationForm['notification_id']) : '' ?>"><?= h((string) $option['label']) ?></a><?php endforeach; ?></div>
                    <div class="stack"><?php foreach ($notificationPreview as $member): ?><div class="metric"><h3><?= h((string) ($member['display_name'] ?? 'Mitglied')) ?></h3><p><?= num($member['recent_strokes'] ?? 0) ?> Striche in 100 Tagen</p></div><?php endforeach; ?><?php if ($notificationPreview === []): ?><div class="metric"><h3>Keine aktiven Mitglieder</h3><p>Für die gewählte Zielgruppe wurden derzeit keine Empfänger gefunden.</p></div><?php endif; ?></div>
                </article>
            </section>
            <section class="grid grid-2" style="margin-top:18px">
                <article class="card"><h2>Kampagnen</h2><div class="table"><table><thead><tr><th>Titel</th><th>Kanal</th><th>Empfänger</th><th>Status</th><th>Aktion</th></tr></thead><tbody><?php foreach ($notificationMessages as $message): ?><tr><td><strong><?= h((string) ($message['title'] ?? '')) ?></strong><br><span class="muted"><?= h((string) ($message['message'] ?? '')) ?></span></td><td><?= h((string) ($message['channel_label'] ?? 'E-Mail')) ?></td><td><?= h((string) ($message['scope_label'] ?? 'Alle Mitglieder')) ?><br><span class="muted"><?= num((int) ($message['recipient_count'] ?? 0)) ?> Personen</span></td><td><?= badge((string) ($message['status_label'] ?? 'Entwurf'), (string) ($message['status_tone'] ?? 'neutral')) ?></td><td><a class="button secondary" href="/notifications/?edit=<?= h((string) ($message['id'] ?? '')) ?>">Bearbeiten</a></td></tr><?php endforeach; ?><?php if ($notificationMessages === []): ?><tr><td colspan="5">Noch keine Benachrichtigungen gespeichert.</td></tr><?php endif; ?></tbody></table></div></article>
                <article class="card"><h2>Versandprotokoll</h2><div class="table"><table><thead><tr><th>Kanal</th><th>Empfänger</th><th>Typ</th><th>Status</th></tr></thead><tbody><?php foreach ($notificationLogs as $log): ?><tr><td><?= h((string) ($log['channel_label'] ?? 'E-Mail')) ?></td><td><?= h((string) ($log['recipient'] ?? '-')) ?></td><td><?= h((string) ($log['template_key'] ?? '-')) ?></td><td><?= badge((string) ($log['status_label'] ?? 'Geplant'), (string) ($log['status_tone'] ?? 'neutral')) ?></td></tr><?php endforeach; ?><?php if ($notificationLogs === []): ?><tr><td colspan="4">Noch keine Versandprotokolle vorhanden.</td></tr><?php endif; ?></tbody></table></div></article>
            </section>
        <?php elseif ($page === 'profile'): ?>
            <section class="hero"><div class="eyebrow">Konto</div><h1>Persönliche Einstellungen</h1><p>Hier pflegst du deinen Anzeigenamen, dein Passwort und deinen persönlichen Anzeigemodus. Diese Einstellungen gelten nur für dich.</p></section>
            <section class="grid grid-2">
                <article class="card">
                    <h2>Profil</h2>
                    <form method="post" action="/profile/" class="grid">
                        <input type="hidden" name="action" value="save-profile">
                        <label>Anzeigename<input name="display_name" value="<?= h((string) ($auth['display_name'] ?? '')) ?>" required></label>
                        <label>Neues Passwort<input type="password" name="password" placeholder="Nur bei Änderung ausfüllen"></label>
                        <label style="grid-column:1 / -1;">Hinweis zu Einzahlungen<textarea readonly><?= h((string) ($tenantSettings['payment_hint'] ?? '')) ?></textarea></label>
                        <div class="actions"><button type="submit">Profil speichern</button></div>
                    </form>
                </article>
                <article class="card">
                    <h2>Anzeige</h2>
                    <div class="stack">
                        <div class="metric"><h3>Anzeigemodus</h3><p>Der Hell-/Dunkelmodus wird pro Benutzer gespeichert und ist bewusst vom Mandanten getrennt.</p></div>
                        <form method="post" action="/profile/" class="actions">
                            <input type="hidden" name="action" value="save-theme-mode">
                            <input type="hidden" name="theme_mode" value="<?= h($themeMode === 'dark' ? 'light' : 'dark') ?>">
                            <button type="submit"><?= h($themeMode === 'dark' ? 'Auf Hell umstellen' : 'Auf Dunkel umstellen') ?></button>
                        </form>
                        <p class="muted">Aktuell aktiv: <?= h($themeMode === 'dark' ? 'Dunkelmodus' : 'Hellmodus') ?></p>
                    </div>
                    <?php $paypalBaseUrl = trim((string) ($tenantSettings['paypal_me_url'] ?? '')); ?>
                    <?php if ($paypalBaseUrl !== ''): ?>
                        <div class="section-mini" style="margin-top:18px">
                            <h3 class="section-mini__title">PayPal-Einzahlungen</h3>
                            <p class="section-mini__copy">Direkte Schnelllinks für feste Beträge oder den aktuellen Ausgleich.</p>
                            <div class="actions">
                                <?php $balance = (float) ($memberSummary['balance'] ?? 0); ?>
                                <?php if ($balance < 0): ?>
                                    <a class="button secondary" target="_blank" href="<?= h(rtrim($paypalBaseUrl, '/') . '/' . number_format(abs($balance), 2, '.', '')) ?>"><?= h(number_format(abs($balance), 2, ',', '.')) ?> EUR ausgleichen</a>
                                <?php endif; ?>
                                <?php foreach ([5, 10, 15] as $quickAmount): ?>
                                    <a class="button secondary" target="_blank" href="<?= h(rtrim($paypalBaseUrl, '/') . '/' . number_format((float) $quickAmount, 2, '.', '')) ?>"><?= h(number_format((float) $quickAmount, 2, ',', '.')) ?> EUR</a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endif; ?>
                </article>
            </section>
            <?php if ($canManageTenant && $hasTenantSettingsFeature): ?>
                <section class="card" style="margin-top:18px">
                    <h2>Mandant</h2>
                    <p class="muted">Mandantenweite Einstellungen bleiben getrennt von deinem persönlichen Konto.</p>
                    <div class="actions" style="margin-top:14px"><a class="button secondary" href="/settings/">Zu den Mandanten-Einstellungen</a></div>
                </section>
            <?php endif; ?>
        <?php elseif ($page === 'settings'): ?>
            <section class="hero"><div class="eyebrow">Mandanten-Einstellungen</div><h1>Mandanten-Einstellungen</h1><p>Diese Einstellungen gelten nur für den aktuell geöffneten Mandanten und bleiben unabhängig von anderen Bereichen.</p></section>
            <section class="grid grid-2">
                <article class="card">
                    <h2>Einstellungen speichern</h2>
                    <form method="post" action="/settings/" class="grid">
                        <input type="hidden" name="action" value="save-settings">
                        <label>Standardpreis pro Strich<input type="number" name="default_unit_price" min="0.01" step="0.01" value="<?= h((string) ($tenantSettings['default_unit_price'] ?? '0.50')) ?>"></label>
                        <label>PDF-Listentitel<input name="pdf_list_title" value="<?= h((string) ($tenantSettings['pdf_list_title'] ?? 'Kaffeeliste')) ?>"></label>
                        <label>Beschriftung Vorderseite<input name="front_page_label" value="<?= h((string) ($tenantSettings['front_page_label'] ?? 'Vorderseite')) ?>"></label>
                        <label>Beschriftung Rückseite<input name="back_page_label" value="<?= h((string) ($tenantSettings['back_page_label'] ?? 'Rückseite')) ?>"></label>
                        <label>Zeilenhöhe PDF-Liste in mm<input type="number" name="pdf_row_height_mm" min="3.2" max="12" step="0.1" value="<?= h((string) ($tenantSettings['pdf_row_height_mm'] ?? '4.00')) ?>"></label>
                        <label>Standortbezeichnung<input name="location_label" value="<?= h((string) ($tenantSettings['location_label'] ?? '')) ?>"></label>
                        <label>Support-E-Mail<input type="email" name="support_email" value="<?= h((string) ($tenantSettings['support_email'] ?? '')) ?>"></label>
                        <label>PayPal-Link<input type="url" name="paypal_me_url" value="<?= h((string) ($tenantSettings['paypal_me_url'] ?? '')) ?>" placeholder="https://paypal.me/dein-tenant"></label>
                        <label>Primärfarbe<input type="color" name="brand_color" value="<?= h((string) ($tenantSettings['brand_color'] ?? '#005e3f')) ?>"></label>
                        <label>Dunkle Primärfarbe<input type="color" name="brand_strong_color" value="<?= h((string) ($tenantSettings['brand_strong_color'] ?? '#00452f')) ?>"></label>
                        <label>Akzentfarbe<input type="color" name="accent_color" value="<?= h((string) ($tenantSettings['accent_color'] ?? '#c18a00')) ?>"></label>
                        <label>Hintergrundfarbe<input type="color" name="background_color" value="<?= h((string) ($tenantSettings['background_color'] ?? '#f4efe4')) ?>"></label>
                        <label>Kartenfarbe<input type="color" name="card_color" value="<?= h((string) ($tenantSettings['card_color'] ?? '#fffdf8')) ?>"></label>
                        <label class="checkbox" style="grid-column:1 / -1;display:flex;flex-direction:row;align-items:center;font-weight:600;">
                            <input type="checkbox" name="allow_self_service_booking"<?= (($tenantSettings['allow_self_service_booking'] ?? '1') === '1') ? ' checked' : '' ?> style="width:auto">
                            <span>Selbstbedienungs-Buchungen im Mandanten aktiv lassen</span>
                        </label>
                        <label style="grid-column:1 / -1;">Hinweis zu Einzahlungen<textarea name="payment_hint"><?= h((string) ($tenantSettings['payment_hint'] ?? '')) ?></textarea></label>
                        <div class="actions"><button type="submit">Einstellungen speichern</button></div>
                    </form>
                </article>
                <article class="card">
                    <h2>Abgrenzung</h2>
                    <div class="stack">
                        <div class="metric"><h3>Mandantenweite Werte</h3><p>Hier werden nur Einstellungen gepflegt, die den gesamten Mandanten betreffen.</p></div>
                        <div class="metric"><h3>Persönliche Einstellungen</h3><p>Profil, Passwort und Anzeigemodus liegen bewusst im eigenen Bereich unter <a href="/profile/" style="text-decoration:underline;">Persönliche Einstellungen</a>.</p></div>
                    </div>
                </article>
            </section>
            <section class="card" style="margin-top:18px">
                <h2>Daten, Hilfe und Kommunikation</h2>
                <div class="grid grid-3">
                    <div class="metric"><h3>Daten</h3><p>Importe, Exporte und Reporting sind im Menü jetzt unter einem gemeinsamen Aufgabenraum gebündelt.</p></div>
                    <div class="metric"><h3>Hilfe & Inhalte</h3><p>Hinweise, FAQ, Support und Umfragen sind zusammen erreichbar, statt als verstreute Einzelpunkte aufzutauchen.</p></div>
                    <div class="metric"><h3>Verwaltung</h3><p>Rollen und Mandanten-Einstellungen bleiben zusammen im Verwaltungsbereich.</p></div>
                </div>
            </section>
            <section class="card" style="margin-top:18px">
                <h2>Aktuelle Lizenz</h2>
                <div class="stack">
                    <div class="metric"><h3><?= h((string) ($tenantLicense['plan_name'] ?? 'Free')) ?></h3><p>Freigeschalteter Lizenzplan für diesen Mandanten.</p></div>
                    <div class="metric"><h3>Mitgliederrahmen</h3><p><?= isset($tenantLicense['member_limit']) && (int) $tenantLicense['member_limit'] > 0 ? h((string) $tenantLicense['member_limit']) . ' aktive Mitglieder im Standardumfang.' : 'Individuell vereinbart.' ?></p></div>
                    <div class="metric"><h3>Freigeschaltete Kernfunktionen</h3><ul class="list"><?php foreach (['tenant_settings' => 'Mandanten-Einstellungen', 'pdf_export' => 'PDF-Listen', 'paper_strike_entry' => 'Papierlisten-Erfassung'] as $featureKey => $featureLabel): ?><?php if (!empty($tenantLicense['features'][$featureKey])): ?><li><?= h($featureLabel) ?></li><?php endif; ?><?php endforeach; ?></ul></div>
                </div>
            </section>
            <section class="card" style="margin-top:18px">
                <h2>Farben im Tenant</h2>
                <div class="grid grid-4">
                    <?php foreach ([
                        'Primärfarbe' => $tenantSettings['brand_color'] ?? '#005e3f',
                        'Dunkle Primärfarbe' => $tenantSettings['brand_strong_color'] ?? '#00452f',
                        'Akzentfarbe' => $tenantSettings['accent_color'] ?? '#c18a00',
                        'Hintergrund' => $tenantSettings['background_color'] ?? '#f4efe4',
                    ] as $label => $color): ?>
                        <div class="metric">
                            <div style="width:100%;height:42px;border-radius:12px;border:1px solid var(--line);background:<?= h((string) $color) ?>"></div>
                            <h3 style="margin-top:12px"><?= h($label) ?></h3>
                            <p class="muted"><?= h((string) $color) ?></p>
                        </div>
                    <?php endforeach; ?>
                </div>
            </section>
        <?php elseif ($page === 'year-end'): ?>
            <section class="hero">
                <div class="eyebrow">Sonderprozess</div>
                <h1>Jahresabschluss und Bonus</h1>
                <p>Hier berechnest du die Jahresverteilung auf Basis der im Jahr gebuchten Striche und verbuchst sie als nachvollziehbare Auszahlungen.</p>
            </section>

            <?php if (!($pdo instanceof PDO) || !scripts_table_exists($pdo, 'year_end_runs')): ?>
                <section class="alert alert-warning">Die Migration für den Jahresabschluss fehlt noch. Bitte die Datenbankmigrationen ausführen.</section>
            <?php endif; ?>

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

            <section class="grid grid-2">
                <article class="card">
                    <h2>Vorschau berechnen</h2>
                    <form method="post" action="/year-end/" class="grid">
                        <input type="hidden" name="action" value="preview-year-end">
                        <label>Jahr<input type="number" name="year" min="2000" max="2100" step="1" value="<?= h((string) $yearEndForm['year']) ?>"></label>
                        <label>Bonusmodus<select name="bonus_mode"><option value="proportional"<?= ($yearEndForm['bonus_mode'] ?? 'proportional') === 'proportional' ? ' selected' : '' ?>>Proportional nach Strichen</option><option value="flat"<?= ($yearEndForm['bonus_mode'] ?? '') === 'flat' ? ' selected' : '' ?>>Fix pro Mitglied</option></select></label>
                        <p class="muted" style="grid-column:1 / -1;">Im proportionalen Modus wird der Bonus-Topf nach Jahresstrichen verteilt. Im fixen Modus erhält jedes aktive Mitglied denselben Betrag.</p>
                        <label>Bonus-Topf<input type="number" name="bonus_pool_amount" min="0" step="0.01" value="<?= h((string) $yearEndForm['bonus_pool_amount']) ?>"></label>
                        <label>Fixer Bonus pro Mitglied<input type="number" name="bonus_per_member_amount" min="0" step="0.01" value="<?= h((string) $yearEndForm['bonus_per_member_amount']) ?>"></label>
                        <label>Buchungszeit<input type="datetime-local" name="booked_at" value="<?= h((string) $yearEndForm['booked_at']) ?>"></label>
                        <label style="grid-column:1 / -1;">Hinweis<textarea name="notes" placeholder="Optionaler Hinweis für die Jahresabschlussbuchung"><?= h((string) $yearEndForm['notes']) ?></textarea></label>
                        <div class="actions" style="grid-column:1 / -1;"><button type="submit">Vorschau berechnen</button></div>
                    </form>
                </article>
                <article class="card">
                    <h2>Was die Vorschau zeigt</h2>
                    <div class="grid grid-2">
                        <article class="metric">
                            <strong><?= num($yearEndPreview['total_strokes'] ?? 0) ?></strong>
                            <h3>Jahresstriche</h3>
                            <p>Aktive Striche im ausgewählten Jahr.</p>
                        </article>
                        <article class="metric">
                            <strong><?= num((int) ($yearEndPreview['member_count'] ?? 0)) ?></strong>
                            <h3>Aktive Mitglieder</h3>
                            <p>Mitglieder, die in die Berechnung eingehen.</p>
                        </article>
                        <article class="metric">
                            <strong><?= money($yearEndPreview['total_amount'] ?? 0) ?></strong>
                            <h3>Verteilte Summe</h3>
                            <p>Effektiv berechnete Bonusgesamtsumme.</p>
                        </article>
                        <article class="metric">
                            <strong><?= num((int) ($yearEndPreview['recipient_count'] ?? 0)) ?></strong>
                            <h3>Empfänger</h3>
                            <p>Mitglieder mit einer Auszahlung größer 0.</p>
                        </article>
                    </div>
                    <?php if ($yearEndExistingRun !== null): ?>
                        <div class="alert alert-info" style="margin-top:16px;">Für dieses Jahr existiert bereits ein verbuchter Jahresabschluss vom <?= dt((string) ($yearEndExistingRun['executed_at'] ?? '')) ?>.</div>
                    <?php endif; ?>
                </article>
            </section>

            <?php if (is_array($yearEndPreview)): ?>
                <section class="card" style="margin-top:18px">
                    <div class="bulk-toolbar">
                        <div>
                            <div class="eyebrow">Vorschau</div>
                            <h2 style="margin:0">Berechnete Verteilung für <?= h((string) ($yearEndPreview['year'] ?? '')) ?></h2>
                            <div class="bulk-summary">
                                <span class="bulk-chip"><?= h((string) ($yearEndPreview['mode'] === 'flat' ? 'Fix pro Mitglied' : 'Proportional nach Strichen')) ?></span>
                                <span><?= num((int) ($yearEndPreview['member_count'] ?? 0)) ?> aktive Mitglieder</span>
                            </div>
                        </div>
                        <?php if ($yearEndExistingRun === null): ?>
                            <form method="post" action="/year-end/">
                                <input type="hidden" name="action" value="execute-year-end">
                                <input type="hidden" name="year" value="<?= h((string) ($yearEndPreview['year'] ?? $yearEndForm['year'])) ?>">
                                <input type="hidden" name="bonus_mode" value="<?= h((string) ($yearEndPreview['mode'] ?? 'proportional')) ?>">
                                <input type="hidden" name="bonus_pool_amount" value="<?= h((string) ($yearEndPreview['bonus_pool_amount'] ?? '0.00')) ?>">
                                <input type="hidden" name="bonus_per_member_amount" value="<?= h((string) ($yearEndPreview['bonus_per_member_amount'] ?? '0.00')) ?>">
                                <input type="hidden" name="booked_at" value="<?= h((string) ($yearEndPreview['booked_at'] ?? '')) ?>">
                                <input type="hidden" name="notes" value="<?= h((string) ($yearEndPreview['notes'] ?? '')) ?>">
                                <button type="submit">Jahresabschluss verbuchen</button>
                            </form>
                        <?php else: ?>
                            <div class="alert alert-info" style="margin-top:8px;">Für dieses Jahr wurde bereits ein Lauf abgeschlossen. Neue Buchungen werden hier deshalb nicht mehr angeboten.</div>
                        <?php endif; ?>
                    </div>
                    <div class="table" style="margin-top:16px">
                        <table>
                            <thead><tr><th>Mitglied</th><th>Jahresstriche</th><th>Anteil</th><th>Bonus</th><th>Saldo vorher</th><th>Saldo nachher</th></tr></thead>
                            <tbody>
                                <?php foreach (($yearEndPreview['rows'] ?? []) as $row): ?>
                                    <tr>
                                        <td><strong><?= h((string) ($row['display_name'] ?? '')) ?></strong><br><span class="muted"><?= h((string) ($row['email'] ?? '')) ?></span></td>
                                        <td><?= num($row['year_strokes'] ?? 0) ?></td>
                                        <td><?= ($row['share_percent'] ?? null) !== null ? h((string) $row['share_percent']) . ' %' : '—' ?></td>
                                        <td><?= money($row['bonus_amount'] ?? 0) ?></td>
                                        <td><?= money($row['current_balance'] ?? 0) ?></td>
                                        <td><?= money($row['projected_balance'] ?? 0) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </section>
            <?php endif; ?>

            <section class="card" style="margin-top:18px">
                <div class="bulk-toolbar">
                    <div>
                        <div class="eyebrow">Verlauf</div>
                        <h2 style="margin:0">Letzte Jahresabschlüsse</h2>
                    </div>
                    <span class="bulk-chip"><?= num(count($yearEndRuns)) ?> Läufe</span>
                </div>
                <div class="table" style="margin-top:16px">
                    <table>
                        <thead><tr><th>Jahr</th><th>Modus</th><th>Summe</th><th>Striche</th><th>Empfänger</th><th>Ausgeführt</th><th>Von</th></tr></thead>
                        <tbody>
                            <?php foreach ($yearEndRuns as $run): ?>
                                <tr>
                                    <td><strong><?= h((string) ($run['year'] ?? '')) ?></strong></td>
                                    <td><?= h((string) (($run['bonus_mode'] ?? '') === 'flat' ? 'Fix pro Mitglied' : 'Proportional')) ?></td>
                                    <td><?= money($run['total_amount'] ?? 0) ?></td>
                                    <td><?= num($run['total_strokes'] ?? 0) ?></td>
                                    <td><?= num($run['recipient_count'] ?? 0) ?></td>
                                    <td><?= dt((string) ($run['executed_at'] ?? $run['created_at'] ?? '')) ?></td>
                                    <td><?= h((string) ($run['created_by_name'] ?? '')) ?></td>
                                </tr>
                            <?php endforeach; ?>
                            <?php if ($yearEndRuns === []): ?>
                                <tr><td colspan="7">Noch kein Jahresabschluss verbucht.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </section>
        <?php elseif ($page === 'exports'): ?>
            <?php if (isset($_GET['view']) && $_GET['view'] === 'print' && is_array($activePrintList)): ?>
                <section class="hero"><div class="eyebrow">PDF-Vorschau</div><h1><?= h((string) $activePrintList['title']) ?></h1><p><?= (($printListGroups['mode'] ?? 'single') === 'single') ? 'Diese Liste wird als einzelne PDF-Seite erzeugt.' : 'Diese Liste wird als Vorder- und Rückseite erzeugt.' ?> Die Zeilenhöhe liegt aktuell bei <?= h((string) ($printListGroups['row_height_mm'] ?? ($tenantSettings['pdf_row_height_mm'] ?? '4.00'))) ?> mm.</p><div class="actions" style="margin-top:18px"><a class="button secondary" href="/exports/?list=<?= h((string) $activePrintList['id']) ?>">Zurück</a><a class="button" href="/exports/?download=print-list-pdf&list=<?= h((string) $activePrintList['id']) ?>">PDF herunterladen</a></div></section>
                <section class="card">
                    <div class="grid<?= (($printListGroups['mode'] ?? 'single') === 'single') ? '' : ' grid-2' ?>">
                        <article>
                            <h2><?= (($printListGroups['mode'] ?? 'single') === 'single') ? h((string) $activePrintList['title']) : h((string) ($tenantSettings['front_page_label'] ?? 'Vorderseite')) . ' / Vieltrinker' ?></h2>
                            <div class="table"><table><thead><tr><th>#</th><th>Person</th><th>Striche</th></tr></thead><tbody><?php foreach (($printListGroups['front'] ?? []) as $item): ?><tr><td><?= h((string) ($item['list_position'] ?? '')) ?></td><td><?= h((string) $item['member_name']) ?></td><td>________</td></tr><?php endforeach; ?></tbody></table></div>
                        </article>
                        <?php if (($printListGroups['mode'] ?? 'single') !== 'single'): ?>
                            <article>
                                <h2><?= h((string) ($tenantSettings['back_page_label'] ?? 'Rückseite')) ?> / Wenigtrinker</h2>
                                <div class="table"><table><thead><tr><th>#</th><th>Person</th><th>Striche</th></tr></thead><tbody><?php foreach (($printListGroups['back'] ?? []) as $item): ?><tr><td><?= h((string) ($item['list_position'] ?? '')) ?></td><td><?= h((string) $item['member_name']) ?></td><td>________</td></tr><?php endforeach; ?></tbody></table></div>
                            </article>
                        <?php endif; ?>
                    </div>
                </section>
            <?php else: ?>
                <section class="hero"><div class="eyebrow">Exporte und Drucklisten</div><h1>Drucklisten</h1><p>Hier erzeugst du druckfertige Listen, speicherst sie als PDF und buchst anschließend die Striche aus Vorder- und Rückseite zurück ins System.</p></section>
                <section class="grid grid-2">
                    <?php if ($hasPdfExportFeature): ?>
                    <article class="card">
                        <h2>Neue Druckliste erzeugen</h2>
                        <form method="post" action="/exports/" class="grid">
                            <input type="hidden" name="action" value="create-print-list">
                            <label>Titel<input name="title" value="<?= h((string) ($tenantSettings['pdf_list_title'] ?? 'Kaffeeliste')) ?>"></label>
                            <label>Preis pro Strich<input type="number" name="unit_price" min="0.01" step="0.01" value="<?= h((string) ($tenantSettings['default_unit_price'] ?? '0.50')) ?>"></label>
                            <label style="grid-column:1 / -1;">Notiz<textarea name="notes"></textarea></label>
                            <div class="actions"><button type="submit">Druckliste erzeugen</button></div>
                        </form>
                    </article>
                    <?php endif; ?>
                    <article class="card">
                        <h2><?= $hasBasicExportsFeature ? 'Basis-Exporte' : 'So funktioniert der PDF-Prozess' ?></h2>
                        <?php if ($hasBasicExportsFeature): ?>
                            <p>Für den laufenden Betrieb kannst du Mitglieder und Buchungen direkt als CSV exportieren.</p>
                            <div class="actions" style="margin-top:18px">
                                <a class="button secondary" href="/exports/?download=members-csv">Mitglieder als CSV</a>
                                <a class="button secondary" href="/exports/?download=ledger-csv">Ledger als CSV</a>
                            </div>
                        <?php else: ?>
                        <ul class="list">
                            <li>Druckliste erzeugen und direkt als saubere PDF-Datei herunterladen.</li>
                            <li>Nur bei vielen Mitgliedern wird automatisch eine Vorder- und Rückseite erzeugt.</li>
                            <li>Die Striche später gesammelt in derselben Liste nachtragen und verbuchen.</li>
                        </ul>
                        <?php endif; ?>
                    </article>
                    <?php if ($hasBasicExportsFeature): ?>
                    <article class="card">
                        <h2>Mitgliederauswertung exportieren</h2>
                        <p>Die Detailauswertung eines einzelnen Mitglieds lässt sich direkt als CSV herunterladen.</p>
                        <form method="get" action="/exports/" class="grid" style="margin-top:18px">
                            <input type="hidden" name="download" value="member-report-csv">
                            <label>Mitglied<select name="member"><?php foreach ($members as $member): ?><option value="<?= h((string) ($member['id'] ?? '')) ?>"><?= h((string) ($member['display_name'] ?? '')) ?></option><?php endforeach; ?></select></label>
                            <div class="actions"><button type="submit">Detail-CSV herunterladen</button></div>
                        </form>
                    </article>
                    <?php endif; ?>
                </section>
                <?php if ($hasPdfExportFeature || $hasPaperStrikeEntryFeature): ?>
                <section class="card" style="margin-top:18px">
                    <h2>Vorhandene Drucklisten</h2>
                    <div class="table">
                        <table>
                            <thead><tr><th>Titel</th><th>Preis</th><th>Status</th><th>Erstellt</th><th>Aktionen</th></tr></thead>
                                <tbody><?php foreach ($printLists as $list): ?><tr><td><strong><?= h((string) $list['title']) ?></strong></td><td><?= money($list['unit_price'] ?? 0) ?></td><td><?= ((string) ($list['status'] ?? 'draft')) === 'imported' ? badge('Verbucht', 'success') : badge('Offen') ?></td><td><?= dt((string) ($list['created_at'] ?? '')) ?></td><td><div class="actions"><a class="button secondary" href="/exports/?list=<?= h((string) $list['id']) ?>">Bearbeiten</a><a class="button secondary" href="/exports/?download=print-list-pdf&list=<?= h((string) $list['id']) ?>">PDF herunterladen</a><a class="button secondary" href="/exports/?list=<?= h((string) $list['id']) ?>&view=print">Vorschau</a></div></td></tr><?php endforeach; ?></tbody>
                        </table>
                    </div>
                </section>
                <?php endif; ?>
                <?php if ($hasPaperStrikeEntryFeature && is_array($activePrintList)): ?>
                    <section class="card" style="margin-top:18px">
                        <h2>Druckliste nachtragen</h2>
                        <form method="post" action="/exports/">
                            <input type="hidden" name="action" value="apply-print-list">
                            <input type="hidden" name="print_list_id" value="<?= h((string) $activePrintList['id']) ?>">
                            <div class="grid grid-2">
                                <label>Buchungszeit<input type="datetime-local" name="booked_at" value="<?= date('Y-m-d\TH:i') ?>"></label>
                                <div class="metric"><h3>Status</h3><p><?= h((string) ($activePrintList['status'] ?? 'draft')) ?></p></div>
                            </div>
                            <div class="grid grid-2" style="margin-top:18px">
                                <article>
                                    <h3><?= (($printListGroups['mode'] ?? 'single') === 'single') ? 'Druckliste' : h((string) ($tenantSettings['front_page_label'] ?? 'Vorderseite')) . ' / Vieltrinker' ?></h3>
                                    <div class="table">
                                        <table>
                                            <thead><tr><th>Person</th><th>Striche</th><th>Bereits erfasst</th></tr></thead>
                                            <tbody><?php foreach (($printListGroups['front'] ?? []) as $item): ?><tr><td><?= h((string) $item['member_name']) ?></td><td><input type="number" min="0" step="1" name="strokes[<?= h((string) $item['id']) ?>][front]" value="<?= h((string) (($printListItemMap[(string) $item['id']]['front_strokes'] ?? 0))) ?>"></td><td><?= h((string) (($printListItemMap[(string) $item['id']]['front_strokes'] ?? 0))) ?></td></tr><?php endforeach; ?></tbody>
                                        </table>
                                    </div>
                                </article>
                                <?php if (($printListGroups['back'] ?? []) !== []): ?>
                                    <article>
                                        <h3><?= h((string) ($tenantSettings['back_page_label'] ?? 'Rückseite')) ?> / Wenigtrinker</h3>
                                        <div class="table">
                                            <table>
                                                <thead><tr><th>Person</th><th>Striche</th><th>Bereits erfasst</th></tr></thead>
                                                <tbody><?php foreach (($printListGroups['back'] ?? []) as $item): ?><tr><td><?= h((string) $item['member_name']) ?></td><td><input type="number" min="0" step="1" name="strokes[<?= h((string) $item['id']) ?>][back]" value="<?= h((string) (($printListItemMap[(string) $item['id']]['back_strokes'] ?? 0))) ?>"></td><td><?= h((string) (($printListItemMap[(string) $item['id']]['back_strokes'] ?? 0))) ?></td></tr><?php endforeach; ?></tbody>
                                            </table>
                                        </div>
                                    </article>
                                <?php endif; ?>
                            </div>
                            <?php if (false): ?><div class="table" style="display:none;margin-top:18px">
                                <table>
                                    <thead><tr><th>#</th><th>Person</th><th>Vorderseite</th><th>Rückseite</th><th>Gesamt</th></tr></thead>
                                    <tbody><?php foreach (($activePrintList['items'] ?? []) as $item): ?><tr><td><?= h((string) $item['list_position']) ?></td><td><?= h((string) $item['member_name']) ?></td><td><input type="number" min="0" step="1" name="strokes[<?= h((string) $item['id']) ?>][front]" value="<?= h((string) ($item['front_strokes'] ?? 0)) ?>"></td><td><input type="number" min="0" step="1" name="strokes[<?= h((string) $item['id']) ?>][back]" value="<?= h((string) ($item['back_strokes'] ?? 0)) ?>"></td><td><?= h((string) ($item['total_strokes'] ?? 0)) ?></td></tr><?php endforeach; ?></tbody>
                                </table>
                            </div><?php endif; ?>
                            <div class="actions" style="margin-top:18px"><button type="submit">Striche verbuchen</button><a class="button secondary" href="/exports/?list=<?= h((string) $activePrintList['id']) ?>&view=print">Zur PDF-Ansicht</a></div>
                        </form>
                    </section>
                <?php endif; ?>
            <?php endif; ?>
        <?php else: ?>
            <section class="alert alert-warning">Die angeforderte Seite konnte nicht gefunden werden.</section>
        <?php endif; ?>

        <p class="footer">Die Kaffeeliste</p>
        </div>
        <?php if ($auth !== null && $mobileBottomNavItems !== []): ?>
            <nav class="mobile-bottom-nav" aria-label="Mobile Kernnavigation">
                <?php foreach ($mobileBottomNavItems as $item): ?>
                    <a href="<?= h((string) ($item['href'] ?? '/')) ?>" class="mobile-bottom-nav__link <?= $page === (string) ($item['key'] ?? '') ? 'active' : '' ?>" <?= $page === (string) ($item['key'] ?? '') ? 'aria-current="page"' : '' ?>>
                        <span class="mobile-bottom-nav__icon"><?= match ((string) ($item['key'] ?? '')) {
                            'dashboard' => 'U',
                            'ledger' => 'B',
                            'payments' => 'Z',
                            default => '•',
                        } ?></span>
                        <span class="mobile-bottom-nav__label"><?= h((string) ($item['label'] ?? 'Link')) ?></span>
                    </a>
                <?php endforeach; ?>
                <button type="button" class="mobile-bottom-nav__toggle" data-mobile-drawer-open>
                    <span class="mobile-bottom-nav__icon">+</span>
                    <span class="mobile-bottom-nav__label">Menü</span>
                </button>
            </nav>
        <?php endif; ?>
    </main>
    <?php endif; ?>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const details = document.querySelectorAll('.site-more');
            const drawer = document.querySelector('[data-mobile-drawer]');
            const drawerOpeners = document.querySelectorAll('[data-mobile-drawer-open]');
            const drawerClosers = document.querySelectorAll('[data-mobile-drawer-close]');

            function closeOthers(current) {
                details.forEach(function (other) {
                    if (other !== current) {
                        other.open = false;
                    }
                });
            }

            details.forEach(function (detail) {
                const summary = detail.querySelector('summary');
                if (summary) {
                    summary.addEventListener('click', function () {
                        if (!detail.open) {
                            closeOthers(detail);
                        }
                    });
                }

                detail.addEventListener('toggle', function () {
                    if (detail.open) {
                        closeOthers(detail);
                    }
                });
            });

            document.querySelectorAll('.site-more__panel a, .mobile-drawer__link').forEach(function (link) {
                link.addEventListener('click', function () {
                    details.forEach(function (detail) {
                        detail.open = false;
                    });
                    if (drawer) {
                        drawer.classList.remove('is-open');
                        document.body.classList.remove('mobile-drawer-open');
                    }
                });
            });

            if (drawer) {
                drawerOpeners.forEach(function (button) {
                    button.addEventListener('click', function () {
                        drawer.classList.add('is-open');
                        document.body.classList.add('mobile-drawer-open');
                    });
                });

                drawerClosers.forEach(function (button) {
                    button.addEventListener('click', function () {
                        drawer.classList.remove('is-open');
                        document.body.classList.remove('mobile-drawer-open');
                    });
                });
            }
        });
    </script>
</body>
</html>
