<?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'] ?? ($_SESSION['password_reset_email'] ?? '')));
$code = trim((string) ($_POST['code'] ?? ''));
$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');
    } elseif ($code === '' || !preg_match('/^\d{6}$/', $code)) {
        $errors[] = t('Please enter the 6-digit code');
    } else {
        $result = $passwordResetService->verifyCode($email, $code);
        if ($result['ok'] ?? false) {
            $_SESSION['password_reset_id'] = (int) $result['reset_id'];
            unset($_SESSION['password_reset_email']);
            Flash::success(t('Code verified'), 'password/reset', 'reset_verified');
            Router::redirect('password/reset');
        } else {
            $errors[] = t('Invalid or expired code');
        }
    }
}

Buffer::set('title', t('Verify code'));
