<?php

use MintyPHP\Buffer;
use MintyPHP\Router;
use MintyPHP\Service\Auth\AuthServicesFactory;
use MintyPHP\Session;
use MintyPHP\Support\Flash;

$errors = [];
$email = trim((string) ($_POST['email'] ?? ''));
$passwordResetService = (new AuthServicesFactory())->createPasswordResetService();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!Session::checkCsrfToken()) {
        $errors[] = t('Form expired, please try again');
    } elseif ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = t('Please enter a valid email address');
    } else {
        $passwordResetService->requestReset($email);
        $_SESSION['password_reset_email'] = $email;
        Flash::success(
            t('If the email exists, a verification code has been sent.'),
            'password/verify',
            'reset_requested'
        );
        Router::redirect('password/verify');
    }
}

Buffer::set('title', t('Forgot password'));
