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

session_name("PHP_SESSION_guestBook");
session_start();
$user = $_SESSION["user"] ?? null;
$_SESSION["error"] = [];

if (!isset($user)) {
  Headers::redirect("../login");
  return;
}

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

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

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

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

$db = DB::openConnection();

$stmt = $db->prepare($insertCommentQuery);
$stmt->bindValue(":UID", $user["id"]);
$stmt->bindValue(":COM", $comment);
$stmt->execute();

DB::closeConnection($db);

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