<!DOCTYPE html>
<html lang="en">

<head>
  <?php require_once "../../base/meta.php" ?>

  <title>Guest Book</title>

  <script src="./js/formValidation.js"></script>
  <script src="./js/textarea.js"></script>
</head>

<body>
  <?php
  // HTML
  require_once "../../base/icons.php";
  // PHP
  require_once "../../base/settings.php";
  require_once "../../base/headers.php";
  Headers::html();

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

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

  if (isset($_GET["p"]) && !is_numeric($_GET["p"])) {
    Headers::redirect(".");
    return;
  }

  $page = isset($_GET["p"]) ? intval($_GET["p"]) : 0;
  $maxPage = intdiv(count($json), 9);
  if ($page > $maxPage) {
    Headers::redirect("./?p=$maxPage");
    return;
  }

  $data = array_slice($json, $page * 9, 9);
  ?>

  <div class="container-fluid p-0">
    <nav class="navbar navbar-expand-lg navbar-light bg-light">
      <div class="container-fluid">
        <a class="navbar-brand" href="#">Guest Book</a>
      </div>
    </nav>

    <div class="row m-0">
      <div class="col">
        <?php foreach ($errors as $error) {
          include "./components/error.php";
        } ?>
      </div>
    </div>

    <div class="row row-cols-1 row-cols-lg-3 g-3 m-0 mb-3">
      <?php foreach ($data as $comment) {
        include "./components/comment.php";
      } ?>
    </div>

    <?php include "./components/pagination.php" ?>

    <hr />

    <?php include "./components/newComment.php" ?>
  </div>
</body>

</html>