<?php
// admin/click_monitor.php – Anzeige der E-Mail-Klicks (Letzte 200)
// Quelle: Tabelle email_link_tracking (clicked_at != NULL = Klick erfolgt)

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../auth/AuthController.php';

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

/* =========================================================================
 * DB initialisieren
 * ========================================================================= */
$db = Database::getInstance();

/* =========================================================================
 * Klick-Logs laden (email_link_tracking)
 *  - Wir zeigen nur Datensätze mit clicked_at IS NOT NULL (echte Klicks)
 *  - JOINs:
 *      email_link_tracking -> send_queue -> recipients
 *      optional: email_templates (Template-Namen)
 *  - LIMIT 200 (neueste zuerst)
 * ========================================================================= */
$clickLogs = [];
$loadError = null;

try {
    $sql = "
        SELECT 
            lt.id,
            lt.token,
            lt.original_url,
            lt.queue_id,
            lt.clicked_at,
            lt.ip_address,
            lt.user_agent,
            lt.device_type,
            r.email,
            q.template_id,
            t.name AS template_name
        FROM email_link_tracking lt
        JOIN send_queue q ON lt.queue_id = q.id
        JOIN recipients r ON q.recipient_id = r.id
        LEFT JOIN email_templates t ON q.template_id = t.id
        WHERE lt.clicked_at IS NOT NULL
        ORDER BY lt.clicked_at DESC
        LIMIT 200
    ";

    $clickLogs = $db->query($sql)->fetchAll(PDO::FETCH_ASSOC);

    // ✅ SQL-Logging Erfolg
    ErrorLogger::logSqlSuccess('click_monitor: load click logs | SQL: ' . $sql . ' | params: []');
} catch (Throwable $e) {
    // ❌ SQL-Logging Fehler
    ErrorLogger::logSqlError('click_monitor: load click logs failed | SQL: ' . ($sql ?? 'SELECT click logs') . ' | params: [] | error: ' . $e->getMessage());
    $loadError = $e->getMessage();
    $clickLogs = [];
}

/* =========================================================================
 * Page Rendering
 * ========================================================================= */
$title = 'E-Mail-Klicks';
ob_start();
?>
<div class="page-header">
    <i class="tml-icon tml-icon-link"></i>
    E-Mail-Klicks (Letzte 200)
</div>

<?php if ($loadError): ?>
    <div class="alert alert-danger auto-dismiss">
        <i class="tml-icon tml-icon-alert-triangle"></i>
        Fehler beim Laden der Klicks: <?= htmlspecialchars($loadError, ENT_QUOTES, 'UTF-8') ?>
    </div>
<?php elseif (empty($clickLogs)): ?>
    <div class="alert alert-info auto-dismiss">
        <i class="tml-icon tml-icon-info"></i>
        Keine Klicks gefunden.
    </div>
<?php endif; ?>

<table class="table table-bordered table-striped">
    <thead>
        <tr>
            <th>ID</th>
            <th>Empfänger</th>
            <th>Template</th>
            <th>Token</th>
            <th>URL</th>
            <th>Gerät</th>
            <th>IP</th>
            <th>Browser (User-Agent)</th>
            <th>Geklickt am</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($clickLogs as $log): ?>
            <tr>
                <td><?= (int)$log['id'] ?></td>
                <td><?= htmlspecialchars($log['email'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                <td><?= htmlspecialchars($log['template_name'] ?? '–', ENT_QUOTES, 'UTF-8') ?></td>
                <td style="max-width: 210px; word-break: break-word;">
                    <?= htmlspecialchars($log['token'] ?? '', ENT_QUOTES, 'UTF-8') ?>
                </td>
                <td style="max-width: 520px; word-break: break-word;">
                    <?php if (!empty($log['original_url'])): ?>
                        <a href="<?= htmlspecialchars($log['original_url'], ENT_QUOTES, 'UTF-8') ?>" target="_blank" rel="noopener">
                            <?= htmlspecialchars($log['original_url'], ENT_QUOTES, 'UTF-8') ?>
                        </a>
                    <?php else: ?>
                        –
                    <?php endif; ?>
                </td>
                <td><?= htmlspecialchars($log['device_type'] ?? 'unknown', ENT_QUOTES, 'UTF-8') ?></td>
                <td><?= htmlspecialchars($log['ip_address'] ?? '–', ENT_QUOTES, 'UTF-8') ?></td>
                <td style="max-width: 520px; word-break: break-word;">
                    <?= htmlspecialchars($log['user_agent'] ?? '–', ENT_QUOTES, 'UTF-8') ?>
                </td>
                <td><?= htmlspecialchars($log['clicked_at'] ?? '–', ENT_QUOTES, 'UTF-8') ?></td>
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<?php
$pageContent = ob_get_clean();
include __DIR__ . '/template.php';

