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

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

  <title>Guest Book DB</title>

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

  <link href="./css/styles.css" rel="stylesheet" />
</head>

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

  require_once "./queries.php";

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

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

  $db = DB::openConnection();

  $stmt = $db->prepare($countQuery);
  $stmt->execute();
  $maxPage = intdiv($stmt->fetch(PDO::FETCH_COLUMN), 9);
  if ($page > $maxPage) {
    Headers::redirect("./?p=$maxPage");
    return;
  }

  $stmt = $db->prepare($dataQuery .  $page * 9);
  $stmt->execute();
  $data = $stmt->fetchAll();

  DB::closeConnection($db);
  ?>

  <div class="container-fluid p-0">
    <nav class="navbar navbar-expand-lg navbar-light bg-light sticky-top shadow-sm">
      <div class="container-fluid">
        <a class="navbar-brand" href="#">Guest Book</a>
        <?php if (!isset($user)) { ?>
          <a href="./login">Login</a>
        <?php } else { ?>
          <div>
            Hallo <?= $user["benutzer"] ?> |
            <a class="fs-6" href="./actions/logout">Logout</a>
          </div>
        <?php } ?>
      </div>
    </nav>

    <div class="row m-0 mb-3">
      <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 if (isset($user)) { ?>
      <?php include "./components/newComment.php" ?>
    <?php } else { ?>
      <div class="row g-3 m-0">
        <h4> You wish to leave a Comment?</h4>
        <p>
          <a href="./login">Login</a> or <a href="./register">register</a> a new account!
        </p>
      </div>
    <?php } ?>
  </div>

  <?php require_once "../../homework/2/counterDB/counter/counter.php" ?>
</body>

</html>