<?php
// admin/reset_requests.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 = 'Passwort-Reset-Anfragen';

ob_start();

try {
    $stmt = Database::getInstance()->query("SELECT id, email, reset_token, expires_at, used, created_at FROM password_resets ORDER BY created_at DESC LIMIT 100");
    ErrorLogger::logSqlSuccess("Reset-Anfragen geladen | table: password_resets | context: " . json_encode(["limit" => 100], JSON_UNESCAPED_UNICODE));
    $tokens = $stmt->fetchAll();
} catch (PDOException $e) {
    ErrorLogger::logSqlError("Fehler beim Laden der Reset-Anfragen | table: password_resets | error: " . $e->getMessage());
    ErrorLogger::log("Fehler beim Laden der Reset-Anfragen: " . $e->getMessage());
    $tokens = [];
}
?>

<div class="page-header">
  Nutzerprotokolle &raquo; Passwort-Reset-Anfragen
</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>Token</th>
        <th>Erstellt</th>
        <th>Gültig bis</th>
        <th>Status</th>
      </tr>
    </thead>
    <tbody>
      <?php if (empty($tokens)): ?>
        <tr><td colspan="6" class="text-center">Keine Reset-Anfragen gefunden.</td></tr>
      <?php else: ?>
        <?php foreach ($tokens as $token): ?>
          <tr>
            <td><?= $token['id'] ?></td>
            <td><?= htmlspecialchars($token['email']) ?></td>
            <td><code><?= substr($token['reset_token'], 0, 8) ?>...</code></td>
            <td><?= $token['created_at'] ?></td>
            <td><?= $token['expires_at'] ?></td>
            <td><?= $token['used'] ? 'Verwendet' : 'Offen' ?></td>
          </tr>
        <?php endforeach; ?>
      <?php endif; ?>
    </tbody>
  </table>
</div>

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