<?php
    session_start();

    include 'db_conn.php';

    $statement = $db->prepare("SELECT user_id, token FROM Password_tokens WHERE token=:token");
    $statement->execute(array(
        "token" => $_REQUEST['token']
    ));

    if ($statement->rowCount() == 0)
    {
        die("Invalid token.");
    }

    if (isset($_POST['password']))
    {
        $user_id = $statement->fetch(PDO::FETCH_ASSOC)['user_id'];

        $statement = $db->prepare("UPDATE Users SET password_hash=:pwhash WHERE user_id=:user_id");
        $statement->execute(array(
            "pwhash" => password_hash($_POST['password'], PASSWORD_BCRYPT),
            "user_id" => $user_id
        ));

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

    if (!isset($_REQUEST['token']))
    {
        http_response_code(401);
        die("Token needed.");
    }
?>
<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta charset="UTF-8">
        <title>OCalendar Password Reset</title>
        <link rel="stylesheet" href="assets/style.css" type="text/css" />
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
    </head>
    <body>
        <div id="header" class="z-depth-1">
            <div id="logo-wrapper" onclick="location='/'"><div id="logo" class="bold"><span class='np blue'>Oggle</span></div>Calendar</div>
            <h3 class="pad-20-around">Password Reset</h3>
        </div>
        <div id="content" class="pad-20 pad-20-around">
            <h1>Reset password</h1>

            <form action="resetPassword.php" method="post">
                <input type="password" name="password" placeholder="New password"/><br/>
                <input type="password" name="password_again" placeholder = "New password (again)"/>
                <input type="hidden" name="token" value="<?php echo $_REQUEST['token']; ?>" />
                <input type="submit" value="Reset"/>
            </form>
        </div>
    </body>
</html>
