<?php

/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

$username_max = 50;
$password_min = 8;

$username = strtolower($VARS["username"]);

if (!preg_match("/^[a-z0-9]+$/", $username)) {
    sendJsonResp($Strings->get("Username contains disallowed characters.  Please use letters and numbers only.", false), "ERROR");
}

if (strlen($username) > $username_max) {
    sendJsonResp($Strings->get("Username is too long.", false), "ERROR");
}

if ($database->has("accounts", ["username" => $username])) {
    sendJsonResp($Strings->get("Username already taken.", false), "ERROR");
}

if (strlen($VARS["password"]) < $password_min) {
    sendJsonResp($Strings->get("Password too short, it must be at least 8 characters long.", false), "ERROR");
}


// Check HaveIBeenPwned
$pwsha1 = strtoupper(hash("sha1", $VARS["password"]));
$pwned = file_get_contents("https://api.pwnedpasswords.com/range/" . substr($pwsha1, 0, 5));
if (strpos($pwned, substr($pwsha1, 5)) !== FALSE) {
    sendJsonResp($Strings->get("Your chosen password has been leaked in a data breach and is no longer secure.  Choose another.", false), "ERROR");
}

// Generate public ID code
do {
    $publicid = substr(hash("sha256", random_bytes(100)), 0, 10);
} while ($database->has("accounts", ["publicid" => $publicid]));

$database->insert("accounts", [
    "publicid" => $publicid,
    "username" => $username,
    "password" => password_hash($VARS["password"], PASSWORD_DEFAULT),
    "type" => ($VARS["accttype"] == "giver" ? 1 : 2),
    "balance" => 0.0
]);

sendJsonResp();