<?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['email_verification_email'] ?? '')));
$code = trim((string) ($_POST['code'] ?? ''));
$emailVerificationService = (new AuthServicesFactory())->createEmailVerificationService();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'verify';

    if (!Session::checkCsrfToken()) {
        $errors[] = t('Form expired, please try again');
    } elseif ($action === 'resend') {
        // Resend verification code
        if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors[] = t('Please enter a valid email address');
        } else {
            $result = $emailVerificationService->resendVerification($email);
            if ($result['ok'] ?? false) {
                Flash::success(t('A new verification code has been sent.'), 'verify-email', 'code_resent');
                Router::redirect('verify-email');
            } elseif (($result['error'] ?? '') === 'already_verified') {
                Flash::success(t('Email already verified. Please login.'), 'login', 'already_verified');
                Router::redirect('login');
            } else {
                Flash::success(t('If the email exists, a new verification code has been sent.'), 'verify-email', 'code_resent');
                Router::redirect('verify-email');
            }
        }
    } 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 = $emailVerificationService->verifyCode($email, $code);
        if ($result['ok'] ?? false) {
            unset($_SESSION['email_verification_email']);

            Flash::success(t('Email verified successfully! Please login.'), 'login', 'email_verified');
            Router::redirect('login');
        } else {
            $errorCode = $result['error'] ?? 'invalid';
            if ($errorCode === 'already_verified') {
                Flash::success(t('Email already verified. Please login.'), 'login', 'already_verified');
                Router::redirect('login');
            } elseif ($errorCode === 'too_many_attempts') {
                $errors[] = t('Too many failed attempts. Please request a new code.');
            } else {
                $errors[] = t('Invalid or expired code');
            }
        }
    }
}

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