<?php
/**
 * admin/transaction_log.php
 *
 * Übersicht über den Inhalt der Tabelle "transaction_log".
 *
 * Erfüllt die Mailresponder‑Guidelines:
 *  - ErrorLogger::logSqlSuccess / logSqlError für alle SQL‑Operationen
 *  - try/catch für Fehlerbehandlung
 *  - ausführlich kommentierter Code
 *  - strukturierte Bootstrap‑Tabelle mit TML‑Icons (Status‑Indikatoren)
 *  - Hinweise (Alerts) mit Auto‑Dismiss
 */

// ---------------------------------------------------------------------------
// Initialisierung & Auth‑Check
// ---------------------------------------------------------------------------

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

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

// ---------------------------------------------------------------------------
// Eingabewerte einlesen & validieren
// ---------------------------------------------------------------------------

$page       = max(1, (int)($_GET['page'] ?? 1));   // Aktuelle Seite
$perPage    = 50;                                  // Einträge pro Seite (Standard)
$status     = trim($_GET['status'] ?? '');         // Filter Status (triggered / skipped / error)
$campaignId = (int)($_GET['campaign_id'] ?? 0);    // Filter Kampagne
$recipient  = trim($_GET['recipient'] ?? '');      // Filter Empfänger‑Mail (LIKE‑Suche)

$offset = ($page - 1) * $perPage;

// Integer‑Sicherheit, da wir sie gleich direkt in LIMIT/OFFSET einfügen
$perPage = max(1, intval($perPage));
$offset  = max(0, intval($offset));

// ---------------------------------------------------------------------------
// Datenbankverbindung & dynamische WHERE‑Klausel aufbauen
// ---------------------------------------------------------------------------

$db     = Database::getInstance();
$where  = [];
$params = [];

if ($status !== '') {
    $where[]  = 'tl.status = ?';
    $params[] = $status;
}
if ($campaignId > 0) {
    $where[]  = 'tl.campaign_id = ?';
    $params[] = $campaignId;
}
if ($recipient !== '') {
    $where[]  = 'r.email LIKE ?';
    $params[] = '%' . $recipient . '%';
}
$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

// ---------------------------------------------------------------------------
// Daten laden – alles in try/catch, Logging bei Erfolg & Fehler
// ---------------------------------------------------------------------------

try {
    // 1) Gesamt‑Count für Pagination
    $countStmt = $db->prepare(
        "SELECT COUNT(*) FROM transaction_log tl
         LEFT JOIN recipients r ON r.id = tl.recipient_id
         $whereSql"
    );
    $countStmt->execute($params);
    $totalRows = (int)$countStmt->fetchColumn();
    ErrorLogger::logSqlSuccess('transaction_log: count loaded | params: ' . json_encode($params, JSON_UNESCAPED_UNICODE));

    // 2) Eigentliche Log‑Daten
    //    WICHTIG: LIMIT & OFFSET dürfen in vielen MySQL‑Versionen keine Platzhalter sein,
    //    deshalb werden sie hier als bereits geprüfte Integer direkt eingesetzt.
    $logSql = "SELECT tl.*, c.name AS campaign_name, r.email
                 FROM transaction_log tl
                 LEFT JOIN campaigns  c ON c.id = tl.campaign_id
                 LEFT JOIN recipients r ON r.id = tl.recipient_id
                 $whereSql
            ORDER BY tl.created_at DESC
               LIMIT $perPage OFFSET $offset";

    $logStmt = $db->prepare($logSql);
    $logStmt->execute($params);   // nur WHERE‑Parameter binden
    $logs = $logStmt->fetchAll(PDO::FETCH_ASSOC);
    ErrorLogger::logSqlSuccess('transaction_log: logs loaded | SQL: ' . $logSql . ' | params: ' . json_encode($params, JSON_UNESCAPED_UNICODE));
} catch (PDOException $e) {
    ErrorLogger::logSqlError('transaction_log: load failed | SQL: ' . ($logSql ?? 'SELECT transaction_log') . ' | params: ' . json_encode($params, JSON_UNESCAPED_UNICODE) . ' | error: ' . $e->getMessage());
    $logs      = [];
    $totalRows = 0;
}

// ---------------------------------------------------------------------------
// Hilfsfunktion: TML‑Icon je Status
// ---------------------------------------------------------------------------

function statusIcon(string $status): string
{
    switch ($status) {
        case 'triggered':
            return '<i class="tml-icon-check text-success" title="Triggered"></i>';
        case 'skipped':
            return '<i class="tml-icon-minus-circle text-warning" title="Skipped"></i>';
        case 'error':
            return '<i class="tml-icon-alert text-danger" title="Error"></i>';
        default:
            return '';
    }
}

// ---------------------------------------------------------------------------
// HTML‑Ausgabe (wird später von template.php eingerahmt)
// ---------------------------------------------------------------------------

ob_start();
?>

<div class="container-fluid">
    <h1 class="mb-4"><i class="tml-icon-list"></i> Transaction‑Log</h1>

    <!-- Filter‑Formular -------------------------------------------------- -->
    <form class="row g-2 mb-3" method="get">
        <div class="col-md-2">
            <input type="number" name="campaign_id" value="<?= htmlspecialchars($campaignId) ?>"
                   class="form-control" placeholder="Campaign‑ID">
        </div>
        <div class="col-md-3">
            <input type="text" name="recipient" value="<?= htmlspecialchars($recipient) ?>"
                   class="form-control" placeholder="E‑Mail">
        </div>
        <div class="col-md-2">
            <select name="status" class="form-select">
                <option value="">— Status —</option>
                <?php foreach ([ 'triggered', 'skipped', 'error' ] as $opt): ?>
                    <option value="<?= $opt ?>" <?= $status === $opt ? 'selected' : '' ?>>
                        <?= ucfirst($opt) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-2">
            <button type="submit" class="btn btn-primary w-100">
                <i class="tml-icon-search"></i> Filtern
            </button>
        </div>
        <div class="col-md-2">
            <a href="<?= basename(__FILE__) ?>" class="btn btn-secondary w-100">
                <i class="tml-icon-undo"></i> Zurücksetzen
            </a>
        </div>
    </form>

    <!-- Log‑Tabelle ------------------------------------------------------ -->
    <?php if (empty($logs)): ?>
        <div id="autoDismiss" class="alert alert-info">
            <i class="tml-icon-info"></i> Keine Einträge gefunden.
        </div>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table table-sm table-striped align-middle">
                <thead class="table-light">
                <tr>
                    <th>ID</th>
                    <th>Status</th>
                    <th>Kampagne</th>
                    <th>Empfänger</th>
                    <th>Nachricht</th>
                    <th>Datum</th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($logs as $row): ?>
                    <tr>
                        <td><?= (int)$row['id'] ?></td>
                        <td><?= statusIcon($row['status']) ?></td>
                        <td>
                            <?= (int)$row['campaign_id'] ?>
                            <?php if (!empty($row['campaign_name'])): ?>
                                <br><small class="text-muted"><?= htmlspecialchars($row['campaign_name']) ?></small>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?= (int)$row['recipient_id'] ?><br>
                            <small class="text-muted"><?= htmlspecialchars($row['email'] ?? '–') ?></small>
                        </td>
                        <td style="max-width:300px;white-space:pre-wrap;">
                            <?= nl2br(htmlspecialchars($row['message'] ?? '')) ?>
                        </td>
                        <td><?= date('d.m.Y H:i:s', strtotime($row['created_at'])) ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- Pagination -------------------------------------------------- -->
        <?php
            $totalPages = (int)ceil($totalRows / $perPage);
            if ($totalPages > 1):
        ?>
        <nav aria-label="Seiten">
            <ul class="pagination">
                <?php for ($p = 1; $p <= $totalPages; $p++): ?>
                    <?php
                        $classes = 'page-item' . ($p === $page ? ' active' : '');
                        $q = http_build_query(array_merge($_GET, ['page' => $p]));
                    ?>
                    <li class="<?= $classes ?>">
                        <a class="page-link" href="?<?= $q ?>"><?= $p ?></a>
                    </li>
                <?php endfor; ?>
            </ul>
        </nav>
        <?php endif; ?>
    <?php endif; ?>
</div>

<!-- Auto‑Dismiss (Bootstrap Alert) -------------------------------------- -->
<script>
setTimeout(() => {
    const alertBox = document.getElementById('autoDismiss');
    if (alertBox) {
        alertBox.classList.add('fade', 'show');
        bootstrap.Alert.getOrCreateInstance(alertBox).close();
    }
}, 5000);
</script>

<?php
// ---------------------------------------------------------------------------
// Inhalt an das Admin‑Template übergeben
// ---------------------------------------------------------------------------

$pageContent = ob_get_clean();
include_once __DIR__ . '/template.php';


