<?php
// admin/open_monitor.php - Anzeige der E-Mail-Öffnungen

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

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

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

$db = Database::getInstance();
$openLogs = [];
$sqlOpenLogs = "SELECT eo.*, r.email, q.template_id, t.name AS template_name
                FROM email_opens eo
                JOIN send_queue q ON eo.queue_id = q.id
                JOIN recipients r ON q.recipient_id = r.id
                LEFT JOIN email_templates t ON q.template_id = t.id
                ORDER BY eo.opened_at DESC LIMIT 200";

try {
    $openLogs = $db->query($sqlOpenLogs)->fetchAll(PDO::FETCH_ASSOC);
    ErrorLogger::logSqlSuccess('open_monitor: load latest opens | SQL: ' . $sqlOpenLogs . ' | params: []');
} catch (Throwable $e) {
    ErrorLogger::logSqlError('open_monitor: load latest opens failed | SQL: ' . $sqlOpenLogs . ' | params: [] | error: ' . $e->getMessage());
    $openLogs = [];
}

$title = 'E-Mail-Öffnungen';
ob_start();
?>
<div class="page-header">E-Mail-Öffnungen (Letzte 200)</div>

<table class="table table-bordered table-striped">
  <thead>
    <tr>
      <th>ID</th>
      <th>Empfänger</th>
      <th>Template</th>
      <th>Gerät</th>
      <th>IP</th>
      <th>Browser (User-Agent)</th>
      <th>Geöffnet am</th>
    </tr>
  </thead>
  <tbody>
    <?php foreach ($openLogs as $log): ?>
      <tr>
        <td><?= $log['id'] ?></td>
        <td><?= htmlspecialchars($log['email']) ?></td>
        <td><?= htmlspecialchars($log['template_name'] ?? '-') ?></td>
        <td><?= htmlspecialchars($log['device_type']) ?></td>
        <td><?= htmlspecialchars($log['ip_address']) ?></td>
        <td><?= htmlspecialchars($log['user_agent']) ?></td>
        <td><?= htmlspecialchars($log['opened_at']) ?></td>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>

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

