<?php

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

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

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

if ($request->isMethod('POST')) {
    if (!Session::checkCsrfToken()) {
        $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'));
    } elseif ($code === '' || !preg_match('/^\d{6}$/', $code)) {
        $errorBag->addGlobal(t('Please enter the 6-digit code'));
    } else {
        $result = $passwordResetService->verifyCode($email, $code);
        if ($result['ok'] ?? false) {
            $sessionStore->set('password_reset_id', (int) $result['reset_id']);
            $sessionStore->remove('password_reset_email');
            Flash::success(t('Code verified'), 'password/reset', 'reset_verified');
            Router::redirect('password/reset');
        } else {
            $errorBag->addGlobal(t('Invalid or expired code'));
        }
    }
}

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