<?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;
}
$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';
$state = ht_read_comments($commentsFile, $repliesFile);
$itemsOldest = $state['items_oldest'];
$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);
}
header('Location: /index.php?submitted=true');
exit;
