<?php
if (isset($_POST["username"]) && isset($_POST["password"])) {
    if (check_username($_POST["username"])) {
        $res = get_account_by_username($_POST["username"]);
        if (password_verify($_POST["password"], $res[0]["pwd"])) {
            $_POST["password"] = null;
            $_SESSION["signedin"] = true;
            $_SESSION["userid"] = $res[0]["id"];
            if (isset($_POST["referer"])) {
                header("Location: {$_POST["referer"]}");
            }
        } else {
            $_POST["password"] = null;
            echo "Invalid password";
        }
    } else {
        $passhash = password_hash($_POST["password"], PASSWORD_BCRYPT, ["cost" => 14]);
        $success = create_account($_POST["username"], $passhash);
        $_POST["password"] = null;
        if ($success) {
            echo "Account created";
        } else {
            echo "An error occurred, you can try again in a moment.";
        }
    }
}
?>
<h3>Logga in</h3>
<p>Loggar in dig eller skapar ett konto med uppgifterna du skrev in.</p>
<form method="post" action="?page=login">
    <input type="hidden" name="referer" value="<?= $_SERVER["HTTP_REFERER"] ?>">
    <input type="text" name="username" placeholder="Användarnamn">
    <input type="password" name="password" placeholder="Lösenord">
    <input type="submit" value="Logga In">
</form>
