<?php
declare(strict_types=1);

if (!defined('APP_ENV') || APP_ENV !== 'staging') {
    http_response_code(404);
    exit;
}

$app = app();
$pdo = $app->pdo();
$users = [];
$error = '';

try {
    if (!$pdo) {
        throw new RuntimeException('Keine Datenbankverbindung verfügbar.');
    }

    $hasRolesTable = false;
    try {
        $stmt = $pdo->query("SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'user_roles' LIMIT 1");
        $hasRolesTable = (bool)$stmt->fetchColumn();
    } catch (Throwable) {
        $hasRolesTable = false;
    }

    $sql = '
        SELECT u.id,
               u.email,
               u.status,
               u.created_at,
               COALESCE(p.display_name, "") AS display_name
        FROM users u
        LEFT JOIN user_profiles p ON p.user_id = u.id
        ORDER BY u.id ASC
    ';
    $stmt = $pdo->query($sql);
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

    if ($hasRolesTable && $users) {
        $roleStmt = $pdo->query('SELECT user_id, role FROM user_roles ORDER BY user_id ASC, role ASC');
        $rolesByUser = [];
        foreach ($roleStmt->fetchAll(PDO::FETCH_ASSOC) ?: [] as $row) {
            $rolesByUser[(int)$row['user_id']][] = (string)$row['role'];
        }
        foreach ($users as &$user) {
            $user['roles'] = $rolesByUser[(int)$user['id']] ?? [];
        }
        unset($user);
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
}
?>
<main class="section">
  <div class="container">
    <div class="section__intro">
      <h1>Staging: Registrierte Benutzer</h1>
    </div>

    <div class="card dash-card">
      <?php if ($error !== ''): ?>
        <div class="toast-bar" style="border-color:#f87171; color:#991b1b; margin-bottom:12px;">
          Fehler: <?= htmlspecialchars($error, ENT_QUOTES) ?>
        </div>
      <?php endif; ?>

      <p class="muted small">Diese Seite ist nur im Staging verfügbar.</p>

      <?php if (!$users): ?>
        <p class="muted">Keine Benutzer gefunden.</p>
      <?php else: ?>
        <div style="overflow:auto; margin-top:14px;">
          <table style="width:100%; border-collapse:collapse;">
            <thead>
              <tr style="text-align:left; border-bottom:1px solid var(--color-border);">
                <th style="padding:10px 8px;">ID</th>
                <th style="padding:10px 8px;">Anzeigename</th>
                <th style="padding:10px 8px;">E-Mail</th>
                <th style="padding:10px 8px;">Status</th>
                <th style="padding:10px 8px;">Registriert</th>
                <th style="padding:10px 8px;">Rollen</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($users as $user): ?>
                <tr style="border-bottom:1px solid var(--color-border);">
                  <td style="padding:10px 8px; white-space:nowrap;"><?= (int)$user['id'] ?></td>
                  <td style="padding:10px 8px;"><?= htmlspecialchars((string)$user['display_name'], ENT_QUOTES) ?></td>
                  <td style="padding:10px 8px;"><?= htmlspecialchars((string)$user['email'], ENT_QUOTES) ?></td>
                  <td style="padding:10px 8px;"><?= htmlspecialchars((string)$user['status'], ENT_QUOTES) ?></td>
                  <td style="padding:10px 8px; white-space:nowrap;"><?= htmlspecialchars((string)$user['created_at'], ENT_QUOTES) ?></td>
                  <td style="padding:10px 8px;"><?= htmlspecialchars(implode(', ', $user['roles'] ?? []), ENT_QUOTES) ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>
    </div>
  </div>
</main>
