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

$admin_user = $_POST["admin_user"];
$admin_mail = $_POST["admin_mail"];
$admin_passwd_1 = $_POST["admin_passwd_1"];
$admin_passwd_2 = $_POST["admin_passwd_2"];

if (!isset($admin_user) || !isset($admin_mail) || !isset($admin_passwd_1) || !isset($admin_passwd_2)) {
    die('{"status":500, "error":"Missing fields"}');
}

if ($admin_passwd_2 !== $admin_passwd_1) {
    die('{"status":500, "error":"Passwords do not match"}');
}

$admin_passwd = hash("sha256", $admin_passwd_2);

$mcServ = new mcServ();
$config = $mcServ->getConf();

$db = new PDO("sqlite:" . $config["DB_PATH"]);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = "
CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    username VARCHAR(30) UNIQUE NOT NULL,
    mail VARCHAR(50),
    passwd VARCHAR(100)
)
";

$db->exec($sql);

$sql = "
CREATE table IF NOT EXISTS servers (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    uuid VARCHAR(50) UNIQUE NOT NULL,
    name VARCHAR(30)
)
";

$db->exec($sql);

$sql = "
CREATE TABLE IF NOT EXISTS api_keys (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    key VARCHAR(100) UNIQUE NOT NULL,
    user_id INTEGER
)
";

$db->exec($sql);

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

$stmt = $db->prepare($sql);
$stmt->execute([':user' => $admin_user, ':mail' => $admin_mail, ':passwd' => $admin_passwd]);

$session["session_id"] = $mcServ->generateSessionID();
$device_id = rand(1, 999);

$json[$device_id] = json_encode($session);
$json["array"] = true;

mkdir($config["PATH"] . "/tmp/user_sessions", 0755, true);

file_put_contents($config["PATH"] . "/tmp/user_sessions/" . $admin_user . ".json", json_encode($json));

setcookie("session_id", $session["session_id"], time() + 3600, "/");
setcookie("device_id", $device_id, time() + 3600, "/");
setcookie("username", $admin_user, time() + 3600, "/");

header("Location: /");
exit;
?>