<?php

namespace WPProofShield\Integration;

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


use WPProofShield\Support\FeatureAccess\FeatureAccess;
use WPProofShield\Support\Settings;
use WPProofShield\Support\UiLanguage;

final class GenericFormGuard {

	public function __construct(
		private Settings $settings,
		private FeatureAccess $feature_access
	) {
	}

	public function register(): void {
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueueAssets' ) );
	}

	public function enqueueAssets(): void {
		if ( ! $this->license_gate->canUse( 'generic_forms' ) || ! $this->settings->isEnabled( 'enabled_generic_forms' ) ) {
			return;
		}

		$selectors_raw = trim( (string) $this->settings->get( 'generic_form_selectors', '' ) );
		if ( $selectors_raw === '' ) {
			return;
		}

		$selectors = array_values( array_filter( array_map( 'trim', explode( "\n", $selectors_raw ) ) ) );
		if ( ! $selectors ) {
			return;
		}

		$contexts = array();
		foreach ( $selectors as $selector ) {
			$contexts[] = array(
				'ctx'      => 'form:' . substr( md5( $selector ), 0, 12 ),
				'selector' => $selector,
			);
		}

		$pow_css_path    = WPSH_DIR . 'assets/css/pow-client.css';
		$pow_js_path     = WPSH_DIR . 'assets/js/pow-client.js';
		$pow_worker_path = WPSH_DIR . 'assets/js/pow-worker.js';
		$pow_css_ver     = is_readable( $pow_css_path ) ? (string) filemtime( $pow_css_path ) : WPSH_VERSION;
		$pow_js_ver      = is_readable( $pow_js_path ) ? (string) filemtime( $pow_js_path ) : WPSH_VERSION;
		$pow_worker_ver  = is_readable( $pow_worker_path ) ? (string) filemtime( $pow_worker_path ) : WPSH_VERSION;
		$pow_worker_url = (string) add_query_arg( 'ver', $pow_worker_ver, WPSH_URL . 'assets/js/pow-worker.js' );
		wp_enqueue_style( 'wpsh-pow-client', WPSH_URL . 'assets/css/pow-client.css', array(), $pow_css_ver );
		wp_enqueue_script( 'wpsh-pow-client', WPSH_URL . 'assets/js/pow-client.js', array(), $pow_js_ver, true );
		$language = UiLanguage::current( $this->settings );
		wp_localize_script(
			'wpsh-pow-client',
			'WPSH_CONFIG',
			array(
				'restUrl'           => esc_url_raw( rest_url( 'wpshield/v1/challenge' ) ),
				'restNonce'         => wp_create_nonce( 'wp_rest' ),
				'workerUrl'         => esc_url_raw( $pow_worker_url ),
				'showDebugUi'       => $this->settings->isEnabled( 'logging_enabled' ) || ( defined( 'WP_DEBUG' ) && WP_DEBUG ),
				'language'          => $language,
				'messages'          => UiLanguage::powMessages( $language ),
				'dynamicDomSupport' => false,
				'contexts'          => $contexts,
			)
		);
	}
}
