<?php
/**
 * admin/empfaenger/empfaenger_verlauf.php
 * --------------------------------------------------------------------------
 * Versand- und Bounce-Verlauf eines Empfängers.
 */

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

// ─────────────────────────────────────────────────────────────────────────────
// 1) Authentifizierung
// ─────────────────────────────────────────────────────────────────────────────
$auth = new AuthController();
if (!$auth->isLoggedIn()) {
    header('Location: ' . $adminLoginPath);
    exit;
}

// ─────────────────────────────────────────────────────────────────────────────
// 2) Empfänger-ID prüfen
// ─────────────────────────────────────────────────────────────────────────────
$db            = Database::getInstance();
$empfaengerId  = isset($_GET['id']) ? (int) $_GET['id'] : 0;
if ($empfaengerId <= 0) {
    die('❌ Ungültige Empfänger-ID');
}

// ─────────────────────────────────────────────────────────────────────────────
// 3) Versand-Verlauf holen
// ─────────────────────────────────────────────────────────────────────────────
try {
    $sqlMail = "
        SELECT
            sq.id AS send_id,
            et.subject,
            sq.sent_at,
            (SELECT MIN(opened_at)  FROM email_opens         WHERE queue_id = sq.id) AS opened_at,
            (SELECT MIN(clicked_at) FROM email_link_tracking WHERE queue_id = sq.id) AS clicked_at
        FROM send_queue sq
        LEFT JOIN email_templates et ON et.id = sq.template_id
        WHERE sq.recipient_id = ?
        ORDER BY sq.sent_at DESC
    ";
    $stMail = $db->prepare($sqlMail);
    $stMail->execute([$empfaengerId]);
    $verlaufMails = $stMail->fetchAll(PDO::FETCH_ASSOC);

    ErrorLogger::logSqlSuccess(__FILE__ . ' | Mail-Verlauf geladen');
} catch (Throwable $e) {
    ErrorLogger::logSqlError(__FILE__ . ' | ' . $e->getMessage());
    $verlaufMails = [];
}

// ─────────────────────────────────────────────────────────────────────────────
// 4) Bounce-Verlauf holen
// ─────────────────────────────────────────────────────────────────────────────
try {
    $sqlBounce = "
        SELECT
            email           AS recipient_email,
            bounce_type,
            logged_at,
            reason,
            raw_body
        FROM email_bounces
        WHERE recipient_id = ?
        ORDER BY logged_at DESC
    ";
    $stBounce = $db->prepare($sqlBounce);
    $stBounce->execute([$empfaengerId]);
    $verlaufBounces = $stBounce->fetchAll(PDO::FETCH_ASSOC);

    ErrorLogger::logSqlSuccess(__FILE__ . ' | Bounce-Verlauf geladen');
} catch (Throwable $e) {
    ErrorLogger::logSqlError(__FILE__ . ' | ' . $e->getMessage());
    $verlaufBounces = [];
}

// ─────────────────────────────────────────────────────────────────────────────
// 5) HTML-Ausgabe
// ─────────────────────────────────────────────────────────────────────────────
ob_start();
?>

<!-- Versand-Verlauf -------------------------------------------------------- -->
<h2 class="mb-4">📬 Versand-Verlauf</h2>

<?php if (empty($verlaufMails)): ?>
    <div class="alert alert-info auto-dismiss">
        <i class="ti ti-info-circle me-1"></i>
        Dieser Empfänger hat bisher keine E-Mails erhalten.
    </div>
<?php else: ?>
    <table class="table table-bordered table-striped align-middle">
        <thead class="table-light">
        <tr>
            <th>Betreff</th>
            <th>Gesendet&nbsp;am</th>
            <th>Erste Öffnung</th>
            <th>Erster Klick</th>
        </tr>
        </thead>
        <tbody>
        <?php foreach ($verlaufMails as $mail): ?>
            <tr>
                <td><?= htmlspecialchars($mail['subject']   ?? '—', ENT_QUOTES, 'UTF-8') ?></td>
                <td><?= htmlspecialchars($mail['sent_at']    ?? '—', ENT_QUOTES, 'UTF-8') ?></td>
                <td><?= htmlspecialchars($mail['opened_at']  ?? '—', ENT_QUOTES, 'UTF-8') ?></td>
                <td><?= htmlspecialchars($mail['clicked_at'] ?? '—', ENT_QUOTES, 'UTF-8') ?></td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
<?php endif; ?>


<!-- Bounce-Verlauf --------------------------------------------------------- -->
<h2 class="mt-5 mb-4">🚨 Bounce-Verlauf</h2>

<table class="table table-bordered">
    <thead>
    <tr>
        <th>E-Mail</th>
        <th>Typ</th>
        <th>Datum</th>
        <th>Reason</th>
    </tr>
    </thead>
    <tbody>
    <?php if (empty($verlaufBounces)): ?>
        <tr><td colspan="4" class="text-center">Keine Einträge gefunden.</td></tr>
    <?php endif; ?>

    <?php foreach ($verlaufBounces as $b): ?>
        <tr>
            <td><?= htmlspecialchars($b['recipient_email'] ?? '—', ENT_QUOTES, 'UTF-8') ?></td>
            <td><?= htmlspecialchars($b['bounce_type']      ?? '—', ENT_QUOTES, 'UTF-8') ?></td>
            <td><?= htmlspecialchars($b['logged_at']        ?? '—', ENT_QUOTES, 'UTF-8') ?></td>
            <td><?= nl2br(htmlspecialchars($b['reason']      ?? '—', ENT_QUOTES, 'UTF-8')) ?></td>
        </tr>
        <tr>
            <td colspan="4" class="text-monospace small text-wrap" style="word-break: break-word; max-width: 200px;">
                <?= htmlspecialchars(
                        str_replace(["\r", "\n"], '', $b['raw_body'] ?? ''),
                        ENT_QUOTES,
                        'UTF-8'
                   ) ?>
            </td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>

<?php
// ─────────────────────────────────────────────────────────────────────────────
// 6) Template einbinden
// ─────────────────────────────────────────────────────────────────────────────
$pageContent = ob_get_clean();
include_once __DIR__ . '/../template.php';
?>