<?php

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

$sessionStore = app(SessionStoreInterface::class);

$request = requestInput();
$error = false;
if (!allowRegistration()) {
    Flash::error(t('Registration is currently disabled'), 'login', 'registration_disabled');
    Router::redirect('login');
}

if ($request->isMethod('POST')) {
    if (!actionRequireCsrf('register', flashOnFailure: false, redirectOnFailure: false)) {
        $error = t('Form expired, please try again');
    } elseif ($request->hasBody('email')) {
        $authService = (app(AuthServicesFactory::class))->createAuthService();
        $firstName = $request->bodyString('first_name');
        $lastName = $request->bodyString('last_name');
        $email = $request->bodyString('email');
        $password = (string) $request->body('password', '');
        $password2 = (string) $request->body('password2', '');

        $result = $authService->register([
          'first_name' => $firstName,
          'last_name' => $lastName,
          'email' => $email,
          'password' => $password,
          'password2' => $password2,
        ]);

        if (!($result['ok'] ?? false)) {
            $error = $result['error'] ?? t('User can not be registered');
        } else {
            // Store email in session for verify-email page
            $sessionStore->set('email_verification_email', $result['email'] ?? $email);
            Flash::success(t('Registration successful! Please check your email for the verification code.'), 'verify-email', 'registration_success');
            Router::redirect('verify-email');
        }
    } else {
        $error = t('User can not be registered');
    }
}

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