<?php
session_start();
require __DIR__ . '/includes/admin_lib.php';
include __DIR__ . '/includes/admin_header.php';

$file = __DIR__ . '/../data/comments.txt';

$action = $_GET['action'] ?? '';
$idx = isset($_GET['i']) ? (int)$_GET['i'] : -1;

if ($action === 'delete' && $idx >= 0) {
  if (!$CAN_EDIT) die("<h1>Access Denied</h1><p>You do not have permission to delete entries.</p>");
  smurf_delete_block($file, $idx);
  header("Location: /admin/comments.php");
  exit;
}

if ($action === 'clear') {
  if (!$CAN_EDIT) die("<h1>Access Denied</h1><p>You do not have permission to clear entries.</p>");
  smurf_clear_file($file);
  header("Location: /admin/comments.php");
  exit;
}

$items = smurf_parse_blocks($file);
?>
<section class="content-card">
  <h1 class="admin-title">💬 Comments</h1>
  <p style="opacity:.8;">File: <code>/data/comments.txt</code></p>

  <div style="margin:10px 0 18px;">
    <?php if ($CAN_EDIT): ?>
      <a class="admin-btn" href="/admin/comments.php?action=clear" onclick="return confirm('Clear ALL entries?');">Clear All</a>
    <?php endif; ?>
    <a class="admin-btn" href="/admin/index.php">Back</a>
  </div>

  <div class="content-card" style="text-align:left;">
    <h3 style="margin-top:0;">Expected format (from site forms)</h3>
    <pre style="white-space:pre-wrap;opacity:.9;margin:0;">Name: ...\nComment: ...\n---</pre>
  </div>

  <?php if (empty($items)): ?>
    <p>No entries yet.</p>
  <?php else: ?>
    <?php foreach ($items as $i => $item): ?>
      <div class="content-card" style="text-align:left;">
        <div style="display:flex;justify-content:space-between;gap:10px;align-items:center;">
          <strong>#<?= $i ?></strong>
          <?php if ($CAN_EDIT): ?>
            <a class="admin-btn" href="/admin/comments.php?action=delete&i=<?= $i ?>" onclick="return confirm('Delete this entry?');">Delete</a>
          <?php endif; ?>
        </div>

        <pre style="white-space:pre-wrap;margin:10px 0 0;opacity:.95;"><?= smurf_h($item['_raw'] ?? '') ?></pre>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>
</section>

<?php include __DIR__ . '/includes/admin_footer.php'; ?>
