<?php

session_start();
require_once __DIR__ . '/../../includes/init.php';
require_once __DIR__ . '/../../auth/AuthController.php';
require_once __DIR__ . '/../../includes/core/SodiumCrypto.php';

$auth = new AuthController();
if (!$auth->isLoggedIn()) {
    header('Location: /admin/login.php');
    exit;
}

$config = require __DIR__ . '/../../includes/config.php';
$cryptoKey = (string) ($config['security']['doi_key'] ?? '');
$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
$token = trim((string) ($_GET['token'] ?? ''));

if ($id <= 0 && $token === '') {
    exit('Parameter &quot;id&quot; oder &quot;token&quot; erforderlich.');
}

try {
    $db = Database::getInstance();
    if ($id > 0) {
        $stmt = $db->prepare('
            SELECT o.*, r.email, r.vorname, r.nachname, l.name AS list_name
            FROM recipient_list_optin o
            LEFT JOIN recipients r ON r.id = o.recipient_id
            LEFT JOIN lists l ON l.id = o.list_id
            WHERE o.recipient_id = ?
            LIMIT 1
        ');
        $stmt->execute([$id]);
    } else {
        $stmt = $db->prepare('
            SELECT o.*, r.email, r.vorname, r.nachname, l.name AS list_name
            FROM recipient_list_optin o
            LEFT JOIN recipients r ON r.id = o.recipient_id
            LEFT JOIN lists l ON l.id = o.list_id
            WHERE o.doi_token = ?
            LIMIT 1
        ');
        $stmt->execute([$token]);
    }
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    ErrorLogger::logSqlSuccess('DOI-Detail geladen | table: recipient_list_optin | context: ' . json_encode([
        'recipient_id' => $id > 0 ? $id : null,
        'token_lookup' => $token !== '',
        'found' => (bool) $row,
    ], JSON_UNESCAPED_UNICODE));

    if (!$row) {
        exit('Kein DOI-Datensatz gefunden.');
    }
} catch (Throwable $e) {
    ErrorLogger::logSqlError('DOI-Detail konnte nicht geladen werden | table: recipient_list_optin | error: ' . $e->getMessage());
    exit('Fehler beim Laden des DOI-Datensatzes.');
}

foreach ([
    ['enc' => 'doi_ip_signup_enc', 'plain' => 'doi_ip_signup_plain'],
    ['enc' => 'doi_ip_confirm_enc', 'plain' => 'doi_ip_confirm_plain'],
] as $fieldMap) {
    $encryptedKey = $fieldMap['enc'];
    $plainKey = $fieldMap['plain'];

    if (!empty($row[$encryptedKey])) {
        try {
            $row[$plainKey] = SodiumCrypto::decrypt($row[$encryptedKey], $cryptoKey);
        } catch (Throwable $e) {
            $row[$plainKey] = 'Entschluesselung fehlgeschlagen';
            ErrorLogger::logSqlError('DOI-IP konnte nicht entschluesselt werden | table: recipient_list_optin | error: ' . $e->getMessage());
        }
    } else {
        $row[$plainKey] = '-';
    }
}

$mailHtml = null;
if (!empty($row['doi_mail_body_b64'])) {
    $decoded = base64_decode((string) $row['doi_mail_body_b64'], true);
    if ($decoded !== false) {
        $mailHtml = $decoded;
    }
}

$fullName = trim(((string) ($row['vorname'] ?? '')) . ' ' . ((string) ($row['nachname'] ?? '')));
$pageHelp = renderPageHelp([
    'sections' => [
        [
            'heading' => 'Was zeigt diese Seite?',
            'items' => [
                'Hier siehst du den einzelnen DOI-Nachweis mit Token, Zeitpunkten und technischen Begleitdaten.',
                'Gespeicherte IP-Daten werden hier nur zur Einsicht entschluesselt dargestellt.',
            ],
        ],
    ],
]);
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>DOI-Detail</title>
    <link rel="stylesheet" href="/assets/bootstrap/dist/css/bootstrap.min.css">
    <style>
        body { padding: 2rem; background: #f5f7fb; }
        .doi-detail-shell { max-width: 980px; margin: 0 auto; }
        .doi-detail-card { border: 1px solid #dbe4ee; border-radius: 1rem; overflow: hidden; background: #fff; box-shadow: 0 12px 30px rgba(15, 23, 42, 0.06); }
        .doi-detail-card .table { margin-bottom: 0; }
        .doi-mail-preview { max-height: 420px; overflow: auto; background: #f8f9fa; padding: 1rem; white-space: pre-wrap; border-radius: 0.75rem; border: 1px solid #dbe4ee; }
    </style>
</head>
<body>
    <div class="doi-detail-shell">
        <h1 class="h3 mb-3">DOI-Detail</h1>
        <?= $pageHelp ?>

        <div class="doi-detail-card mb-4">
            <table class="table table-sm table-bordered align-middle">
                <tbody>
                    <tr><th scope="row">E-Mail</th><td><?= htmlspecialchars((string) ($row['email'] ?? '-'), ENT_QUOTES, 'UTF-8') ?></td></tr>
                    <tr><th scope="row">Name</th><td><?= htmlspecialchars($fullName !== '' ? $fullName : '-', ENT_QUOTES, 'UTF-8') ?></td></tr>
                    <tr><th scope="row">Liste</th><td><?= htmlspecialchars((string) ($row['list_name'] ?? '-'), ENT_QUOTES, 'UTF-8') ?></td></tr>
                    <tr><th scope="row">Token</th><td><code><?= htmlspecialchars((string) ($row['doi_token'] ?? ''), ENT_QUOTES, 'UTF-8') ?></code></td></tr>
                    <tr><th scope="row">Signup-IP</th><td><?= htmlspecialchars((string) ($row['doi_ip_signup_plain'] ?? '-'), ENT_QUOTES, 'UTF-8') ?></td></tr>
                    <tr><th scope="row">Signup-Zeit</th><td><?= htmlspecialchars((string) ($row['doi_requested_at'] ?? '-'), ENT_QUOTES, 'UTF-8') ?></td></tr>
                    <tr><th scope="row">Klick-IP</th><td><?= htmlspecialchars((string) ($row['doi_ip_confirm_plain'] ?? '-'), ENT_QUOTES, 'UTF-8') ?></td></tr>
                    <tr><th scope="row">Klick-Zeit</th><td><?= htmlspecialchars((string) ($row['doi_confirmed_at'] ?? '-'), ENT_QUOTES, 'UTF-8') ?></td></tr>
                    <tr><th scope="row">DOI-Mail versendet</th><td><?= htmlspecialchars((string) ($row['doi_mail_sent_at'] ?? '-'), ENT_QUOTES, 'UTF-8') ?></td></tr>
                    <tr><th scope="row">Mail-Hash</th><td><code><?= htmlspecialchars((string) ($row['doi_mail_hash'] ?? '-'), ENT_QUOTES, 'UTF-8') ?></code></td></tr>
                    <tr><th scope="row">Policy-Hash</th><td><code><?= htmlspecialchars((string) ($row['doi_policy_hash'] ?? '-'), ENT_QUOTES, 'UTF-8') ?></code></td></tr>
                    <tr><th scope="row">User-Agent</th><td><small><?= htmlspecialchars((string) ($row['doi_user_agent'] ?? '-'), ENT_QUOTES, 'UTF-8') ?></small></td></tr>
                    <tr><th scope="row">Referrer</th><td><small><?= htmlspecialchars((string) ($row['doi_referrer'] ?? '-'), ENT_QUOTES, 'UTF-8') ?></small></td></tr>
                    <tr>
                        <th scope="row">Status</th>
                        <td>
                            <?php if (!empty($row['doi_confirmed'])): ?>
                                <span class="badge text-bg-success">Best&auml;tigt</span>
                            <?php else: ?>
                                <span class="badge text-bg-warning">Offen</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div class="mb-4">
            <h2 class="h5">Gesendeter DOI-Mail-Body</h2>
            <?php if ($mailHtml !== null): ?>
                <div class="doi-mail-preview"><code><?= htmlspecialchars($mailHtml, ENT_QUOTES, 'UTF-8') ?></code></div>
            <?php else: ?>
                <p class="text-muted mb-0"><em>Kein DOI-Mail-Body gespeichert.</em></p>
            <?php endif; ?>
        </div>

        <div class="d-flex gap-2">
            <a href="optin_list.php" class="btn btn-secondary">Zur&uuml;ck zur DOI-Suche</a>
            <a href="javascript:history.back()" class="btn btn-outline-secondary">Zur&uuml;ck</a>
        </div>
    </div>
</body>
</html>
