<?php
// admin/status_monitor.php

session_start();
require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../auth/AuthController.php';

$auth = new AuthController();
if (!$auth->isLoggedIn() || $_SESSION['admin_role'] !== 'admin') {
    http_response_code(403);
    echo 'Zugriff verweigert.';
    exit;
}

$db = Database::getInstance();

function getStatusCounts($db) {
    $sql = 'SELECT status, COUNT(*) AS count FROM send_queue GROUP BY status';

    try {
        $rows = $db->query($sql)->fetchAll(PDO::FETCH_KEY_PAIR);
        ErrorLogger::logSqlSuccess('status_monitor: load queue status counts | SQL: ' . $sql . ' | params: []');
        return $rows;
    } catch (Throwable $e) {
        ErrorLogger::logSqlError('status_monitor: load queue status counts failed | SQL: ' . $sql . ' | params: [] | error: ' . $e->getMessage());
        return [];
    }
}

$statusCounts = getStatusCounts($db);
$total = array_sum($statusCounts);

$title = 'Versandstatus';
ob_start();
?>
<div class="page-header">
  Versand &raquo; Status-Monitor
</div>

<div class="page-contend">
  <div class="card">
    <div class="card-header fw-bold">Sendestatus Übersicht <small class="text-muted">(autom. Aktualisierung)</small></div>
    <div class="card-body" id="statusData">
      <ul class="list-unstyled">
        <li><strong>Gesamt:</strong> <?= $total ?></li>
        <li><strong>Ausstehend:</strong> <?= $statusCounts['pending'] ?? 0 ?></li>
        <li><strong>Gesendet:</strong> <?= $statusCounts['sent'] ?? 0 ?></li>
        <li><strong>Fehlgeschlagen:</strong> <?= $statusCounts['failed'] ?? 0 ?></li>
      </ul>
    </div>
  </div>
</div>

<script>
setInterval(() => {
  fetch('status_monitor_api.php')
    .then(res => res.text())
    .then(html => {
      document.getElementById('statusData').innerHTML = html;
    });
}, 10000);
</script>

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