<?php
    session_start();

    include 'db_conn.php';
    include 'mail.php';

    $token = bin2hex(openssl_random_pseudo_bytes(32));

    if (isset($_REQUEST['username']))
    {
        $statement = $db->prepare("SELECT email, user_id FROM Users WHERE username=:uname");
        $statement->execute(array(
            "uname" => $_REQUEST['username']
        ));

        $result = $statement->fetch(PDO::FETCH_ASSOC);
        $user_id = $result['user_id'];
        $email = $result['email'];

        $statement = $db->prepare("INSERT INTO Password_tokens (token, user_id) VALUES (:token, :user_id);");
        $statement->execute(array(
            "token" => $token,
            "user_id" => $user_id
        ));

        send_mail($email, "The link to reset your password is <a href='https://oggle.segfault.party/resetPassword.php?token=$token'>here</a>.<br/>"
                          . "If you did not request this password reset, you can safely ignore this email.", "Password reset");
    } else {
        http_response_code(400);
        die("No username supplied.");
    }
?>
<!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">
            <p>A token has been sent to <?php echo $email; ?>.</p>
        </div>
    </body>
</html>
