<?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();

if (isset($_SESSION["user"])) {
  Headers::redirect("../");
  return;
}

$_SESSION["error"] = [];
unset($_SESSION["user"]);

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

$username = trim($_POST["username"]);
$password = trim($_POST["password"]);

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

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

$db = DB::openConnection();

$stmt = $db->prepare($loginQuery);
$stmt->bindValue(":USR", $username);
$stmt->execute();
$user = $stmt->fetch();

if ($user) {
  if (password_verify($password, $user["passwort"])) {
    $_SESSION["user"] = $user;
    // REHASH for safety should it somehow change
    if (password_needs_rehash($user["passwort"], PASSWORD_DEFAULT)) {
      $newHash = password_hash($password, PASSWORD_DEFAULT);
      $stmt = $db->prepare($updatePasswordQuery);
      $stmt->bindValue(":PAS", $newHash);
      $stmt->bindValue(":UID", $user["id"]);
      $stmt->execute();
    }
    unset($_SESSION["user"]["passwort"]);
    unset($_SESSION["user"]["confirmationcode"]);
  } else {
    array_push($_SESSION["error"], "Username or Password incorrect.");
  }
} else {
  array_push($_SESSION["error"], "Username or Password incorrect.");
}

DB::closeConnection($db);

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

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