<?php

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

$sessionStore = app(SessionStoreInterface::class);
$session = $sessionStore->all();

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

$resetId = (int) ($session['password_reset_id'] ?? 0);
if ($resetId <= 0) {
    Router::redirect('password/forgot');
}

if ($request->isMethod('POST')) {
    if (!Session::checkCsrfToken()) {
        $errorBag->addGlobal(t('Form expired, please try again'));
    } else {
        $result = $passwordResetService->resetPassword($resetId, $password, $password2);
        if ($result['ok'] ?? false) {
            $sessionStore->remove('password_reset_id');
            $sessionStore->remove('password_reset_email');
            Flash::success(t('Password updated'), 'login', 'password_updated');
            Router::redirect('login');
        } else {
            $errorBag->merge($result['errors'] ?? [t('Password can not be updated')]);
        }
    }
}

$userPasswordPolicyService = (app(UserServicesFactory::class))->createUserPasswordPolicyService();
$passwordHints = $userPasswordPolicyService->hints();
$passwordMinLength = $userPasswordPolicyService->minLength();

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