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


$file = __DIR__ . '/../data/comments.txt';
$settingsFile = __DIR__ . '/../data/settings.json';
$settings = smurf_load_settings($settingsFile);

$repliesFile = __DIR__ . '/../data/comment_replies.json';
$replies = smurf_read_json($repliesFile, []);

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['moderation_action'])) {
  if (!$CAN_EDIT) die("<h1>Access Denied</h1><p>You do not have permission.</p>");
  $mAction = (string)($_POST['moderation_action'] ?? '');
  $mIndex = (int)($_POST['moderation_index'] ?? -1);

  if ($mAction === 'delete' && $mIndex >= 0) {
    $itemsNewest = smurf_parse_blocks($file);
    if (isset($itemsNewest[$mIndex])) {
      $deleteKey = smurf_entry_stable_key($itemsNewest[$mIndex]);
      unset($replies[$deleteKey]);
      smurf_write_json($repliesFile, $replies);
    }
    smurf_delete_block($file, $mIndex);
    smurf_redirect_self(['saved'=>1], ['action','i']);
  }

  if ($mAction === 'approve' || $mAction === 'unapprove') {
    $itemsNewest = smurf_parse_blocks($file);
    if (isset($itemsNewest[$mIndex])) {
      $raw = $itemsNewest[$mIndex]['_raw'] ?? '';
      $raw2 = preg_replace('/^Approved\s*:\s*.*$/mi', '', $raw);
      $raw2 = trim($raw2);
      $raw2 .= "\nApproved: " . ($mAction === 'approve' ? '1' : '0');
      smurf_update_block($file, $mIndex, $raw2);
    }
    smurf_redirect_self(['saved'=>1], ['action','i']);
  }

  if ($mAction === 'clear') {
    smurf_clear_file($file);
    smurf_redirect_self(['saved'=>1], ['action','i']);
  }
}

// Toggle comments enabled/disabled
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_comments'])) {
  if (!$CAN_EDIT) die("<h1>Access Denied</h1>");
  $settings['comments_enabled'] = isset($_POST['comments_enabled']) ? true : false;
  smurf_save_settings($settingsFile, $settings);
  smurf_redirect_self(['saved'=>1], ['action','i']);
}

// Save a reply (stored by hash of the comment block)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reply_key'])) {
  if (!$CAN_EDIT) die("<h1>Access Denied</h1><p>You do not have permission to reply.</p>");
  $key = preg_replace('/[^a-f0-9]/', '', (string)($_POST['reply_key'] ?? ''));
  $reply = trim((string)($_POST['reply_text'] ?? ''));
  if ($key !== '') {
    if ($reply === '') {
      unset($replies[$key]);
    } else {
      $replies[$key] = [
        'text' => $reply,
        'by'   => $_SESSION['user'] ?? 'admin',
        'ts'   => time(),
      ];
    }
    smurf_write_json($repliesFile, $replies);
  }
  smurf_redirect_self(['saved'=>1], ['action','i']);
}

$items = smurf_parse_blocks($file);

function smurf_comment_key(array $item): string {
  return smurf_entry_stable_key($item);
}

function smurf_is_approved(array $item): bool {
  $v = $item['Approved'] ?? $item['approved'] ?? '';
  return (string)$v === '1' || strtolower((string)$v) === 'yes' || strtolower((string)$v) === 'true';
}
include __DIR__ . '/includes/admin_header.php';
?>

<section class="content-card">
  <div style="display:flex;justify-content:space-between;align-items:center;gap:10px;">
    <h1 class="admin-title" style="margin:0;">💬 Comments</h1>
    <a class="admin-btn" href="/admin/index.php">Back</a>
  </div>

  <p style="opacity:.8;">File: <code>/data/comments.txt</code></p>

  <?php if (!empty($_GET['saved'])): ?>
    <div class="msg success" style="margin-top:10px;">Saved.</div>
  <?php endif; ?>

  <div class="content-card" style="text-align:left;margin-top:12px;">
    <h3 style="margin-top:0;">Settings</h3>
    <form method="post" style="display:flex;gap:12px;align-items:center;flex-wrap:wrap;">
      <input type="hidden" name="toggle_comments" value="1">
      <label style="display:flex;gap:8px;align-items:center;">
        <input type="checkbox" name="comments_enabled" value="1" <?= !empty($settings['comments_enabled']) ? 'checked' : '' ?>>
        <span>Allow new comments on the homepage</span>
      </label>
      <?php if ($CAN_EDIT): ?>
        <button class="admin-btn" type="submit">Save</button>
      <?php endif; ?>
      <div style="opacity:.8;">Tip: turn this off if you get spammed.</div>
    </form>
  </div>

  <div style="margin:10px 0 18px;">
    <?php if ($CAN_EDIT): ?>
      <form method="post" style="display:inline;" onsubmit="return confirm('Clear ALL entries?');">
        <input type="hidden" name="moderation_action" value="clear">
        <button class="admin-btn" type="submit">Clear All</button>
      </form>
    <?php endif; ?>
  </div>

  <?php if (empty($items)): ?>
    <p>No entries yet.</p>
  <?php else: ?>
    <?php foreach ($items as $i => $item): ?>
      <?php
        $approved = smurf_is_approved($item);
        $key = smurf_comment_key($item);
        $reply = $replies[$key]['text'] ?? '';
      ?>
      <div class="content-card" style="text-align:left;">
        <div style="display:flex;justify-content:space-between;gap:10px;align-items:center;flex-wrap:wrap;">
          <strong>#<?= $i ?></strong>
          <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
            <span style="font-weight:700;<?= $approved ? 'color:#7CFFB5' : 'color:#ffd27a' ?>;">
              <?= $approved ? 'Approved' : 'Pending' ?>
            </span>

            <?php if ($CAN_EDIT): ?>
              <?php if (!$approved): ?>
                <form method="post" style="display:inline;">
                  <input type="hidden" name="moderation_action" value="approve">
                  <input type="hidden" name="moderation_index" value="<?= $i ?>">
                  <button class="admin-btn" type="submit">Approve</button>
                </form>
              <?php else: ?>
                <form method="post" style="display:inline;">
                  <input type="hidden" name="moderation_action" value="unapprove">
                  <input type="hidden" name="moderation_index" value="<?= $i ?>">
                  <button class="admin-btn" type="submit">Unapprove</button>
                </form>
              <?php endif; ?>
              <form method="post" style="display:inline;" onsubmit="return confirm('Delete this entry?');">
                <input type="hidden" name="moderation_action" value="delete">
                <input type="hidden" name="moderation_index" value="<?= $i ?>">
                <button class="admin-btn" type="submit">Delete</button>
              </form>
            <?php endif; ?>
          </div>
        </div>

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

        <div style="margin-top:12px;">
          <h4 style="margin:0 0 6px;">Admin Reply</h4>
          <?php if (!empty($reply)): ?>
            <div class="content-card" style="margin:8px 0 10px;border-style:dashed;">
              <?= nl2br(smurf_h($reply)) ?>
            </div>
          <?php endif; ?>

          <?php if ($CAN_EDIT): ?>
            <form method="post">
              <input type="hidden" name="reply_key" value="<?= smurf_h($key) ?>">
              <textarea class="request-textarea" name="reply_text" rows="3" style="width:100%;max-width:100%;background:rgba(0,0,0,.35);color:#f7efe4;"><?= smurf_h($reply) ?></textarea>
              <div style="display:flex;gap:10px;justify-content:flex-end;margin-top:8px;flex-wrap:wrap;">
                <button class="admin-btn" type="submit">Save Reply</button>
                <span style="opacity:.75;">(leave blank and save to remove)</span>
              </div>
            </form>
          <?php else: ?>
            <p style="opacity:.8;">You do not have permission to reply.</p>
          <?php endif; ?>
        </div>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>
</section>

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