<?php

namespace Formatrica\Registration;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class Email_Verification_Controller
{
    public function maybe_handle_verify_request(): void
    {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- signed-token verification flow, no nonce available
        if (!isset($_GET['fmt_verify']) || $_GET['fmt_verify'] !== '1') {
            return;
        }

        $user_id = isset($_GET['u']) ? absint($_GET['u']) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $token = isset($_GET['t']) ? sanitize_text_field(wp_unslash($_GET['t'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

        if ($user_id <= 0 || $token === '') {
            $this->redirect_with_message('invalid');
            return;
        }

        $service = new Verification_Service();

        if ($service->is_valid_token($user_id, $token)) {
            $service->mark_verified($user_id);
            $this->redirect_with_message('success');
            return;
        }

        $this->redirect_with_message('expired');
    }

    private function redirect_with_message(string $status): void
    {
        $url = add_query_arg([
            'fmt_verify_status' => $status,
        ], wp_login_url());

        wp_safe_redirect($url);
        exit;
    }
}
