<?php

use bin\php\Classes\mailBuilder;

if (!isset($_POST['user_email'])) {
    header('Location: /');
    exit;
}

require_once "{$_SERVER['DOCUMENT_ROOT']}/login/php/authFunctions.php";
require_once "{$_SERVER['DOCUMENT_ROOT']}/bin/php/Classes/mailBuilder.php";

$loginAttempts = checkLoginAttempts();

if ($loginAttempts > 5) {
    header('location: /login/forgotPassword.php?result=blocked');
    exit;
}

$user_email = $_POST['user_email'];

$sql = "SELECT * FROM system_users WHERE user_email = ?";
$stmt = $GLOBALS['conn']->prepare($sql);
$stmt->bind_param("s", $user_email);
if (!$stmt->execute()) {
    header('location: /login/forgotPassword.php?result=failed');
    exit;
}

$result = $stmt->get_result();
$user_data = $result->fetch_assoc();

if ($result->num_rows == 0) {
    header('location: /login/forgotPassword.php?result=success');
    exit;
}

if ($user_data['user_status'] != 'active') {
    header('location: /login/forgotPassword.php?result=success');
    exit;
}

$user_uuid = $user_data["user_uuid"];
$user_password_reset_token = bin2hex(random_bytes(32));
$user_password_reset_expires = time() + 86400;

$sql = "UPDATE system_users SET user_password_reset_token = ?, user_password_reset_expires = ? WHERE user_uuid = ?";
$stmt = $GLOBALS['conn']->prepare($sql);
$stmt->bind_param("sss",
    $user_password_reset_token,
    $user_password_reset_expires,
    $user_uuid
);


# Sending an email to the user
$host = $_SERVER['HTTP_HOST'];
$verifyLink = "https://{$host}/login/resetPassword.php?token={$user_password_reset_token}";

$mail = new mailBuilder();
$mail->subject = "Hello " . $user_data['user_full_name'] . ", Here’s Your Password Reset Link";
$mail->addAddress($user_data['user_email'], $user_data['user_first_name']);
$mail->mailText = '
Hello ' . $user_data['user_first_name'] . ',<br><br>

We received a request to reset the password for your account. You can reset your password by clicking the link below.<br>
This link is valid for 24 hours from the time of this request:<br>
<a href="' . $verifyLink . '" class="btn btn-primary">Reset Password</a><br><br>

Or copy and paste the following link into your browser: <br>' . $verifyLink . '<br><br>

If you did not request a password reset, you can safely ignore this message. No changes will be made to your account.<br><br>

Best regards,<br><br>
The Sentri gnome behind the code
';

if ($stmt->execute()) {
    $mail->sendMail();
    addLoginAttempts(); # add login attempt to prevent spamming from the forgot password link
    header('location: /login/forgotPassword.php?result=success');
} else {
    header('location: /login/forgotPassword.php?result=failed');
}

exit;