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

session_name("PHP_SESSION_guestBook");
session_start();

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

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

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

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

if ($username === "") {
  array_push($_SESSION["error"], "The username was empty.");
}
if ($email === "") {
  array_push($_SESSION["error"], "The email was empty.");
}
if ($password === "") {
  array_push($_SESSION["error"], "The password was empty.");
}
if ($passwordConfirm === "" || $password !== $passwordConfirm) {
  array_push($_SESSION["error"], "The passwords do not match.");
}

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

$db = DB::openConnection();

try {
  $guid = guidv4();

  $stmt = $db->prepare($insertUserQuery);
  $stmt->bindValue(":USR", $username);
  $stmt->bindValue(":PAS", password_hash($password, PASSWORD_DEFAULT));
  $stmt->bindValue(":EMA", $email);
  $stmt->bindValue(":COD", $guid);
  $stmt->execute();

  mail(
    $email,
    "Account activation GuestBookDB",
    "Hello $username. To activate your account, visit https://userpage.fu-berlin.de/khofmann/phpCourse/tasks/guestBookDB/confirm?c=$guid"
  );

  array_push($_SESSION["message"], "Please confirm your account using the mail we sent you.");
} catch (PDOException $e) {
  if ($e->getCode() === "23000") {
    array_push($_SESSION["error"], "A user with this username or email already exists");
  } else {
    array_push($_SESSION["error"], "SQL Error: {$e->getMessage()}");
  }
  Headers::redirect("../register");
  return;
}

DB::closeConnection($db);

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