<?php
/**
 * Registers a no-op `wpps_simple_captcha` Elementor Pro field when the real
 * {@see \SimpleCaptcha\Elementor_Pro_Form_Field} is not registered, so existing
 * form JSON does not still output a second captcha.
 *
 * The concrete class file is only loaded when Elementor Pro's Field_Base exists.
 *
 * @package WP_PowerSuite\Captcha\Shared
 */

namespace WP_PowerSuite\Captcha\Shared;

use WP_PowerSuite\Core\OptionStoreModuleSettingsRepository;

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

/**
 * Elementor Pro: orphan Simple CAPTCHA field registration (safe without Elementor Pro loaded).
 */
final class ElementorWppsScStubField {

	/**
	 * @param \ElementorPro\Modules\Forms\Registrars\Form_Fields_Registrar|mixed $form_fields_registrar Registrar from Elementor Pro.
	 * @return void
	 */
	public static function registerIfNeeded( $form_fields_registrar ): void {
		if ( ! class_exists( '\ElementorPro\Modules\Forms\Fields\Field_Base' ) || ! is_object( $form_fields_registrar ) || ! method_exists( $form_fields_registrar, 'register' ) ) {
			return;
		}
		if ( self::simpleCaptchaRegistersRealElementorField() ) {
			return;
		}
		require_once __DIR__ . '/ElementorWppsScStubFieldType.php';
		$form_fields_registrar->register( new ElementorWppsScStubFieldType() );
	}

	/**
	 * Mirrors {@see \SimpleCaptcha\Module::initElementorForms()} + yield rules.
	 */
	private static function simpleCaptchaRegistersRealElementorField(): bool {
		if ( ! defined( 'ELEMENTOR_PRO_VERSION' ) ) {
			return false;
		}
		if ( ! OptionStoreModuleSettingsRepository::isModuleEnabled( 'simple-captcha' ) ) {
			return false;
		}
		if ( OptionStoreModuleSettingsRepository::isModuleEnabled( 'google-recaptcha' ) || OptionStoreModuleSettingsRepository::isModuleEnabled( 'cloudflare-turnstile' ) ) {
			return false;
		}
		$settings = OptionStoreModuleSettingsRepository::forModule( 'simple-captcha' )->all( [] );
		return is_array( $settings ) && ! empty( $settings['elementor_forms'] );
	}
}
