<?php

use MintyPHP\Buffer;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Service\Auth\AuthServicesFactory;
use MintyPHP\Support\Flash;

$sessionStore = app(SessionStoreInterface::class);

$request = requestInput();
$errorBag = formErrors();
$errors = [];
$email = trim((string) $request->body('email', ''));
$passwordResetService = (app(AuthServicesFactory::class))->createPasswordResetService();

if ($request->isMethod('POST')) {
    if (!actionRequireCsrf('password/forgot', flashOnFailure: false, redirectOnFailure: false)) {
        $errorBag->addGlobal(t('Form expired, please try again'));
    } elseif ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errorBag->addGlobal(t('Please enter a valid email address'));
    } else {
        $passwordResetService->requestReset($email);
        $sessionStore->set('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');
    }
}

$errors = $errorBag->toFlatList();
Buffer::set('title', t('Forgot password'));
