<?php

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

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

if (isset($_POST['email'])) {
  $authService = (new AuthServicesFactory())->createAuthService();
  $firstName = trim((string) ($_POST['first_name'] ?? ''));
  $lastName = trim((string) ($_POST['last_name'] ?? ''));
  $email = trim((string) ($_POST['email'] ?? ''));
  $password = (string) ($_POST['password'] ?? '');
  $password2 = (string) ($_POST['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
    $_SESSION['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');
  }
}

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