<?php
// admin/listen.php

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();
$title = 'Listenübersicht';
$listen = [];
$sqlListen = 'SELECT l.*, s.name AS sender_name, s.email AS sender_email FROM lists l LEFT JOIN sender_identities s ON l.from_identity_id = s.id ORDER BY l.created_at DESC';

try {
    $listen = $db->query($sqlListen)->fetchAll();
    ErrorLogger::logSqlSuccess('listen: load list overview | SQL: ' . $sqlListen . ' | params: []');
} catch (Throwable $e) {
    ErrorLogger::logSqlError('listen: load list overview failed | SQL: ' . $sqlListen . ' | params: [] | error: ' . $e->getMessage());
    $listen = [];
}

ob_start();
?>
<div class="page-header h2">Listenübersicht</div>

<p>
  <a href="listen_create.php" class="btn btn-success">+ Neue Liste erstellen</a>
</p>

<table class="table table-bordered table-hover">
  <thead class="table-light">
    <tr>
      <th>Name</th>
      <th>Absender</th>
      <th>Double-Opt-In</th>
      <th>Anmeldeinfo</th>
      <th>Erstellt</th>
      <th>Aktionen</th>
    </tr>
  </thead>
  <tbody>
    <?php foreach ($listen as $liste): ?>
      <tr>
        <td><?= htmlspecialchars($liste['name']) ?></td>
        <td><?= htmlspecialchars($liste['sender_name'] . ' <' . $liste['sender_email'] . '>') ?></td>
        <td><?= $liste['requires_doi'] ? 'Ja' : 'Nein' ?></td>
        <td><?= !empty($liste['notify_on_signup']) ? 'Ja' : 'Nein' ?></td>
        <td><?= date('d.m.Y H:i', strtotime($liste['created_at'])) ?></td>
        <td>
          <a href="listen_edit.php?id=<?= $liste['id'] ?>" class="btn btn-sm btn-outline-primary">Bearbeiten</a>
          <a href="listen_delete.php?id=<?= $liste['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Möchtest du diese Liste wirklich löschen?')">Löschen</a>
        </td>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>

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