<?php include '../includes/header.php'; ?>

<!-- Apply content-box styling to center content -->
<div class="py-5">
  <div class="container content-box">

    <h2 class="mb-4 text-center">🛠️ Moderate Comments</h2>

    <?php
    $commentsFile = '../comments.txt';
    if (file_exists($commentsFile)) {
      $allComments = explode("---\n", file_get_contents($commentsFile));
      $recent = array_reverse($allComments);

      foreach ($recent as $entry) {
        $lines = explode("\n", trim($entry));
        $reply = '';
        $content = [];

        foreach ($lines as $line) {
          if (str_starts_with($line, 'Reply:')) {
            $reply = substr($line, 7);
          } else {
            $content[] = $line;
          }
        }

        echo "<div class='mb-4 border-bottom pb-3'>";
        echo "<p>" . nl2br(htmlspecialchars(implode("\n", $content))) . "</p>";

        if ($reply) {
          echo "<div class='bg-white border rounded p-2 mt-2'><strong>Reply:</strong> " . htmlspecialchars($reply) . "</div>";
        }

        // Reply form
        echo "<form method='POST' action='save-reply.php' class='mt-3'>";
        echo "<input type='hidden' name='original' value='" . htmlspecialchars(implode("\n", $content)) . "'>";
        echo "<textarea name='reply' class='form-control mb-2' placeholder='Write a reply...' required></textarea>";
        echo "<button type='submit' class='btn btn-primary'>Reply</button>";
        echo "</form>";
        echo "</div>";
      }
    } else {
      echo "<p>No comments found.</p>";
    }
    ?>

  </div>
</div>

<?php include '../includes/footer.php'; ?>
