<?php
require_once __DIR__ . '/../includes/redirect_helper.php';

$name = trim((string)($_POST['name'] ?? ''));
$message = trim((string)($_POST['message'] ?? ''));
if ($name === '' || $message === '') {
  ah_redirect_back('/comments/index.php', ['err' => 'missing']);
}

$timestamp = date('Y-m-d H:i:s');
$jsonFile = __DIR__ . '/../data/comments.json';
$txtFile = __DIR__ . '/../data/comments.txt';

$comments = file_exists($jsonFile) ? json_decode((string)file_get_contents($jsonFile), true) : [];
if (!is_array($comments)) $comments = [];
$comments[] = [
  'name' => $name,
  'message' => $message,
  'timestamp' => $timestamp,
  'ip' => (string)($_SERVER['REMOTE_ADDR'] ?? ''),
  'approved' => false,
  'reply' => ''
];
file_put_contents($jsonFile, json_encode($comments, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n", LOCK_EX);

$clean = static function (string $value): string {
  $value = str_replace(["\r\n", "\r"], "\n", $value);
  $value = preg_replace("/\n{3,}/", "\n\n", $value);
  return trim(str_replace(["\0"], '', $value));
};
$block = "Name: " . $clean($name) . "\n"
       . "Message: " . $clean($message) . "\n"
       . "IP: " . $clean((string)($_SERVER['REMOTE_ADDR'] ?? '')) . "\n"
       . "Timestamp: " . $timestamp . "\n"
       . "Approved: 0\n---\n";
file_put_contents($txtFile, $block, FILE_APPEND | LOCK_EX);

ah_redirect_back('/index.php', ['commented' => 1]);
