<?php
/**
 * admin/bounce_log.php
 * -----------------------------------------------------------------------------
 * Zeigt alle Einträge aus `email_bounces` im Admin-Backend an mit Suchfunktion.
 *
 * Funktionen:
 * - Suche nach Empfänger-E-Mail
 * - Anzeige von Bounce-Metadaten und Raw-Body
 * - Paginierung
 * - Fehler-Handling und Logging mit ErrorLogger
 * - TML-Icons in Status-Headern
 */

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

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

// Datenbank-Instanz
$db = Database::getInstance();

// =============================================================================
// Parameter: Suche & Pagination
// =============================================================================
$search  = isset($_GET['search']) ? trim($_GET['search']) : '';
$page    = max(1, (int) ($_GET['page'] ?? 1));
$perPage = 25;
$offset  = ($page - 1) * $perPage;

try {
    // Dynamischer WHERE-Teil bei Suche
    $where  = '';
    $params = [];
    if ($search !== '') {
        $where = 'WHERE r.email LIKE :search';
        $params[':search'] = "%{$search}%";
    }

    // Gesamtanzahl ermitteln
    $countSql = "SELECT COUNT(*) FROM email_bounces b JOIN recipients r ON b.recipient_id = r.id $where";
    $countSt  = $db->prepare($countSql);
    foreach ($params as $key => $val) {
        $countSt->bindValue($key, $val, PDO::PARAM_STR);
    }
    $countSt->execute();
    ErrorLogger::logSqlSuccess("Bounce-Log Gesamtanzahl geladen | table: email_bounces | context: " . json_encode(["search" => $search], JSON_UNESCAPED_UNICODE));
    $total = (int) $countSt->fetchColumn();

    // Datensätze abfragen
    $sql = "SELECT b.id,
                   r.email AS recipient_email,
                   b.bounce_type,
                   b.reason,
                   b.raw_body,
                   b.logged_at
            FROM email_bounces b
            JOIN recipients r ON b.recipient_id = r.id
            $where
            ORDER BY b.logged_at DESC
            LIMIT :offset, :limit";
    $st = $db->prepare($sql);
    foreach ($params as $key => $val) {
        $st->bindValue($key, $val, PDO::PARAM_STR);
    }
    $st->bindValue(':offset', $offset, PDO::PARAM_INT);
    $st->bindValue(':limit',  $perPage, PDO::PARAM_INT);
    $st->execute();
    ErrorLogger::logSqlSuccess("Bounce-Log Einträge geladen | table: email_bounces | context: " . json_encode(["search" => $search, "page" => $page, "per_page" => $perPage], JSON_UNESCAPED_UNICODE));
    $rows = $st->fetchAll(PDO::FETCH_ASSOC);

} catch (Throwable $e) {
    ErrorLogger::logSqlError("Fehler beim Laden des Bounce-Logs | table: email_bounces | error: " . $e->getMessage());
    ErrorLogger::log('BOUNCE_LOG_ERROR: ' . $e->getMessage());
    echo '<div class="alert alert-danger auto-dismiss">';
    echo '<i class="tml-icon tml-icon-error"></i> Fehler beim Laden der Bounce-Daten.';
    echo '</div>';
    exit;
}

// =============================================================================
// Anzeige
// =============================================================================
ob_start();
?>
<div class="container mt-4">
    <h1>Bounce Log</h1>
    <form method="get" class="mb-3">
        <div class="input-group">
            <input type="text" name="search" value="<?= htmlspecialchars($search, ENT_QUOTES, 'UTF-8') ?>" 
                   class="form-control" placeholder="Nach Empfänger-E-Mail suchen">
            <button class="btn btn-primary" type="submit">
                <i class="tml-icon tml-icon-search"></i> Suchen
            </button>
        </div>
    </form>

    <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($rows)): ?>
                <tr><td colspan="4" class="text-center">Keine Einträge gefunden.</td></tr>
            <?php endif; ?>

            <?php foreach ($rows as $row): ?>
                <tr>
                    <td><?= htmlspecialchars($row['recipient_email'], ENT_QUOTES, 'UTF-8') ?></td>
                    <td><?= htmlspecialchars($row['bounce_type'], ENT_QUOTES, 'UTF-8') ?></td>
                    <td><?= htmlspecialchars($row['logged_at'], ENT_QUOTES, 'UTF-8') ?></td>
                    <td><?= nl2br(htmlspecialchars($row['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"], '', $row['raw_body']), ENT_QUOTES, 'UTF-8') ?>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <?php if (ceil($total / $perPage) > 1): ?>
    <nav>
      <ul class="pagination">
        <?php for ($i = 1, $pages = ceil($total / $perPage); $i <= $pages; $i++): ?>
          <li class="page-item <?= $i === $page ? 'active' : '' ?>">
            <a class="page-link" href="?page=<?= $i ?><?= $search !== '' ? '&search=' . urlencode($search) : '' ?>"><?= $i ?></a>
          </li>
        <?php endfor; ?>
      </ul>
    </nav>
    <?php endif; ?>
</div>
<?php
$pageContent = ob_get_clean();
include __DIR__ . '/template.php';
?>
