<?php

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

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

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

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

$userPasswordPolicyService = (new UserServicesFactory())->createUserPasswordPolicyService();
$passwordHints = $userPasswordPolicyService->hints();
$passwordMinLength = $userPasswordPolicyService->minLength();

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