<?php
require "../api.php";

ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
error_reporting(E_ALL);

$api = new spamhasiApi();
$conf = $api->getConf();

if (!$api->checkAuth()) {
    header("Location: /users.html?status=500&error=Unauthorized");
    exit;
}

if (!isset($_POST["name"]) || !isset($_POST["passwd1"]) || !isset($_POST["passwd2"])) {
    header("Location: /users.html?status=500&error=Missing fields");
    exit;
}

$name = htmlspecialchars($_POST["name"]);
$passwd1 = hash("sha256", $_POST["passwd1"]);
$passwd2 = hash("sha256", $_POST["passwd2"]);

if (!preg_match('/^[a-z]+$/', $name)) {
    header("Location: /users.html?status=500&error=Der Benutzername enthält ungültige Zeichen.");
    exit;
}

if ($passwd1 !== $passwd2) {
    header("Location: /users.html?status=500&error=Die Passwörter stimmen nicht überein.");
    exit;
}

$db = $api->getDB();

$sql = "INSERT INTO users (username, passwd) VALUES (:name, :passwd)";

$stmt = $db->prepare($sql);

$sql_exec = $stmt->execute([':name' => $name, ':passwd' => $passwd2]);

if (!$sql_exec) {
    header("Location: /users.html?status=500&error=SQL Error");
}

if (!file_put_contents($conf["PATH"] . "/tmp/user_sessions/" . $name . ".json", '{}')) {
    header("Location: /users.html?status=500&error=Error to write session file.");
    exit;
}

header("Location: /users.html?status=200");
exit;
?>