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

$file = __DIR__ . '/../data/comments.txt';
$bannedFile = __DIR__ . '/../data/banned_ips.txt';
$settingsFile = __DIR__ . '/../data/settings.json';
$settings = smurf_load_settings($settingsFile);
$repliesFile = __DIR__ . '/../data/comment_replies.json';
$replies = smurf_read_json($repliesFile, []);

function almostheaven_parse_comments(string $file): array {
  if (!file_exists($file) || filesize($file) === 0) return [];
  $raw = trim((string)file_get_contents($file));
  if ($raw === '') return [];
  if (strpos($raw, '---') !== false && preg_match('/(^|\n)\w+\s*:/', $raw)) {
    $items = [];
    foreach (smurf_parse_blocks($file) as $item) {
      $name = trim((string)($item['Name'] ?? ''));
      $msg = trim((string)($item['Message'] ?? ''));
      if ($name === '' && $msg === '') continue;
      $item['_key'] = smurf_entry_stable_key($item);
      $items[] = $item;
    }
    return $items;
  }
  $lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
  $out = [];
  foreach (array_reverse($lines) as $line) {
    $p = explode('|', trim($line));
    if (count($p) < 6) continue;
    [$id,$name,$message,$ip,$timestamp,$approved] = array_pad($p, 6, '');
    if (trim($name) === '' && trim($message) === '') continue;
    $rawBlock = "ID: $id\nName: $name\nMessage: $message\nIP: $ip\nTimestamp: $timestamp\nApproved: " . (($approved==='yes'||$approved==='1') ? '1' : '0');
    $item = ['ID'=>$id,'Name'=>$name,'Message'=>$message,'IP'=>$ip,'Timestamp'=>$timestamp,'Approved'=>($approved==='yes'||$approved==='1') ? '1' : '0','_raw'=>$rawBlock,'_legacy_line'=>$line];
    $item['_key'] = md5($id . '|' . $name . '|' . $timestamp . '|' . $message);
    $out[] = $item;
  }
  return $out;
}
function almostheaven_write_comments(string $file, array $items): void {
  $legacy = true;
  foreach ($items as $it) { if (!isset($it['_legacy_line'])) { $legacy = false; break; } }
  if ($legacy) {
    $lines = [];
    foreach (array_reverse($items) as $it) {
      $id = $it['ID'] ?? '';
      $name = str_replace(["\n", "\r", "|"], ' ', (string)($it['Name'] ?? ''));
      $msg = str_replace(["\n", "\r", "|"], ' ', (string)($it['Message'] ?? ''));
      $ip = str_replace('|', ' ', (string)($it['IP'] ?? ''));
      $ts = str_replace('|', ' ', (string)($it['Timestamp'] ?? ''));
      $ap = (($it['Approved'] ?? '0') === '1') ? 'yes' : 'no';
      $lines[] = "$id|$name|$msg|$ip|$ts|$ap";
    }
    file_put_contents($file, implode("\n", $lines) . (count($lines) ? "\n" : ''), LOCK_EX);
    return;
  }
  $blocks = [];
  foreach (array_reverse($items) as $it) { $raw = trim((string)($it['_raw'] ?? '')); if ($raw !== '') $blocks[] = $raw; }
  file_put_contents($file, $blocks ? implode("\n---\n", $blocks) . "\n---\n" : '', LOCK_EX);
}
function almostheaven_comment_approved(array $item): bool {
  $v = $item['Approved'] ?? $item['approved'] ?? '';
  return (string)$v === '1' || strtolower((string)$v) === 'yes' || strtolower((string)$v) === 'true';
}

$items = almostheaven_parse_comments($file);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (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]);
  }
  if (isset($_POST['reply_key'])) {
    if (!$CAN_EDIT) die('<h1>Access Denied</h1>');
    $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]);
  }
  if ($CAN_EDIT) {
    if (isset($_POST['clear_all'])) {
      almostheaven_write_comments($file, []);
      smurf_redirect_self(['saved'=>1]);
    }
    $key = trim((string)($_POST['comment_key'] ?? ''));
    $foundIndex = null;
    foreach ($items as $idx => $item) { if ((string)($item['_key'] ?? '') === $key) { $foundIndex = $idx; break; } }
    if ($foundIndex !== null) {
      if (isset($_POST['delete_comment'])) {
        array_splice($items, $foundIndex, 1);
        almostheaven_write_comments($file, $items);
        smurf_redirect_self(['saved'=>1]);
      }
      if (isset($_POST['approve_comment']) || isset($_POST['unapprove_comment'])) {
        $items[$foundIndex]['Approved'] = isset($_POST['approve_comment']) ? '1' : '0';
        almostheaven_write_comments($file, $items);
        smurf_redirect_self(['saved'=>1]);
      }
      if (isset($_POST['ban_ip'])) {
        $ip = trim((string)($items[$foundIndex]['IP'] ?? ''));
        if ($ip !== '') file_put_contents($bannedFile, $ip . "\n", FILE_APPEND | LOCK_EX);
        smurf_redirect_self(['saved'=>1]);
      }
    }
  }
}
$items = almostheaven_parse_comments($file);
include __DIR__ . '/includes/admin_header.php';
?>
<section class="content-card">
  <div style="display:flex;justify-content:space-between;align-items:center;gap:10px;flex-wrap:wrap;">
    <h1 class="admin-title" style="margin:0;">💬 Comments</h1>
    <div class="admin-actions">
      <a class="admin-btn" href="index.php">Back</a>
      <?php if ($CAN_EDIT): ?><form method="post" style="display:inline-block;margin:0;" onsubmit="return confirm('Clear ALL entries?');"><input type="hidden" name="clear_all" value="1"><button class="admin-btn danger" type="submit">Clear All</button></form><?php endif; ?>
    </div>
  </div>
  <?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; ?>
    </form>
  </div>
  <?php if (empty($items)): ?>
    <p>No entries yet.</p>
  <?php else: ?>
    <?php foreach ($items as $item): $approved = almostheaven_comment_approved($item); $key = (string)($item['_key'] ?? ''); $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><?= smurf_h((string)(($item['Name'] ?? '') !== '' ? $item['Name'] : 'Comment')) ?></strong>
          <div class="admin-actions">
            <span class="preview-badge"><?= $approved ? 'Approved' : 'Pending' ?></span>
            <?php if ($CAN_EDIT): ?>
              <form method="post" style="display:inline-block;margin:0;"><input type="hidden" name="comment_key" value="<?= smurf_h($key) ?>"><?php if (!$approved): ?><button class="admin-btn" name="approve_comment" value="1" type="submit">Approve</button><?php else: ?><button class="admin-btn" name="unapprove_comment" value="1" type="submit">Unapprove</button><?php endif; ?></form>
              <form method="post" style="display:inline-block;margin:0;"><input type="hidden" name="comment_key" value="<?= smurf_h($key) ?>"><button class="admin-btn" name="ban_ip" value="1" type="submit">Ban IP</button></form>
              <form method="post" style="display:inline-block;margin:0;" onsubmit="return confirm('Delete this comment?');"><input type="hidden" name="comment_key" value="<?= smurf_h($key) ?>"><button class="admin-btn" name="delete_comment" value="1" type="submit">Delete</button></form>
            <?php endif; ?>
          </div>
        </div>
        <div style="margin-top:10px;display:grid;gap:8px;">
          <?php if (!empty($item['Timestamp'])): ?><div><strong>Timestamp:</strong> <?= smurf_h((string)$item['Timestamp']) ?></div><?php endif; ?>
          <?php if (!empty($item['IP'])): ?><div><strong>IP:</strong> <?= smurf_h((string)$item['IP']) ?></div><?php endif; ?>
          <div><strong>Message:</strong><br><?= nl2br(smurf_h((string)($item['Message'] ?? ''))) ?></div>
        </div>
        <form method="post" style="margin-top:12px;">
          <input type="hidden" name="reply_key" value="<?= smurf_h($key) ?>">
          <label style="display:block;margin-bottom:6px;font-weight:700;">Admin reply</label>
          <textarea name="reply_text" rows="3" class="input-field"><?= smurf_h((string)$reply) ?></textarea>
          <?php if ($CAN_EDIT): ?><button class="admin-btn" type="submit" style="margin-top:8px;">Save Reply</button><?php endif; ?>
        </form>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>
</section>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
