<?php

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

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

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

if ($request->isMethod('POST')) {
    $action = (string) $request->body('action', 'verify');

    if (!actionRequireCsrf('verify-email', flashOnFailure: false, redirectOnFailure: false)) {
        $errorBag->addGlobal(t('Form expired, please try again'));
    } elseif ($action === 'resend') {
        // Resend verification code
        if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errorBag->addGlobal(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)) {
        $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 = $emailVerificationService->verifyCode($email, $code);
        if ($result['ok'] ?? false) {
            $sessionStore->remove('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') {
                $errorBag->addGlobal(t('Too many failed attempts. Please request a new code.'));
            } else {
                $errorBag->addGlobal(t('Invalid or expired code'));
            }
        }
    }
}

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