<?php

require(__DIR__ . "/../libs/page.php");
require(__DIR__ . "/../libs/form.php");

function post_handler()
{
    global $db;

    // there is 100% a better way to do this but i need to test
    if (!array_key_exists('pass', $_POST) || !array_key_exists('user', $_POST) || !array_key_exists('pass2', $_POST)) {
        return '';
    }

    $user = $_POST['user'];
    $pass = $_POST['pass'];
    $pass2 = $_POST['pass2'];

    preg_match("/[^A-Za-z0-9\-\_]/", $user, $matches);

    if ($pass != $pass2) {
        return 'Passwords are not the same.';
    }

    if (isset($matches) && count($matches) > 0) {
        return 'Username contains invalid characters.';
    }

    if (strlen($user) < 1 || strlen($user) > 32) {
        return 'Username is too long or short.';
    }

    $stmt = $db->prepare("SELECT username FROM main.auth WHERE UPPER(username) LIKE UPPER(?)");
    $stmt->execute([$user]);

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

    if ($result) {
        return 'Username is taken.';
    }

    $hashed = password_hash($pass, PASSWORD_DEFAULT);

    $stmt = $db->prepare("INSERT INTO main.auth (username, password) VALUES (?, ?)");
    $stmt->execute([$user,$hashed]);

    header("Location: /");
    die();
}

page_header();

$form_message = post_handler();

form("Join", $form_message, array(
    array('key' => 'Username', 'type' => 'text', 'name' => 'user', 'default' => ''),
    array('key' => 'Password', 'type' => 'password', 'name' => 'pass', 'default' => ''),
    array('key' => 'Password (again)', 'type' => 'password', 'name' => 'pass2', 'default' => '')
));

page_footer();