<?php
// admin/login_log.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 = 'Erfolgreiche Logins';

ob_start();

try {
    $stmt = Database::getInstance()->query("SELECT id, email, last_login_attempt FROM admin_users WHERE last_login_attempt IS NOT NULL ORDER BY last_login_attempt DESC LIMIT 100");
    ErrorLogger::logSqlSuccess("Erfolgreiche Logins geladen | table: admin_users | context: " . json_encode(["filter" => "last_login_attempt IS NOT NULL", "limit" => 100], JSON_UNESCAPED_UNICODE));
    $logins = $stmt->fetchAll();
} catch (PDOException $e) {
    ErrorLogger::logSqlError("Fehler beim Laden erfolgreicher Logins | table: admin_users | error: " . $e->getMessage());
    ErrorLogger::log("Fehler beim Laden der Login-Daten: " . $e->getMessage());
    $logins = [];
}
?>

<div class="page-header">
  Nutzerprotokolle &raquo; Erfolgreiche Logins
</div>

<div class="page-contend">
  <table class="table table-bordered table-sm table-hover">
    <thead class="table-light">
      <tr>
        <th>ID</th>
        <th>E-Mail</th>
        <th>Letzter Login</th>
      </tr>
    </thead>
    <tbody>
      <?php if (empty($logins)): ?>
        <tr><td colspan="3" class="text-center">Keine erfolgreichen Logins gefunden.</td></tr>
      <?php else: ?>
        <?php foreach ($logins as $login): ?>
          <tr>
            <td><?= $login['id'] ?></td>
            <td><?= htmlspecialchars($login['email']) ?></td>
            <td><?= $login['last_login_attempt'] ?></td>
          </tr>
        <?php endforeach; ?>
      <?php endif; ?>
    </tbody>
  </table>
</div>

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