<?php
// admin/status/smtp_status.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();

$smtpAccounts = [];
$sqlSmtp = 'SELECT id, host, from_email, last_used_at, is_active FROM smtp_accounts ORDER BY last_used_at ASC';

try {
    $smtpAccounts = $db->query($sqlSmtp)->fetchAll();
    ErrorLogger::logSqlSuccess('smtp_status: load smtp accounts | SQL: ' . $sqlSmtp . ' | params: []');
} catch (Throwable $e) {
    ErrorLogger::logSqlError('smtp_status: load smtp accounts failed | SQL: ' . $sqlSmtp . ' | params: [] | error: ' . $e->getMessage());
    $smtpAccounts = [];
}

$title = 'SMTP Statusmonitor';

ob_start();
?>
<div class="page-header">SMTP Statusmonitor</div>

<table class="table table-bordered table-striped">
  <thead>
    <tr>
      <th>ID</th>
      <th>SMTP-Host</th>
      <th>Absender</th>
      <th>Letzte Nutzung</th>
      <th>Status</th>
    </tr>
  </thead>
  <tbody>
    <?php foreach ($smtpAccounts as $smtp): ?>
      <tr>
        <td><?= htmlspecialchars($smtp['id']) ?></td>
        <td><?= htmlspecialchars($smtp['host']) ?></td>
        <td><?= htmlspecialchars($smtp['from_email']) ?></td>
        <td><?= htmlspecialchars($smtp['last_used_at']) ?></td>
        <td>
          <?php if ($smtp['is_active']): ?>
            <span class="badge bg-success">Aktiv</span>
          <?php else: ?>
            <span class="badge bg-danger">Inaktiv</span>
          <?php endif; ?>
        </td>
      </tr>
    <?php endforeach; ?>
  </tbody>
</table>

<script>
  setInterval(function() {
    fetch(location.href)
      .then(res => res.text())
      .then(html => {
        const doc = new DOMParser().parseFromString(html, 'text/html');
        document.querySelector('table').innerHTML = doc.querySelector('table').innerHTML;
      });
  }, 30000);
</script>
<?php
$pageContent = ob_get_clean();
include __DIR__ . '/../template.php';
