<?php
// admin/absender.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;
}

$title = 'Absender-Verwaltung';
$db = Database::getInstance();
ob_start();

try {
    $stmt = $db->query("SELECT * FROM sender_identities ORDER BY is_active DESC, name ASC");
    ErrorLogger::logSqlSuccess("Absender geladen | table: sender_identities | context: " . json_encode(["order" => "is_active DESC, name ASC"], JSON_UNESCAPED_UNICODE));
    $senders = $stmt->fetchAll();
} catch (PDOException $e) {
    ErrorLogger::logSqlError("Fehler beim Laden der Absender | table: sender_identities | error: " . $e->getMessage());
    ErrorLogger::log("Fehler beim Laden der Absender: " . $e->getMessage());
    $senders = [];
}
?>

<div class="page-header">
  Admin &raquo; Absender-Verwaltung
</div>

<div class="page-contend">
  <a href="absender_neu.php" class="btn btn-success mb-3">Neuen Absender hinzufügen</a>

  <table class="table table-sm table-bordered table-hover">
    <thead class="table-light">
      <tr>
        <th>ID</th>
        <th>Name</th>
        <th>E-Mail</th>
        <th>DKIM-Selector</th>
        <th>Status</th>
        <th>Aktion</th>
      </tr>
    </thead>
    <tbody>
      <?php if (empty($senders)): ?>
        <tr><td colspan="6" class="text-center">Keine Absender vorhanden.</td></tr>
      <?php else: ?>
        <?php foreach ($senders as $sender): ?>
          <tr>
            <td><?= $sender['id'] ?></td>
            <td><?= htmlspecialchars($sender['name']) ?></td>
            <td><?= htmlspecialchars($sender['email']) ?></td>
            <td><?= $sender['dkim_selector'] ?: '–' ?></td>
            <td><?= $sender['is_active'] ? '<span class="text-success">aktiv</span>' : '<span class="text-muted">inaktiv</span>' ?></td>
            <td>
              <a href="absender_bearbeiten.php?id=<?= $sender['id'] ?>" class="btn btn-sm btn-outline-primary">Bearbeiten</a>
              <a href="absender_loeschen.php?id=<?= $sender['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Wirklich löschen?')">Löschen</a>
            </td>
          </tr>
        <?php endforeach; ?>
      <?php endif; ?>
    </tbody>
  </table>
</div>

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