<?php
    /* Verify the captcha. */
    /* Source: https://www.youtube.com/watch?v=rFccSL76SeY */
    function post_captcha($user_response)
    {
        $fields_string = '';
        $fields = array(
            'secret' => '6Lfk90IUAAAAAPV59AkKlb1AlFgOt5h_H_YUlRbN',
            'response' => $user_response
        );

        foreach($fields as $key=>$value)
            $fields_string .= $key . '=' . $value . '&';
        $fields_string = rtrim($fields_string, '&');

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
        curl_setopt($ch, CURLOPT_POST, count($fields));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);

        $result = curl_exec($ch);
        curl_close($ch);

        return json_decode($result, true);
    }

    include 'db_conn.php';

    /* If any of these are empty, registration is impossible. */
    if (empty($_POST['username']) || empty($_POST['email'])
        || empty($_POST['password']))
    {
        http_response_code(400);
        die("Error registering user.");
    }

    $res = post_captcha($_POST['g-recaptcha-response']);

    if (!$res['success'])
    {
        http_response_code(400);
        die("Error registering user (CAPTCHA error).");
    }

    /* Verify the input data.
     * The 72 characters is a password_hash() limitation. */
    $username_ok = preg_match('/^[a-zA-Z0-9_.-]+$/', $_POST['username']);

    if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)
        ||!$username_ok
        ||(strlen($_POST['password']) > 72))
    {
        http_response_code(400);
        die("Error registering user (validation error).");
    }

    /* If a user already exists, return 400. */
    $query = 'SELECT * FROM Users WHERE username=:uname';

    $statement = $db->prepare($query);
    $statement->execute(array("uname" => $_POST['username']));
    $result = $statement->fetch(PDO::FETCH_ASSOC);
    if ($result)
    {
        http_response_code(400);
        die("Error registering user (username exists).");
    }

    /* By default, privilege is 'user' and active status is 'inactive' */
    $privilege = 4;
    $active = 1;

    if (!empty($_POST['invite_token']))
    {
        $invite_token = $_POST['invite_token'];

        $statement = $db->prepare("SELECT privilege_level FROM Invites WHERE token=:token;");
        $statement->execute(array("token" => $invite_token));
        if ($statement->rowCount() == 0)
        {
            http_response_code(400);
            die("Invalid invite token.");
        }

        $results = $statement->fetch(PDO::FETCH_ASSOC);
        $privilege = $results['privilege_level'];
        $active = 2;

        $statement = $db->prepare("DELETE FROM Invites WHERE token=:token;");
        $statement->execute(array("token" => $invite_token));
    }

    /* Otherwise, insert a new user :) */
    $query = 'INSERT INTO Users (username, password_hash, email, privilege_id, status_user_id) '
        .'VALUES (:uname, :pwhash, :email, :pid, :usid)';

    $statement = $db->prepare($query);

    $hash = password_hash($_POST['password'], PASSWORD_BCRYPT);

    try {
        $statement->execute(array(
            "uname" => $_POST['username'],
            "pwhash" => $hash,
            "email" => $_POST['email'],
            "pid" => $privilege,
            "usid" => $active
        ));
    } catch (PDOException $ex2) {
        die("Error registering user.");
    }

    echo "You've been registered.";
?>
