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

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

$api = new spamhasiApi();

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

if (!isset($_POST["id"]) || !isset($_POST["name"]) || !isset($_POST["passwd1"]) || !isset($_POST["passwd2"])) {
    die('{"status":500, "error":"Missing fields"}');
}

$db = $api->getDB();

$id = intval($_POST["id"]);

$sql = "SELECT username FROM users WHERE id = :id";

$stmt = $db->prepare($sql);
$sql_exec = $stmt->execute([':id' => $id]);

if (!$sql_exec) {
    header("Location: /users.html?status=500&error=Alter Benutzername konnte nicht abgerufen werden.");
    exit;
}

$result = $stmt->fetch(PDO::FETCH_ASSOC);

if ($result) {
    $old_name = $result["username"];
}else{
    header("Location: /users.html?status=500&error=Alter Benutzername konnte nicht ermittelt werden: SQL Error");
    exit;
}


$name = $_POST["name"];

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

if ($name !== $old_name) {
    if (file_exists("../../tmp/user_sessions/" . $old_name . ".json")) {
        unlink("../../tmp/user_sessions/" . $old_name . ".json");
    }
}

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

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

$db = $api->getDB();

$sql = "UPDATE users SET username = :name, passwd = :passwd WHERE id = :id";

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

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

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

if (file_put_contents("../../tmp/user_sessions/" . $name . ".json", '{"array":true}')) {
    header("Location: /users.html?status=200");
}else{
    header("Location: /users.html?status=500&error=Error to write session file.");
}
exit;
?>