<?php
date_default_timezone_set('America/New_York');
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
  header('Location: /index.php');
  exit;
}
$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.');
}
$entry = "IP: {$ip}\nDate: " . date('Y-m-d H:i:s') . "\n" . htmlspecialchars($comment, ENT_QUOTES, 'UTF-8') . "\nApproved: false";
file_put_contents(__DIR__ . '/../data/comments.txt', $entry . "\n---\n", FILE_APPEND | LOCK_EX);
header('Location: /index.php?submitted=true');
exit;
