<?php

namespace Formatrica\Registration;

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

use WP_Error;

final class Auth_Guard
{
    /**
     * Prevent login for users who haven't verified email yet.
     *
     * @param null|\WP_User|WP_Error $user
     * @param string $username
     * @param string $password
     * @return null|\WP_User|WP_Error
     */
    public function block_unverified_login($user, string $username, string $password)
    {
        if (is_wp_error($user) || !$user) {
            return $user;
        }

        $wp_user = $user instanceof \WP_User ? $user : null;
        if (!$wp_user) {
            return $user;
        }

        // Never block site administrators or network super admins
        if (user_can($wp_user, 'manage_options') || (function_exists('is_super_admin') && is_super_admin($wp_user->ID))) {
            return $user;
        }

        $verified = get_user_meta($wp_user->ID, 'fmt_verified', true);

        // Only block when explicitly marked as unverified ('0').
        // If the meta is missing, assume legacy user and allow login.
        if ($verified === '0' || $verified === 0) {
            return new WP_Error(
                'fmt_unverified',
                __('Please verify your email address to log in. Check your inbox for the verification link.', 'formatrica')
            );
        }

        return $user;
    }
}
