<?php

date_default_timezone_set('Asia/Colombo');

require_once 'config/db.php';
require_once 'config/app.php';
require_once 'includes/csrf.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';

$message = '';

if(isset($_POST['submit']))
{
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) die('Invalid request.');
    $email = trim($_POST['email']);

    $stmt = mysqli_prepare(
        $conn,
        "SELECT id FROM users WHERE email=?"
    );

    mysqli_stmt_bind_param($stmt,"s",$email);
    mysqli_stmt_execute($stmt);

    $result = mysqli_stmt_get_result($stmt);

    if(mysqli_num_rows($result) > 0)
    {
        $token = bin2hex(random_bytes(32));

        $expiry = date(
            'Y-m-d H:i:s',
            strtotime('+1 hour')
        );

        $update = mysqli_prepare(
            $conn,
            "UPDATE users
             SET reset_token=?,
                 reset_expiry=?
             WHERE email=?"
        );

        mysqli_stmt_bind_param(
            $update,
            "sss",
            $token,
            $expiry,
            $email
        );

        mysqli_stmt_execute($update);

        $resetLink = BASE_URL . 'reset_password.php?token=' . urlencode($token);

        try
        {
            $mail = new PHPMailer(true);

            $mail->isSMTP();
            $mail->Host       = 'smtp.gmail.com';
            $mail->SMTPAuth   = true;

            $mail->Username   = getenv('SPCHS_SMTP_USERNAME') ?: '';
            $mail->Password   = getenv('SPCHS_SMTP_PASSWORD') ?: '';

            if ($mail->Username === '' || $mail->Password === '') {
                throw new Exception('Mail service is not configured.');
            }

            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port       = 587;

            $mail->setFrom(
                'surveysystem26@gmail.com',
                'Survey System'
            );

            $mail->addAddress($email);

            $mail->isHTML(true);

            $mail->Subject = 'Password Reset';

            $mail->Body = "
            <h3>Password Reset</h3>

            <p>Click the link below to reset your password:</p>

            <a href='{$resetLink}'>
                Reset Password
            </a>

            <p>This link will expire in 1 hour.</p>
            ";

            $mail->send();

            $message =
            "<div class='alert alert-success'>
            Password reset link has been sent to your email.
            </div>";
        }
        catch(Exception $e)
        {
            $message = "<div class='alert alert-success'>If that account exists, a password reset link has been sent.</div>";
        }
    }
    else
    {
        $message = "<div class='alert alert-success'>If that account exists, a password reset link has been sent.</div>";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Forgot Password</title>
</head>
<body>

<h3>Forgot Password</h3>

<?= $message ?>

<form method="POST">

    <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">

    <input
        type="email"
        name="email"
        placeholder="Email Address"
        required>

    <button
        type="submit"
        name="submit">

        Send Reset Link

    </button>

</form>

</body>
</html>
