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

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

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

  <title>Artikel</title>
</head>

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

  require_once "./queries.php";
  $query = $base;

  session_name("PHP_SESSION_itemList");
  session_start();
  $db = DB::openConnection();

  // DEFAULTS
  $number = "none";
  $article = "up";
  $price = "none";
  $page = 0;

  // Set from Session first
  if (isset($_SESSION["number"])) {
    $number = $_SESSION["number"];
  }
  if (isset($_SESSION["article"])) {
    $article = $_SESSION["article"];
  }
  if (isset($_SESSION["price"])) {
    $price = $_SESSION["price"];
  }

  // Populate with actual values if set and save to session
  $shouldRedirect = false;
  if (isset($_POST["number"])) {
    $number = $_POST["number"];
    $article = "none";
    $price = "none";
    $shouldRedirect = true;
  }
  if (isset($_POST["article"])) {
    $number = "none";
    $article = $_POST["article"];
    $price = "none";
    $shouldRedirect = true;
  }
  if (isset($_POST["price"])) {
    $number = "none";
    $article = "none";
    $price = $_POST["price"];
    $shouldRedirect = true;
  }

  // Save to session
  $_SESSION["number"] = $number;
  $_SESSION["article"] = $article;
  $_SESSION["price"] = $price;

  if ($shouldRedirect) {
    Headers::redirect("./");
    return;
  }

  if ($number !== "none")
    $query .= "\nORDER BY {$sorters["number"][$number]}\n";
  if ($article !== "none")
    $query .= "\nORDER BY {$sorters["article"][$article]}\n";
  if ($price !== "none")
    $query .= "\nORDER BY {$sorters["price"][$price]}\n";

  $query .= "LIMIT 10\n";

  $stmt = $db->prepare($cnt);
  $stmt->execute();
  $maxPage = intdiv($stmt->fetch(PDO::FETCH_COLUMN), 10);

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

  $query .= "OFFSET " . $page * 10;

  $stmt = $db->prepare($query);
  $stmt->execute();
  $result = $stmt->fetchAll();

  DB::closeConnection($db);
  ?>
  <nav class="navbar navbar-expand-lg navbar-light bg-light shadow-sm">
    <div class="container-fluid">
      <a class="navbar-brand" href="#">List of items</a>
    </div>
  </nav>

  <div class="container-fluid">
    <p>
      Below you will find a list of all purchasable items, their item number as well as their price per unit.
    </p>

    <main>
      <table class="table table-sm table-striped">
        <?php include "./components/table/head.php" ?>
        <?php include "./components/table/body.php" ?>
      </table>
      <?php include "./components/pagination.php" ?>
    </main>
  </div>
</body>

</html>