<?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);
require_once __DIR__ . '/../includes/comments_lib.php';

$repliesFile = __DIR__ . '/../data/comment_replies.json';
$action = $_GET['action'] ?? '';
$idx = isset($_GET['i']) ? (int)$_GET['i'] : -1;

$state = ht_read_comments($file, $repliesFile);
$items = $state['items_newest'];
$replies = $state['replies'];
ht_write_comments($file, array_reverse($items));
smurf_write_json($repliesFile, $replies);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_comments'])) {
  if (!$CAN_EDIT) smurf_admin_denied();
  $settings['comments_enabled'] = isset($_POST['comments_enabled']) ? true : false;
  smurf_save_settings($settingsFile, $settings);
  smurf_redirect_self(['saved'=>1], ['action','i']);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reply_key'])) {
  if (!$CAN_EDIT) smurf_admin_denied('You do not have permission to reply.');
  $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']);
}

if ($action === 'delete' && $idx >= 0) {
  if (!$CAN_EDIT) smurf_admin_denied('You do not have permission to delete entries.');
  if (isset($items[$idx])) {
    $delKey = $items[$idx]['key'] ?? '';
    if ($delKey !== '') unset($replies[$delKey]);
    unset($items[$idx]);
    $items = array_values($items);
    ht_write_comments($file, array_reverse($items));
    smurf_write_json($repliesFile, $replies);
  }
  smurf_redirect_self([], ['action','i']);
}

if ($action === 'clear') {
  if (!$CAN_EDIT) smurf_admin_denied('You do not have permission to clear entries.');
  ht_write_comments($file, []);
  smurf_write_json($repliesFile, []);
  smurf_redirect_self([], ['action','i']);
}

if (($action === 'approve' || $action === 'unapprove') && $idx >= 0) {
  if (!$CAN_EDIT) smurf_admin_denied('You do not have permission for that action.');
  if (isset($items[$idx])) {
    $items[$idx]['approved'] = ($action === 'approve');
    ht_write_comments($file, array_reverse($items));
  }
  smurf_redirect_self(['saved'=>1], ['action','i']);
}

function smurf_comment_key(array $item): string { return (string)($item['key'] ?? ht_comment_key($item)); }
function smurf_is_approved(array $item): bool { return !empty($item['approved']); }

$q = smurf_q('q');
$status = strtolower(smurf_q('status', 'all'));
$filtered = array_values(array_filter($items, function($item) use ($q, $status, $replies) {
  $haystack = implode(' ', [(string)($item['ip'] ?? ''), (string)($item['date'] ?? ''), (string)($item['message'] ?? '')]);
  if (!smurf_match_text($haystack, $q)) return false;
  $reply = trim((string)($replies[smurf_comment_key($item)]['text'] ?? ''));
  return match ($status) {
    'pending' => empty($item['approved']),
    'approved' => !empty($item['approved']),
    'replied' => $reply !== '',
    'unreplied' => $reply === '',
    default => true,
  };
}));
$stats = [
  'all' => count($items),
  'pending' => count(array_filter($items, fn($i) => empty($i['approved']))),
  'approved' => count(array_filter($items, fn($i) => !empty($i['approved']))),
  'replied' => count(array_filter($items, fn($i) => trim((string)($replies[smurf_comment_key($i)]['text'] ?? '')) !== '')),
];
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>
    <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="display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px;margin:12px 0 18px;">
    <div class="content-card"><strong><?= (int)$stats['all'] ?></strong><div>Total comments</div></div>
    <div class="content-card"><strong><?= (int)$stats['pending'] ?></strong><div>Pending</div></div>
    <div class="content-card"><strong><?= (int)$stats['approved'] ?></strong><div>Approved</div></div>
    <div class="content-card"><strong><?= (int)$stats['replied'] ?></strong><div>Replied</div></div>
  </div>

  <div style="margin:10px 0 18px;display:flex;gap:10px;flex-wrap:wrap;align-items:center;justify-content:space-between;">
    <form method="get" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;">
      <input class="input-field" type="text" name="q" value="<?= smurf_h($q) ?>" placeholder="Search comment text or IP" style="min-width:220px;">
      <select class="input-field" name="status" style="min-width:160px;">
        <option value="all" <?= $status === 'all' ? 'selected' : '' ?>>All comments</option>
        <option value="pending" <?= $status === 'pending' ? 'selected' : '' ?>>Pending</option>
        <option value="approved" <?= $status === 'approved' ? 'selected' : '' ?>>Approved</option>
        <option value="replied" <?= $status === 'replied' ? 'selected' : '' ?>>Replied</option>
        <option value="unreplied" <?= $status === 'unreplied' ? 'selected' : '' ?>>Need reply</option>
      </select>
      <button class="admin-btn" type="submit">Filter</button>
      <?php if ($q !== '' || $status !== 'all'): ?><a class="admin-btn" href="/admin/comments.php">Reset</a><?php endif; ?>
    </form>
    <?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; ?>
  </div>

  <?php if (empty($filtered)): ?>
    <p>No entries match this view.</p>
  <?php else: ?>
    <?php foreach ($filtered as $i => $item): ?>
      <?php $approved = smurf_is_approved($item); $key = smurf_comment_key($item); $reply = trim((string)($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['date'] ?? 'Comment')) ?></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 ($reply !== ''): ?><span style="font-weight:700;color:#9fd9ff;">Replied</span><?php endif; ?>
            <?php if ($CAN_EDIT): ?>
              <?php if (!$approved): ?><a class="admin-btn" href="/admin/comments.php?action=approve&i=<?= (int)array_search($item, $items, true) ?>">Approve</a><?php else: ?><a class="admin-btn" href="/admin/comments.php?action=unapprove&i=<?= (int)array_search($item, $items, true) ?>">Unapprove</a><?php endif; ?>
              <a class="admin-btn" href="/admin/comments.php?action=delete&i=<?= (int)array_search($item, $items, true) ?>" onclick="return confirm('Delete this entry?');">Delete</a>
            <?php endif; ?>
          </div>
        </div>
        <div style="margin:10px 0 0;opacity:.95;">
          <div><strong>IP:</strong> <?= smurf_h((string)($item['ip'] ?? '')) ?></div>
          <div style="margin-top:8px;white-space:pre-wrap;"><?= smurf_h((string)($item['message'] ?? '')) ?></div>
        </div>
        <div style="margin-top:12px;">
          <h4 style="margin:0 0 6px;">Admin Reply</h4>
          <?php if ($reply !== ''): ?>
            <div class="content-card" style="margin:8px 0 10px;background:rgba(255,255,255,.03);border:1px solid rgba(0,255,180,.28);">
              <strong style="display:block;margin-bottom:6px;">Saved Reply</strong>
              <?= 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 name="reply_text" rows="3" style="width:100%;max-width:100%;"><?= 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 endif; ?>
        </div>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>
</section>

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