<?php
require_once "../../../base/settings.php";
require_once "../../../base/headers.php";

session_start();
$_SESSION["error"] = [];

if (!isset($_POST["title"])) {
  array_push($_SESSION["error"], "Title was not among the data sent.");
}
if (!isset($_POST["name"])) {
  array_push($_SESSION["error"], "Name was not among the data sent.");
}
if (!isset($_POST["comment"])) {
  array_push($_SESSION["error"], "Comment was not among the data sent.");
}

$title = trim($_POST["title"]);
$name = trim($_POST["name"]);
$comment = substr(trim($_POST["comment"]), 0, 250);
$time = time();

if ($title === "") {
  array_push($_SESSION["error"], "The title was empty.");
}
if ($name === "") {
  array_push($_SESSION["error"], "The name was empty.");
}
if ($comment === "") {
  array_push($_SESSION["error"], "The comment was empty.");
}

if (count($_SESSION["error"]) > 0) {
  Headers::redirect(".");
  return;
}

$string = file_get_contents("../data/data.json") ?? "[]";
$json = json_decode($string);

array_push($json, ["time" => $time, "title" => $title, "name" => $name, "comment" => $comment]);

file_put_contents("../data/data.json", json_encode($json));

Headers::redirect("../");
