<?php
date_default_timezone_set('America/New_York');
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
  header('Location: /index.php');
  exit;
}
require_once __DIR__ . '/../includes/comments_lib.php';

$comment = trim((string)($_POST['comment'] ?? ''));
if ($comment === '') {
  header('Location: /index.php?error=empty_comment');
  exit;
}
if (mb_strlen($comment, 'UTF-8') > 1200) {
  header('Location: /index.php?error=comment_too_long');
  exit;
}
$blockedTerms = ['http://', 'https://', '[url', 'viagra', 'cialis', 'crypto giveaway'];
$lower = mb_strtolower($comment, 'UTF-8');
foreach ($blockedTerms as $term) {
  if (str_contains($lower, $term)) {
    header('Location: /index.php?error=comment_blocked');
    exit;
  }
}
$ip = trim((string)($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
$bannedFile = __DIR__ . '/../data/banned_ips.txt';
$bannedIPs = is_file($bannedFile) ? file($bannedFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) : [];
if (in_array($ip, $bannedIPs, true)) {
  http_response_code(403);
  exit('Your IP has been blocked from commenting.');
}
$commentsFile = __DIR__ . '/../data/comments.txt';
$repliesFile = __DIR__ . '/../data/comment_replies.json';
$rateFile = __DIR__ . '/../data/comment_rate_limits.json';
$rate = file_exists($rateFile) ? json_decode((string)file_get_contents($rateFile), true) : [];
if (!is_array($rate)) $rate = [];
$now = time();
foreach ($rate as $rateIp => $ts) {
  if (($now - (int)$ts) > 86400) unset($rate[$rateIp]);
}
if (!empty($rate[$ip]) && ($now - (int)$rate[$ip]) < 90) {
  header('Location: /index.php?error=comment_wait');
  exit;
}
$state = ht_read_comments($commentsFile, $repliesFile);
$itemsOldest = $state['items_oldest'];
$normalizedMessage = trim(preg_replace('/\s+/', ' ', $comment));
foreach (array_reverse($itemsOldest) as $existing) {
  $existingText = trim(preg_replace('/\s+/', ' ', html_entity_decode((string)($existing['message'] ?? ''), ENT_QUOTES, 'UTF-8')));
  if (($existing['ip'] ?? '') === $ip && $existingText !== '' && strcasecmp($existingText, $normalizedMessage) === 0) {
    $existingTime = strtotime((string)($existing['date'] ?? '')) ?: 0;
    if ($existingTime && ($now - $existingTime) < 3600) {
      header('Location: /index.php?error=duplicate_comment');
      exit;
    }
  }
}
$itemsOldest[] = [
  'ip' => $ip,
  'date' => date('Y-m-d H:i:s'),
  'message' => htmlspecialchars($comment, ENT_QUOTES, 'UTF-8'),
  'approved' => false,
];
ht_write_comments($commentsFile, $itemsOldest);
if (!empty($state['replies'])) {
  file_put_contents($repliesFile, json_encode($state['replies'], JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES), LOCK_EX);
}
$rate[$ip] = $now;
file_put_contents($rateFile, json_encode($rate, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES), LOCK_EX);
header('Location: /index.php?submitted=true');
exit;
