<?php
// admin/nutzer.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 = 'Nutzer anzeigen & bearbeiten';
ob_start();

// Nutzer laden
try {
    $stmt = Database::getInstance()->query("SELECT id, email, name, role, is_active, list_id, created_at FROM admin_users ORDER BY created_at DESC");
    ErrorLogger::logSqlSuccess("Nutzerliste geladen | table: admin_users | context: " . json_encode(["order" => "created_at DESC"], JSON_UNESCAPED_UNICODE));
    $nutzer = $stmt->fetchAll();
} catch (PDOException $e) {
    ErrorLogger::logSqlError("Fehler beim Laden der Nutzerliste | table: admin_users | error: " . $e->getMessage());
    ErrorLogger::log("Fehler beim Laden der Nutzerliste: " . $e->getMessage());
    $nutzer = [];
}
?>

<div class="page-header">
  Nutzerverwaltung &raquo; Übersicht
</div>

<div class="page-contend">

  <?php if (!empty($_SESSION['success_message'])): ?>
    <div class="alert alert-success">
      <?= htmlspecialchars($_SESSION['success_message']) ?>
    </div>
    <?php unset($_SESSION['success_message']); ?>
  <?php endif; ?>

  <table class="table table-bordered table-hover table-sm">
    <thead class="table-light">
      <tr>
        <th>ID</th>
        <th>Name</th>
        <th>E-Mail</th>
        <th>Rolle</th>
        <th>Liste</th>
        <th>Status</th>
        <th>Erstellt</th>
        <th>Aktion</th>
      </tr>
    </thead>
    <tbody>
      <?php if (empty($nutzer)): ?>
        <tr><td colspan="8" class="text-center">Keine Nutzer gefunden.</td></tr>
      <?php else: ?>
        <?php foreach ($nutzer as $row): ?>
          <tr>
            <td><?= htmlspecialchars($row['id']) ?></td>
            <td><?= htmlspecialchars($row['name']) ?></td>
            <td><?= htmlspecialchars($row['email']) ?></td>
            <td><?= htmlspecialchars($row['role']) ?></td>
            <td><?= $row['list_id'] ?? '-' ?></td>
            <td><?= $row['is_active'] ? 'Aktiv' : 'Inaktiv' ?></td>
            <td><?= htmlspecialchars($row['created_at']) ?></td>
            <td>
              <a href="nutzer_edit.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-primary">Bearbeiten</a>
            </td>
          </tr>
        <?php endforeach; ?>
      <?php endif; ?>
    </tbody>
  </table>

</div>

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

