<?php
declare(strict_types=1);

$app = app();
$pdo = $app->pdo();
$userId = $_SESSION['user_id'] ?? null;

if (!$userId) {
    redirect('/login');
}

$communityCfg = require __DIR__ . '/../../../config/community.php';
$access = $pdo ? new \App\CommunityAccess($pdo, $communityCfg) : null;
$migration = $pdo ? new \App\CommunityMigration($pdo) : null;

if (!$access || !$access->canModerateForum((int)$userId)) {
    http_response_code(403);
    echo '<main class="section"><div class="container"><div class="card dash-card"><h1>Kein Zugriff</h1><p class="muted">Dieser Bereich ist nur für Community-Admins freigegeben.</p></div></div></main>';
    return;
}

$error = '';
$info = '';
$canManageApplications = $access->canManageApplications((int)$userId) && $access->supportsApplications();
$canManageRoles = $access->canManageRoles((int)$userId);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? '');
    try {
        if ($action === 'application_decide') {
            $access->decideApplication((int)$userId, (int)($_POST['application_id'] ?? 0), (string)($_POST['decision'] ?? ''), (string)($_POST['decision_reason'] ?? ''));
            $info = 'Bewerbung wurde bearbeitet.';
        } elseif ($action === 'report_resolve') {
            $access->resolveReport((int)$userId, (int)($_POST['report_id'] ?? 0), (string)($_POST['moderator_note'] ?? ''));
            $info = 'Meldung wurde abgeschlossen.';
        } elseif ($action === 'role_revoke') {
            $access->revokeRole((int)$userId, (int)($_POST['target_user_id'] ?? 0), (string)($_POST['role'] ?? ''));
            $info = 'Rolle wurde entzogen.';
        } elseif ($action === 'role_assign') {
            $access->assignRole((int)$userId, (int)($_POST['target_user_id'] ?? 0), (string)($_POST['role'] ?? ''));
            $info = 'Rolle wurde vergeben.';
        } elseif ($action === 'community_migrate') {
            if (!$canManageApplications || !$migration) {
                throw new \RuntimeException('Keine Berechtigung für die Community-Migration.');
            }
            $migration->apply();
            $info = 'Die Community-Migration wurde ausgeführt.';
        }
    } catch (\Throwable $e) {
        $error = $e->getMessage();
    }
}

$applications = $canManageApplications ? $access->listApplications('open') : [];
$reports = $access->supportsReports() ? $access->listOpenReports() : [];
$roleAssignments = $canManageRoles ? $access->listRoleAssignments() : [];
$migrationStatus = ($migration && $canManageApplications) ? $migration->status() : null;
?>
<main class="section">
  <div class="container">
    <div class="forum-breadcrumbs">
      <a href="/">Home</a>
      <span>/</span>
      <a href="/dashboard">Mitgliederbereich</a>
      <span>/</span>
      <span>Community-Admin</span>
    </div>

    <div class="forum-hero forum-hero--compact">
      <div>
        <h1>Community-Admin</h1>
        <p class="forum-hero__copy">Moderation, Bewerbungen und Rollen an einem Ort.</p>
      </div>
      <div class="forum-hero__cta">
        <a class="btn ghost" href="/dashboard">Zurück zum Mitgliederbereich</a>
      </div>
    </div>

    <?php if ($error): ?>
      <div class="toast-bar" style="margin-top:14px; border-color:#f87171; color:#991b1b;"><?= htmlspecialchars($error, ENT_QUOTES) ?></div>
    <?php endif; ?>
    <?php if ($info): ?>
      <div class="toast-bar" style="margin-top:14px;"><?= htmlspecialchars($info, ENT_QUOTES) ?></div>
    <?php endif; ?>

    <div class="forum-admin-grid">
      <?php if ($canManageApplications): ?>
        <section class="forum-board">
          <div class="forum-board__head">
            <div>
              <h2>Offene Bewerbungen</h2>
              <p class="muted">Bewerbungen für die Forum-Moderation prüfen.</p>
            </div>
          </div>
          <div class="forum-admin-list">
            <?php foreach ($applications as $application): ?>
              <article class="forum-admin-item">
                <div>
                  <strong><?= htmlspecialchars((string)($application['display_name'] ?: $application['email']), ENT_QUOTES) ?></strong>
                  <p><?= nl2br(htmlspecialchars((string)$application['motivation'], ENT_QUOTES)) ?></p>
                </div>
                <form method="post" class="forum-admin-item__actions">
                  <input type="hidden" name="action" value="application_decide">
                  <input type="hidden" name="application_id" value="<?= (int)$application['id'] ?>">
                  <textarea name="decision_reason" class="textarea" rows="3" placeholder="Begründung"></textarea>
                  <div class="flex gap-12">
                    <button class="btn" type="submit" name="decision" value="approved">Annehmen</button>
                    <button class="btn ghost" type="submit" name="decision" value="rejected">Ablehnen</button>
                  </div>
                </form>
              </article>
            <?php endforeach; ?>
            <?php if (!$applications): ?>
              <div class="forum-empty">Keine offenen Bewerbungen.</div>
            <?php endif; ?>
          </div>
        </section>
      <?php endif; ?>

      <section class="forum-board">
        <div class="forum-board__head">
          <div>
            <h2>Offene Meldungen</h2>
            <p class="muted">Gemeldete Inhalte prüfen und abschließen.</p>
          </div>
        </div>
        <div class="forum-admin-list">
          <?php foreach ($reports as $report): ?>
            <article class="forum-admin-item">
              <div>
                <strong><?= htmlspecialchars((string)$report['target_type'], ENT_QUOTES) ?> #<?= (int)$report['target_id'] ?></strong>
                <p><?= nl2br(htmlspecialchars((string)$report['reason'], ENT_QUOTES)) ?></p>
                <p class="muted small">Gemeldet von <?= htmlspecialchars((string)($report['reporter_name'] ?: 'Mitglied'), ENT_QUOTES) ?> am <?= htmlspecialchars((string)$report['created_at'], ENT_QUOTES) ?></p>
              </div>
              <form method="post" class="forum-admin-item__actions">
                <input type="hidden" name="action" value="report_resolve">
                <input type="hidden" name="report_id" value="<?= (int)$report['id'] ?>">
                <textarea name="moderator_note" class="textarea" rows="3" placeholder="Moderationsnotiz"></textarea>
                <button class="btn" type="submit">Als erledigt markieren</button>
              </form>
            </article>
          <?php endforeach; ?>
          <?php if (!$reports): ?>
            <div class="forum-empty">Keine offenen Meldungen.</div>
          <?php endif; ?>
        </div>
      </section>

      <?php if ($canManageRoles): ?>
        <section class="forum-board">
          <div class="forum-board__head">
            <div>
              <h2>Rollen verwalten</h2>
              <p class="muted">Community-Rollen vergeben und entziehen.</p>
            </div>
          </div>
          <div style="padding:24px; border-bottom:1px solid var(--color-border);">
            <form method="post" class="form-grid single">
              <input type="hidden" name="action" value="role_assign">
              <div class="stack gap-6">
                <label class="label" for="adminTargetUserId">Benutzer-ID</label>
                <input id="adminTargetUserId" name="target_user_id" class="input" type="number" min="1" required>
              </div>
              <div class="stack gap-6">
                <label class="label" for="adminRole">Rolle</label>
                <select id="adminRole" name="role" class="select">
                  <option value="forum_admin">forum_admin</option>
                  <option value="site_admin">site_admin</option>
                  <option value="owner">owner</option>
                </select>
              </div>
              <div>
                <button class="btn" type="submit">Rolle vergeben</button>
              </div>
            </form>
          </div>
          <div class="forum-admin-list">
            <?php foreach ($roleAssignments as $assignment): ?>
              <article class="forum-admin-item">
                <div>
                  <strong><?= htmlspecialchars((string)($assignment['display_name'] ?: $assignment['email']), ENT_QUOTES) ?></strong>
                  <p class="muted small">Rolle: <?= htmlspecialchars((string)$assignment['role'], ENT_QUOTES) ?> · seit <?= htmlspecialchars((string)$assignment['assigned_at'], ENT_QUOTES) ?></p>
                </div>
                <form method="post">
                  <input type="hidden" name="action" value="role_revoke">
                  <input type="hidden" name="target_user_id" value="<?= (int)$assignment['user_id'] ?>">
                  <input type="hidden" name="role" value="<?= htmlspecialchars((string)$assignment['role'], ENT_QUOTES) ?>">
                  <button class="btn ghost" type="submit">Rolle entziehen</button>
                </form>
              </article>
            <?php endforeach; ?>
            <?php if (!$roleAssignments): ?>
              <div class="forum-empty">Keine Rollen vergeben.</div>
            <?php endif; ?>
          </div>
        </section>
      <?php endif; ?>

      <?php if ($canManageApplications && $migrationStatus): ?>
        <section class="forum-board">
          <div class="forum-board__head">
            <div>
              <h2>Migration</h2>
              <p class="muted">Status der Community-Datenbank prüfen.</p>
            </div>
          </div>
          <div style="padding:24px;">
            <ul class="dash-list">
              <li>Status: <?= !empty($migrationStatus['complete']) ? 'Vollständig eingerichtet' : 'Migration noch offen' ?></li>
              <li>Fehlende Bausteine: <?= !empty($migrationStatus['missing']) ? htmlspecialchars(implode(', ', $migrationStatus['missing']), ENT_QUOTES) : 'Keine' ?></li>
            </ul>
            <form method="post" style="margin-top:14px;">
              <input type="hidden" name="action" value="community_migrate">
              <button class="btn" type="submit">Community-Migration ausführen</button>
            </form>
          </div>
        </section>
      <?php endif; ?>
    </div>
  </div>
</main>
