<?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/.
 */

$where = [];

if (!empty($VARS["username"])) {
    $where["username"] = $VARS["username"];
} else if (!empty($VARS["email"])) {
    $where["email"] = $VARS["email"];
} else if (!empty($VARS["phone"])) {
    $where["phone"] = $VARS["phone"];
} else {
    sendJsonResp($Strings->get("No user identification (username, email, or phone number) supplied.", false), "ERROR");
}


if (!$database->has("accounts", $where)) {
    sendJsonResp($Strings->get("Account not found.", false), "ERROR");
}

$pass = "";
$hash = "";
if (!empty($VARS["password"])) {
    $pass = $VARS["password"];
    $hash = $database->get("accounts", "password", $where);
} else if (!empty($VARS["pin"])) {
    $pass = $VARS["pin"];
    $hash = $database->get("accounts", "pin", $where);
}

if (password_verify($pass, $hash)) {
    $accountid = $database->get("accounts", "accountid", $where);
    do {
        $key = hash("sha256", random_bytes(100));
    } while ($database->has("authkeys", ["key" => $key]));

    $database->insert("authkeys", [
        "accountid" => $accountid,
        "key" => $key,
        "expires" => date("Y-m-d H:i:s", strtotime("+30 days"))
    ]);
    exitWithJson(["status" => "OK", "key" => $key]);
} else {
    sendJsonResp($Strings->get("Password incorrect.", false), "ERROR");
}