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

$jsonFile = __DIR__ . '/../data/comments.json';
$txtFile = __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, []);
if (!is_array($replies)) $replies = [];

function ah_comment_key(array $item): string {
  $name = trim((string)($item['name'] ?? $item['Name'] ?? ''));
  $message = trim((string)($item['message'] ?? $item['Message'] ?? ''));
  $timestamp = trim((string)($item['timestamp'] ?? $item['Timestamp'] ?? ''));
  return md5($name . '|' . $timestamp . '|' . $message);
}

function ah_comments_parse_txt(string $file): array {
  if (!file_exists($file) || trim((string)@file_get_contents($file)) === '') return [];
  $raw = trim((string)@file_get_contents($file));
  $items = [];
  if (strpos($raw, '---') !== false && preg_match('/(^|\n)\w+\s*:/', $raw)) {
    foreach (smurf_parse_blocks($file) as $item) {
      $name = trim((string)($item['Name'] ?? ''));
      $message = trim((string)($item['Message'] ?? ''));
      if ($name === '' && $message === '') continue;
      $norm = [
        'name' => $name,
        'message' => $message,
        'timestamp' => (string)($item['Timestamp'] ?? ''),
        'ip' => (string)($item['IP'] ?? ''),
        'approved' => in_array(strtolower((string)($item['Approved'] ?? '0')), ['1','yes','true'], true),
        'reply' => '',
      ];
      $norm['_key'] = ah_comment_key($norm);
      $items[] = $norm;
    }
    return array_reverse($items);
  }
  $lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
  foreach ($lines as $line) {
    $p = explode('|', trim((string)$line));
    if (count($p) < 6) continue;
    [$id,$name,$message,$ip,$timestamp,$approved] = array_pad($p, 6, '');
    if (trim($name) === '' && trim($message) === '') continue;
    $norm = [
      'name' => $name,
      'message' => $message,
      'timestamp' => $timestamp,
      'ip' => $ip,
      'approved' => in_array(strtolower((string)$approved), ['1','yes','true'], true),
      'reply' => '',
    ];
    $norm['_key'] = ah_comment_key($norm);
    $items[] = $norm;
  }
  return array_reverse($items);
}

function ah_comments_load(string $jsonFile, string $txtFile, array $replies): array {
  $json = file_exists($jsonFile) ? json_decode((string)file_get_contents($jsonFile), true) : [];
  $items = [];
  if (is_array($json) && !empty($json)) {
    foreach ($json as $row) {
      if (!is_array($row)) continue;
      $name = trim((string)($row['name'] ?? $row['Name'] ?? ''));
      $message = trim((string)($row['message'] ?? $row['Message'] ?? ''));
      if ($name === '' && $message === '') continue;
      $norm = [
        'name' => $name,
        'message' => $message,
        'timestamp' => (string)($row['timestamp'] ?? $row['Timestamp'] ?? ''),
        'ip' => (string)($row['ip'] ?? $row['IP'] ?? ''),
        'approved' => !empty($row['approved']) || in_array(strtolower((string)($row['Approved'] ?? '0')), ['1','yes','true'], true),
        'reply' => (string)($row['reply'] ?? ''),
      ];
      $norm['_key'] = ah_comment_key($norm);
      if ($norm['reply'] === '' && !empty($replies[$norm['_key']]['text'])) $norm['reply'] = (string)$replies[$norm['_key']]['text'];
      $items[] = $norm;
    }
  }
  if (empty($items)) {
    $items = ah_comments_parse_txt($txtFile);
    foreach ($items as &$item) {
      if (!empty($replies[$item['_key']]['text'])) $item['reply'] = (string)$replies[$item['_key']]['text'];
    }
    unset($item);
  }
  return $items;
}

function ah_comments_write(string $jsonFile, string $txtFile, array $items): void {
  $json = [];
  $blocks = [];
  foreach ($items as $item) {
    $json[] = [
      'name' => (string)($item['name'] ?? ''),
      'message' => (string)($item['message'] ?? ''),
      'timestamp' => (string)($item['timestamp'] ?? ''),
      'ip' => (string)($item['ip'] ?? ''),
      'approved' => !empty($item['approved']),
      'reply' => (string)($item['reply'] ?? ''),
    ];
    $blocks[] = implode("\n", [
      'Name: ' . str_replace(["\r","\n"], ' ', (string)($item['name'] ?? '')),
      'Message: ' . str_replace(["\r"], '', (string)($item['message'] ?? '')),
      'IP: ' . str_replace(["\r","\n"], ' ', (string)($item['ip'] ?? '')),
      'Timestamp: ' . str_replace(["\r","\n"], ' ', (string)($item['timestamp'] ?? '')),
      'Approved: ' . (!empty($item['approved']) ? '1' : '0'),
    ]);
  }
  smurf_write_json($jsonFile, $json);
  file_put_contents($txtFile, $blocks ? implode("\n---\n", $blocks) . "\n---\n" : '', LOCK_EX);
}

$items = ah_comments_load($jsonFile, $txtFile, $replies);
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']);
    smurf_save_settings($settingsFile, $settings);
    smurf_redirect_self(['saved'=>1]);
  }

  if ($CAN_EDIT && isset($_POST['reply_key'])) {
    $key = preg_replace('/[^a-f0-9]/', '', (string)($_POST['reply_key'] ?? ''));
    $reply = trim((string)($_POST['reply_text'] ?? ''));
    foreach ($items as &$item) {
      if ((string)($item['_key'] ?? '') === $key) {
        $item['reply'] = $reply;
        break;
      }
    }
    unset($item);
    if ($key !== '') {
      if ($reply === '') unset($replies[$key]); else $replies[$key] = ['text'=>$reply,'by'=>$_SESSION['user'] ?? $_SESSION['username'] ?? 'admin','ts'=>time()];
      smurf_write_json($repliesFile, $replies);
      ah_comments_write($jsonFile, $txtFile, $items);
    }
    smurf_redirect_self(['saved'=>1]);
  }

  if ($CAN_EDIT) {
    if (isset($_POST['clear_all'])) {
      ah_comments_write($jsonFile, $txtFile, []);
      smurf_write_json($repliesFile, []);
      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'])) {
        unset($replies[$key]);
        array_splice($items, $foundIndex, 1);
        smurf_write_json($repliesFile, $replies);
        ah_comments_write($jsonFile, $txtFile, $items);
        smurf_redirect_self(['saved'=>1]);
      }
      if (isset($_POST['approve_comment']) || isset($_POST['unapprove_comment'])) {
        $items[$foundIndex]['approved'] = isset($_POST['approve_comment']);
        ah_comments_write($jsonFile, $txtFile, $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 = ah_comments_load($jsonFile, $txtFile, $replies);
$displayItems = array_reverse($items);
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($displayItems)): ?>
    <p>No entries yet.</p>
  <?php else: ?>
    <?php foreach ($displayItems as $item): $approved = !empty($item['approved']); $key = (string)($item['_key'] ?? ''); ?>
      <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)($item['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'; ?>
