<?php
declare(strict_types=1);

$app = app();
$pdo = $app->pdo();
$userId = $_SESSION['user_id'] ?? null;
$error = '';
$search = trim((string)($_GET['q'] ?? ''));

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'thread_create') {
    if (!$userId) {
        $error = 'Bitte einloggen, um Fragen zu stellen.';
    } elseif ($community) {
        $title = trim((string)($_POST['title'] ?? ''));
        $body  = trim((string)($_POST['body'] ?? ''));
        if ($title === '' || $body === '') {
            $error = 'Titel und Text sind erforderlich.';
        } else {
            $community->createThread((int)$userId, $title, $body);
            redirect('/community');
        }
    }
}

$threads = $community ? ($search !== '' ? $community->searchThreads($search, 50) : $community->listThreads(50)) : [];
?>
<main class="section">
  <div class="container">
    <p class="eyebrow">Community</p>
    <h1>Forum</h1>
    <?php if ($error): ?>
      <div class="toast-bar" style="border-color:#f87171; color:#991b1b;"><?= htmlspecialchars($error, ENT_QUOTES) ?></div>
    <?php endif; ?>

    <div class="flex between center-y" style="margin:14px 0; gap:12px; flex-wrap:wrap;">
      <form method="get" class="flex gap-8" style="flex-wrap:wrap; align-items:flex-end;">
        <div class="stack gap-4">
          <label class="label" for="searchQ">Suche nach Stichwort</label>
          <input id="searchQ" name="q" class="input" value="<?= htmlspecialchars($search, ENT_QUOTES) ?>" placeholder="Schlagwort eingeben">
        </div>
        <button class="btn" type="submit">Suchen</button>
      </form>
      <?php if ($userId): ?>
        <button class="btn" type="button" data-modal-open="modalThread">Neue Frage</button>
      <?php else: ?>
        <a class="btn ghost" href="/login">Login für neue Frage</a>
      <?php endif; ?>
    </div>

    <div class="stack gap-8" style="margin-top:10px;">
      <?php foreach ($threads as $t): ?>
        <?php
          $pts = ($community && $pdo) ? $community->computePoints((int)$t['uid']) : 0.0;
          $lvl = $community ? $community->membershipLevel($pts) : ['label'=>'','icon'=>''];
        ?>
        <article class="card" style="padding:14px;">
          <div class="event__body">
            <div class="event__meta" style="flex-wrap:wrap; gap:8px;">
              <span><?= htmlspecialchars($t['created_at'], ENT_QUOTES) ?></span>
              <span><?= htmlspecialchars($t['display_name'] ?: 'Mitglied', ENT_QUOTES) ?></span>
              <span><?= htmlspecialchars($lvl['icon'] ?? '', ENT_QUOTES) ?> <?= htmlspecialchars($lvl['label'] ?? '', ENT_QUOTES) ?> (<?= number_format($pts,1) ?> Punkte)</span>
              <span>Beiträge: <?= (int)$t['user_posts'] + (int)$t['answers'] ?></span>
              <span>Antworten: <?= (int)$t['answers'] ?></span>
            </div>
            <h3 style="margin:6px 0;"><a href="/community_thread?id=<?= (int)$t['id'] ?>"><?= htmlspecialchars($t['title'], ENT_QUOTES) ?></a></h3>
            <p class="muted small"><?= nl2br(htmlspecialchars(substr($t['body'], 0, 200), ENT_QUOTES)) ?><?= strlen($t['body']) > 200 ? '…' : '' ?></p>
          </div>
        </article>
      <?php endforeach; ?>
      <?php if (!$threads): ?>
        <p class="muted">Keine Treffer.</p>
      <?php endif; ?>
    </div>
  </div>
</main>

<?php if ($userId): ?>
<div class="modal" id="modalThread">
  <div class="panel">
    <div class="head flex between center-y">
      <h3 style="margin:0;">Neue Frage</h3>
      <button class="btn ghost" type="button" data-modal-close>✕</button>
    </div>
    <form method="post" class="stack gap-10" style="margin-top:12px;">
      <input type="hidden" name="action" value="thread_create">
      <div class="stack gap-6">
        <label class="label" for="fTitleModal">Frage/Titel</label>
        <input id="fTitleModal" name="title" class="input" required>
      </div>
      <div class="stack gap-6">
        <label class="label" for="fBodyModal">Text</label>
        <textarea id="fBodyModal" name="body" class="textarea" rows="4" required></textarea>
      </div>
      <div class="flex gap-12" style="flex-wrap:wrap;">
        <button class="btn ghost" type="button" data-modal-close>Abbrechen</button>
        <button class="btn" type="submit">Frage erstellen</button>
      </div>
    </form>
  </div>
</div>
<?php endif; ?>

<script>
  document.querySelectorAll('[data-modal-open]').forEach(btn => {
    btn.addEventListener('click', () => {
      const id = btn.getAttribute('data-modal-open');
      const modal = document.getElementById(id);
      if (modal) modal.classList.add('open');
    });
  });
  document.querySelectorAll('[data-modal-close]').forEach(btn => {
    btn.addEventListener('click', () => {
      const modal = btn.closest('.modal');
      if (modal) modal.classList.remove('open');
    });
  });
  document.querySelectorAll('.modal').forEach(modal => {
    modal.addEventListener('click', (e) => {
      if (e.target === modal) modal.classList.remove('open');
    });
  });
</script>
