<?php
declare(strict_types=1);

$app = app();
$pdo = $app->pdo();
$userId = $_SESSION['user_id'] ?? null;
$error = '';
$info = '';
$threadId = (int)($_GET['id'] ?? 0);
$editPostId = (int)($_GET['edit_post'] ?? 0);

$communityCfg = require __DIR__ . '/../../../config/community.php';
$community = $pdo ? new \App\Community($pdo, $communityCfg) : null;
$access = $pdo ? new \App\CommunityAccess($pdo, $communityCfg) : null;
$forumCategories = $community ? $community->listForumCategories() : [];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $community && $access) {
    $action = (string)($_POST['action'] ?? '');
    try {
        if ($action === 'reply') {
            if (!$userId) {
                throw new \RuntimeException('Bitte einloggen, um zu antworten.');
            }
            if (!$access->canReply((int)$userId)) {
                $state = $access->getRestrictionState((int)$userId);
                throw new \RuntimeException($state['reason'] ?: 'Du darfst aktuell nicht antworten.');
            }
            $body = trim((string)($_POST['body'] ?? ''));
            if ($body === '') {
                throw new \RuntimeException('Antwort darf nicht leer sein.');
            }
            $community->createPost((int)$userId, $threadId, $body);
            redirect('/community_thread?id=' . $threadId);
        } elseif ($action === 'post_vote') {
            if (!$userId) {
                throw new \RuntimeException('Bitte einloggen, um Beiträge zu bewerten.');
            }
            $access->votePost((int)$userId, (int)($_POST['post_id'] ?? 0), (int)($_POST['value'] ?? 0));
            redirect('/community_thread?id=' . $threadId);
        } elseif ($action === 'report_content') {
            if (!$userId) {
                throw new \RuntimeException('Bitte einloggen, um Beiträge zu melden.');
            }
            $access->submitReport((int)$userId, (string)($_POST['target_type'] ?? ''), (int)($_POST['target_id'] ?? 0), (string)($_POST['reason'] ?? ''));
            $info = 'Deine Meldung wurde eingereicht.';
        } elseif ($action === 'post_update') {
            if (!$userId || !$access->canModerateForum((int)$userId)) {
                throw new \RuntimeException('Keine Berechtigung.');
            }
            $community->updatePost((int)($_POST['post_id'] ?? 0), (string)($_POST['body'] ?? ''));
            redirect('/community_thread?id=' . $threadId);
        } elseif ($action === 'post_delete') {
            if (!$userId || !$access->canModerateForum((int)$userId)) {
                throw new \RuntimeException('Keine Berechtigung.');
            }
            $community->deletePost((int)($_POST['post_id'] ?? 0));
            redirect('/community_thread?id=' . $threadId);
        } elseif ($action === 'thread_update') {
            if (!$userId || !$access->canModerateForum((int)$userId)) {
                throw new \RuntimeException('Keine Berechtigung.');
            }
            $community->updateThread($threadId, (string)($_POST['title'] ?? ''), (string)($_POST['body'] ?? ''));
            redirect('/community_thread?id=' . $threadId);
        } elseif ($action === 'thread_delete') {
            if (!$userId || !$access->canModerateForum((int)$userId)) {
                throw new \RuntimeException('Keine Berechtigung.');
            }
            $community->deleteThread($threadId);
            redirect('/community');
        } elseif ($action === 'highlight_post') {
            if (!$userId) {
                throw new \RuntimeException('Bitte einloggen.');
            }
            $points = $community->computePoints((int)$userId);
            if (!$access->canHighlightHelpful($points) && !$access->canModerateForum((int)$userId)) {
                throw new \RuntimeException('Dafür ist mindestens der Rang Mentor-Vater erforderlich.');
            }
            $postId = (int)($_POST['post_id'] ?? 0);
            $highlight = ((string)($_POST['highlight'] ?? '1')) === '1';
            $community->toggleHelpfulHighlight($postId, $highlight ? (int)$userId : null);
            redirect('/community_thread?id=' . $threadId);
        } elseif ($action === 'restriction_set') {
            $access->setRestriction((int)$userId, (int)($_POST['target_user_id'] ?? 0), (string)($_POST['restriction_type'] ?? ''), (string)($_POST['reason'] ?? ''));
            $info = 'Community-Sperre wurde gesetzt.';
        } elseif ($action === 'restriction_clear') {
            $access->clearRestriction((int)$userId, (int)($_POST['target_user_id'] ?? 0), (string)($_POST['restriction_type'] ?? ''));
            $info = 'Community-Sperre wurde aufgehoben.';
        }
    } catch (\Throwable $e) {
        $error = $e->getMessage();
    }
}

$thread = $community ? $community->getThread($threadId) : null;
$posts = $community ? $community->listPosts($threadId) : [];

if (!$thread) {
    http_response_code(404);
    echo "<p>Thread nicht gefunden.</p>";
    return;
}

$threadAuthor = (string)($thread['display_name'] ?: 'Mitglied');
$threadPoints = ($community && $pdo) ? $community->computePoints((int)$thread['user_id']) : 0.0;
$threadLevel = $community ? $community->membershipLevel($threadPoints) : ['label' => '', 'icon' => ''];
$userRoles = $access && $userId ? $access->getUserRoles((int)$userId) : [];
$isForumAdmin = $access && $userId ? $access->canModerateForum((int)$userId) : false;
$userRestrictions = $access && $userId ? $access->getRestrictionState((int)$userId) : ['reply_blocked' => false, 'reason' => null];
$postIds = array_map(static fn(array $post): int => (int)$post['id'], $posts);
$feedbackSummary = $access ? $access->getPostFeedbackSummary($postIds) : [];
$userVotes = ($access && $userId) ? $access->getUserPostVotes((int)$userId, $postIds) : [];
?>
<main class="section">
  <div class="container">
    <div class="forum-breadcrumbs">
      <a href="/">Home</a>
      <span>/</span>
      <a href="/community">Community</a>
      <?php if (!empty($thread['board_title'])): ?>
        <span>/</span>
        <a href="/community?board=<?= rawurlencode((string)$thread['board_slug']) ?>"><?= htmlspecialchars((string)$thread['board_title'], ENT_QUOTES) ?></a>
      <?php endif; ?>
      <span>/</span>
      <span><?= htmlspecialchars((string)$thread['title'], ENT_QUOTES) ?></span>
    </div>

    <div class="forum-shell">
      <?php
        $sidebarCategories = $forumCategories;
        $sidebarCurrentBoardSlug = (string)($thread['board_slug'] ?? '');
        require __DIR__ . '/sidebar.php';
      ?>
      <div class="forum-shell__main">
        <div class="forum-thread-head">
          <div>
            <h1><?= htmlspecialchars((string)$thread['title'], ENT_QUOTES) ?></h1>
            <p class="forum-thread-head__meta">Erstellt von <?= htmlspecialchars($threadAuthor, ENT_QUOTES) ?> am <?= htmlspecialchars((string)$thread['created_at'], ENT_QUOTES) ?></p>
            <?php if (!empty($thread['board_title'])): ?>
              <p class="muted small" style="margin:8px 0 0;">Bereich: <?= htmlspecialchars((string)$thread['board_title'], ENT_QUOTES) ?></p>
            <?php endif; ?>
          </div>
          <div class="forum-thread-head__meta-box">
            <strong><?= count($posts) ?></strong>
            <span>Antworten</span>
          </div>
        </div>

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

        <article class="forum-post forum-post--lead">
          <aside class="forum-post__author">
            <div class="forum-post__avatar"><?= \App\Avatar\Lorelei::render($thread, $threadAuthor, 'forum') ?></div>
            <strong><?= htmlspecialchars($threadAuthor, ENT_QUOTES) ?></strong>
            <span><?= htmlspecialchars(trim((string)($threadLevel['icon'] ?? '') . ' ' . (string)($threadLevel['label'] ?? '')), ENT_QUOTES) ?></span>
            <span><?= number_format($threadPoints, 1) ?> Punkte</span>
            <?php if ($isForumAdmin): ?>
              <div class="forum-post__admin">
                <button class="btn ghost" type="button" data-modal-open="modalThreadEdit">Thema bearbeiten</button>
                <form method="post" onsubmit="return confirm('Thema wirklich löschen?');">
                  <input type="hidden" name="action" value="thread_delete">
                  <button class="btn ghost" type="submit">Thema löschen</button>
                </form>
              </div>
            <?php endif; ?>
          </aside>
          <div class="forum-post__body">
            <div class="forum-post__head">
              <span><?= htmlspecialchars((string)$thread['created_at'], ENT_QUOTES) ?></span>
              <span>#1</span>
            </div>
            <div class="forum-post__content">
              <?= nl2br(htmlspecialchars((string)$thread['body'], ENT_QUOTES)) ?>
            </div>
            <?php if ($userId && $access && $access->supportsReports()): ?>
              <form method="post" class="forum-inline-report">
                <input type="hidden" name="action" value="report_content">
                <input type="hidden" name="target_type" value="thread">
                <input type="hidden" name="target_id" value="<?= (int)$thread['id'] ?>">
                <input type="hidden" name="reason" value="Thread benötigt Moderation oder Prüfung.">
                <button class="btn ghost" type="submit">Thema melden</button>
              </form>
            <?php endif; ?>
          </div>
        </article>

        <div class="forum-replies-head">
          <h2>Antworten</h2>
          <span><?= count($posts) ?> Beitrag/Beiträge</span>
        </div>

        <div class="forum-replies">
          <?php foreach ($posts as $index => $p): ?>
            <?php
              $postAuthor = (string)($p['display_name'] ?: 'Mitglied');
              $summary = $feedbackSummary[(int)$p['id']] ?? ['helpful' => 0, 'unhelpful' => 0];
              $userVote = $userVotes[(int)$p['id']] ?? 0;
              $isHighlighted = !empty($p['highlighted_at']);
            ?>
            <article class="forum-post<?= $isHighlighted ? ' forum-post--highlighted' : '' ?>">
              <aside class="forum-post__author">
                <div class="forum-post__avatar"><?= \App\Avatar\Lorelei::render($p, $postAuthor, 'forum') ?></div>
                <strong><?= htmlspecialchars($postAuthor, ENT_QUOTES) ?></strong>
                <?php if ($isHighlighted): ?>
                  <span class="forum-highlight-badge">Hilfreich hervorgehoben</span>
                <?php endif; ?>
                <?php if ($isForumAdmin && $access && $access->supportsRestrictions()): ?>
                  <form method="post" class="forum-admin-mini-form">
                    <input type="hidden" name="action" value="restriction_set">
                    <input type="hidden" name="target_user_id" value="<?= (int)$p['user_id'] ?>">
                    <input type="hidden" name="restriction_type" value="reply_blocked">
                    <input type="hidden" name="reason" value="Antworten in der Community vorübergehend gesperrt.">
                    <button class="btn ghost" type="submit">Antworten sperren</button>
                  </form>
                <?php endif; ?>
              </aside>
              <div class="forum-post__body">
                <div class="forum-post__head">
                  <span><?= htmlspecialchars((string)$p['created_at'], ENT_QUOTES) ?></span>
                  <span>#<?= $index + 2 ?></span>
                </div>
                <div class="forum-post__content">
                  <?php if ($editPostId === (int)$p['id'] && $isForumAdmin): ?>
                    <form method="post" class="stack gap-10">
                      <input type="hidden" name="action" value="post_update">
                      <input type="hidden" name="post_id" value="<?= (int)$p['id'] ?>">
                      <textarea name="body" class="textarea" rows="6" required><?= htmlspecialchars((string)$p['body'], ENT_QUOTES) ?></textarea>
                      <div class="flex gap-12">
                        <button class="btn" type="submit">Änderung speichern</button>
                        <a class="btn ghost" href="/community_thread?id=<?= $threadId ?>">Abbrechen</a>
                      </div>
                    </form>
                  <?php else: ?>
                    <?= nl2br(htmlspecialchars((string)$p['body'], ENT_QUOTES)) ?>
                  <?php endif; ?>
                </div>

                <div class="forum-post__toolbar">
                  <?php if ($userId && $access && $access->supportsFeedback()): ?>
                    <form method="post">
                      <input type="hidden" name="action" value="post_vote">
                      <input type="hidden" name="post_id" value="<?= (int)$p['id'] ?>">
                      <input type="hidden" name="value" value="1">
                      <button class="btn ghost<?= $userVote === 1 ? ' is-active' : '' ?>" type="submit">Hilfreich (<?= (int)$summary['helpful'] ?>)</button>
                    </form>
                    <form method="post">
                      <input type="hidden" name="action" value="post_vote">
                      <input type="hidden" name="post_id" value="<?= (int)$p['id'] ?>">
                      <input type="hidden" name="value" value="-1">
                      <button class="btn ghost<?= $userVote === -1 ? ' is-active' : '' ?>" type="submit">Nicht hilfreich (<?= (int)$summary['unhelpful'] ?>)</button>
                    </form>
                  <?php endif; ?>
                  <?php if ($userId && $access && $access->supportsReports()): ?>
                    <form method="post">
                      <input type="hidden" name="action" value="report_content">
                      <input type="hidden" name="target_type" value="post">
                      <input type="hidden" name="target_id" value="<?= (int)$p['id'] ?>">
                      <input type="hidden" name="reason" value="Beitrag benötigt Moderation oder Prüfung.">
                      <button class="btn ghost" type="submit">Melden</button>
                    </form>
                  <?php endif; ?>

                  <?php if ($userId && $access && $access->canHighlightHelpful($community->computePoints((int)$userId))): ?>
                    <form method="post">
                      <input type="hidden" name="action" value="highlight_post">
                      <input type="hidden" name="post_id" value="<?= (int)$p['id'] ?>">
                      <input type="hidden" name="highlight" value="<?= $isHighlighted ? '0' : '1' ?>">
                      <button class="btn ghost" type="submit"><?= $isHighlighted ? 'Hervorhebung entfernen' : 'Als hilfreich hervorheben' ?></button>
                    </form>
                  <?php endif; ?>

                  <?php if ($isForumAdmin): ?>
                    <a class="btn ghost" href="/community_thread?id=<?= $threadId ?>&edit_post=<?= (int)$p['id'] ?>">Bearbeiten</a>
                    <form method="post" onsubmit="return confirm('Beitrag wirklich löschen?');">
                      <input type="hidden" name="action" value="post_delete">
                      <input type="hidden" name="post_id" value="<?= (int)$p['id'] ?>">
                      <button class="btn ghost" type="submit">Löschen</button>
                    </form>
                  <?php endif; ?>
                </div>
              </div>
            </article>
          <?php endforeach; ?>
          <?php if (!$posts): ?>
            <div class="forum-empty">Noch keine Antworten.</div>
          <?php endif; ?>
        </div>

        <?php if ($userId): ?>
          <?php if ($userRestrictions['reply_blocked']): ?>
            <div class="forum-login-note">Du darfst aktuell keine Antworten schreiben. <?= !empty($userRestrictions['reason']) ? htmlspecialchars((string)$userRestrictions['reason'], ENT_QUOTES) : '' ?></div>
          <?php else: ?>
            <form method="post" class="forum-reply-form">
              <input type="hidden" name="action" value="reply">
              <div class="stack gap-6">
                <label class="label" for="replyBody">Antwort</label>
                <textarea id="replyBody" name="body" class="textarea" rows="4" required></textarea>
              </div>
              <button class="btn" type="submit">Antwort senden</button>
            </form>
          <?php endif; ?>
        <?php else: ?>
          <div class="forum-login-note">Bitte <a href="/login">einloggen</a>, um zu antworten.</div>
        <?php endif; ?>
      </div>
    </div>
  </div>
</main>

<?php if ($isForumAdmin): ?>
<div class="modal" id="modalThreadEdit">
  <div class="panel">
    <div class="head flex between center-y">
      <h3 style="margin:0;">Thema bearbeiten</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_update">
      <div class="stack gap-6">
        <label class="label" for="threadTitleEdit">Titel</label>
        <input id="threadTitleEdit" name="title" class="input" value="<?= htmlspecialchars((string)$thread['title'], ENT_QUOTES) ?>" required>
      </div>
      <div class="stack gap-6">
        <label class="label" for="threadBodyEdit">Text</label>
        <textarea id="threadBodyEdit" name="body" class="textarea" rows="8" required><?= htmlspecialchars((string)$thread['body'], ENT_QUOTES) ?></textarea>
      </div>
      <div class="flex gap-12">
        <button class="btn ghost" type="button" data-modal-close>Abbrechen</button>
        <button class="btn" type="submit">Speichern</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>
