<?php

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

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

$db = Database::getInstance();
$search = trim((string) ($_GET['search'] ?? ''));
$statusFilter = trim((string) ($_GET['status'] ?? 'all'));
$rows = [];
$error = '';

$where = [];
$params = [];

if ($search !== '') {
    $where[] = '(r.email LIKE :search OR o.doi_token LIKE :search)';
    $params[':search'] = '%' . $search . '%';
}

if ($statusFilter === 'confirmed') {
    $where[] = 'o.doi_confirmed = 1';
} elseif ($statusFilter === 'open') {
    $where[] = 'o.doi_confirmed = 0';
}

$whereSql = $where !== [] ? 'WHERE ' . implode(' AND ', $where) : '';

try {
    $sql = "
        SELECT
            o.recipient_id,
            o.list_id,
            o.doi_token,
            o.doi_confirmed,
            o.doi_requested_at,
            o.doi_confirmed_at,
            r.email,
            r.vorname,
            r.nachname,
            l.name AS list_name
        FROM recipient_list_optin o
        INNER JOIN recipients r ON r.id = o.recipient_id
        LEFT JOIN lists l ON l.id = o.list_id
        $whereSql
        ORDER BY COALESCE(o.doi_requested_at, o.doi_created_at) DESC
        LIMIT 200
    ";
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    ErrorLogger::logSqlSuccess('DOI-Nachweise geladen | table: recipient_list_optin | context: ' . json_encode([
        'search' => $search,
        'status' => $statusFilter,
        'rows' => count($rows),
    ], JSON_UNESCAPED_UNICODE));
} catch (Throwable $e) {
    ErrorLogger::logSqlError('DOI-Nachweise konnten nicht geladen werden | table: recipient_list_optin | error: ' . $e->getMessage());
    $error = 'Fehler beim Laden der DOI-Nachweise.';
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>DOI-Nachweise</title>
    <link rel="stylesheet" href="/assets/bootstrap/dist/css/bootstrap.min.css">
    <style>
        body { padding: 2rem; background: #f5f7fb; }
        .doi-list-shell { max-width: 1180px; margin: 0 auto; }
        .doi-list-card { border: 1px solid #dbe4ee; border-radius: 1rem; background: #fff; box-shadow: 0 12px 30px rgba(15, 23, 42, 0.06); overflow: hidden; }
        .doi-list-card .table { margin-bottom: 0; }
        .doi-toolbar { display: flex; gap: 0.75rem; flex-wrap: wrap; margin-bottom: 1rem; }
    </style>
</head>
<body>
    <div class="doi-list-shell">
        <div class="d-flex flex-wrap justify-content-between align-items-center gap-3 mb-3">
            <h1 class="h3 mb-0">DOI-Nachweise</h1>
            <div class="doi-toolbar">
                <a href="/admin/admin.php" class="btn btn-secondary">Zur Admin-Zentrale</a>
            </div>
        </div>

        <div class="alert alert-info">
            Hier suchst du Double-Opt-in-Nachweise gezielt nach E-Mail-Adresse oder DOI-Token. Die Nachweise liegen pro Empf&auml;nger und pro Liste vor.
        </div>

        <?php if ($error !== ''): ?>
            <div class="alert alert-danger"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></div>
        <?php endif; ?>

        <form method="get" class="row g-3 mb-3">
            <div class="col-md-6">
                <label for="search" class="form-label">Suche nach E-Mail oder Token</label>
                <input type="text" id="search" name="search" value="<?= htmlspecialchars($search, ENT_QUOTES, 'UTF-8') ?>" class="form-control">
            </div>
            <div class="col-md-3">
                <label for="status" class="form-label">Status</label>
                <select name="status" id="status" class="form-select">
                    <option value="all" <?= $statusFilter === 'all' ? 'selected' : '' ?>>Alle</option>
                    <option value="confirmed" <?= $statusFilter === 'confirmed' ? 'selected' : '' ?>>Best&auml;tigt</option>
                    <option value="open" <?= $statusFilter === 'open' ? 'selected' : '' ?>>Offen</option>
                </select>
            </div>
            <div class="col-md-3 d-flex align-items-end gap-2">
                <button type="submit" class="btn btn-primary">Suchen</button>
                <a href="optin_list.php" class="btn btn-outline-secondary">Zur&uuml;cksetzen</a>
            </div>
        </form>

        <div class="doi-list-card">
            <div class="table-responsive">
                <table class="table table-striped align-middle">
                    <thead>
                        <tr>
                            <th>E-Mail</th>
                            <th>Name</th>
                            <th>Liste</th>
                            <th>Status</th>
                            <th>Angefordert</th>
                            <th>Best&auml;tigt</th>
                            <th>Aktion</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($rows === []): ?>
                            <tr>
                                <td colspan="7" class="text-muted">Keine DOI-Nachweise gefunden.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($rows as $row): ?>
                                <?php
                                $name = trim(((string) ($row['vorname'] ?? '')) . ' ' . ((string) ($row['nachname'] ?? '')));
                                $isConfirmed = !empty($row['doi_confirmed']);
                                ?>
                                <tr>
                                    <td><?= htmlspecialchars((string) ($row['email'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
                                    <td><?= htmlspecialchars($name !== '' ? $name : '-', ENT_QUOTES, 'UTF-8') ?></td>
                                    <td><?= htmlspecialchars((string) ($row['list_name'] ?? '-'), ENT_QUOTES, 'UTF-8') ?></td>
                                    <td>
                                        <?php if ($isConfirmed): ?>
                                            <span class="badge text-bg-success">Best&auml;tigt</span>
                                        <?php else: ?>
                                            <span class="badge text-bg-warning">Offen</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= htmlspecialchars((string) ($row['doi_requested_at'] ?? '-'), ENT_QUOTES, 'UTF-8') ?></td>
                                    <td><?= htmlspecialchars((string) ($row['doi_confirmed_at'] ?? '-'), ENT_QUOTES, 'UTF-8') ?></td>
                                    <td>
                                        <a href="optin_view.php?token=<?= urlencode((string) ($row['doi_token'] ?? '')) ?>" class="btn btn-sm btn-outline-primary">
                                            Details
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>
</html>
