<?php
/**
 * Newsletter Subscribe class file.
 *
 * @package hcaptcha-wp
 */

namespace HCaptcha\Blocksy;

use HCaptcha\Helpers\API;
use HCaptcha\Helpers\HCaptcha;
use WP_Block;

/**
 * Class `Newsletter Subscribe`.
 */
class NewsletterSubscribe {
	/**
	 * Script handle.
	 */
	private const HANDLE = 'hcaptcha-blocksy';

	/**
	 * Nonce action.
	 */
	private const ACTION = 'hcaptcha_blocksy_newsletter_subscribe';

	/**
	 * Nonce name.
	 */
	private const NONCE = 'hcaptcha_blocksy_newsletter_subscribe_nonce';

	/**
	 * Class constructor.
	 */
	public function __construct() {
		$this->init_hooks();
	}

	/**
	 * Init hooks.
	 *
	 * @return void
	 */
	private function init_hooks(): void {
		add_filter( 'render_block', [ $this, 'add_hcaptcha' ], 10, 3 );
		add_action(
			'wp_ajax_blc_newsletter_subscribe_process_ajax_subscribe',
			[ $this, 'verify' ],
			9
		);
		add_action(
			'wp_ajax_nopriv_blc_newsletter_subscribe_process_ajax_subscribe',
			[ $this, 'verify' ],
			9
		);

		add_action( 'wp_head', [ $this, 'print_inline_styles' ] );
		add_action( 'wp_print_footer_scripts', [ $this, 'enqueue_scripts' ], 9 );
		add_filter( 'script_loader_tag', [ $this, 'add_type_module' ], 10, 3 );
	}

	/**
	 * Render block filter.
	 *
	 * @param string|mixed $block_content Block content.
	 * @param array        $block         Block.
	 * @param WP_Block     $instance      Instance.
	 *
	 * @return string|mixed
	 * @noinspection PhpUnusedParameterInspection
	 */
	public function add_hcaptcha( $block_content, array $block, WP_Block $instance ): string {
		$block_content = (string) $block_content;

		if ( 'blocksy/newsletter' !== $block['blockName'] ) {
			return $block_content;
		}

		$args = [
			'action' => self::ACTION,
			'name'   => self::NONCE,
			'id'     => $this->get_expected_id(),
		];

		$search = '<button';

		return str_replace(
			$search,
			"\n" . HCaptcha::form( $args ) . "\n" . $search,
			$block_content
		);
	}

	/**
	 * Verify.
	 *
	 * @return void
	 */
	public function verify(): void {
		// phpcs:ignore WordPress.Security.NonceVerification.Missing
		$error_message = API::verify( $this->get_entry( $_POST ) );

		if ( null === $error_message ) {
			return;
		}

		wp_send_json_error(
			[
				'result'  => 'no',
				'message' => $error_message,
			]
		);
	}

	/**
	 * Enqueue scripts.
	 *
	 * @return void
	 */
	public function enqueue_scripts(): void {
		if ( ! hcaptcha()->form_shown ) {
			return;
		}

		$min = hcap_min_suffix();

		wp_enqueue_script(
			self::HANDLE,
			HCAPTCHA_URL . "/assets/js/hcaptcha-blocksy$min.js",
			[],
			HCAPTCHA_VERSION,
			true
		);
	}

	/**
	 * Add the type="module" attribute to the script tag.
	 *
	 * @param string|mixed $tag    Script tag.
	 * @param string       $handle Script handle.
	 * @param string       $src    Script source.
	 *
	 * @return string
	 * @noinspection PhpUnusedParameterInspection
	 */
	public function add_type_module( $tag, string $handle, string $src ): string {
		$tag = (string) $tag;

		if ( self::HANDLE !== $handle ) {
			return $tag;
		}

		return HCaptcha::add_type_module( $tag );
	}

	/**
	 * Print inline styles.
	 *
	 * @return void
	 * @noinspection CssUnusedSymbol
	 */
	public function print_inline_styles(): void {
		/* language=CSS */
		$css = '
	.ct-newsletter-subscribe-form input[type="email"] {
		grid-row: 1;
	}

	.ct-newsletter-subscribe-form h-captcha {
		grid-row: 2;
		margin-bottom: 0;
	}

	.ct-newsletter-subscribe-form button {
		grid-row: 3;
	}
';

		HCaptcha::css_display( $css );
	}

	/**
	 * Get entry.
	 *
	 * @param array $form_data Form data.
	 *
	 * @return array
	 */
	private function get_entry( array $form_data ): array {
		global $post;

		$entry = [
			'nonce_name'         => self::NONCE,
			'nonce_action'       => self::ACTION,
			'h-captcha-response' => $form_data['h-captcha-response'] ?? '',
			'form_date_gmt'      => $post->post_modified_gmt ?? null,
			'data'               => [],
			'expected_id'        => $this->get_expected_id(),
		];

		foreach ( $form_data as $key => $value ) {
			$key = strtolower( $key );

			if ( ! in_array( $key, [ 'email', 'group' ], true ) ) {
				continue;
			}

			$entry['data'][ $key ] = $value;
		}

		return $entry;
	}

	/**
	 * Get expected hCaptcha widget id.
	 *
	 * @return array
	 */
	private function get_expected_id(): array {
		return [
			'source'  => HCaptcha::get_class_source( __CLASS__ ),
			'form_id' => 'newsletter-subscribe',
		];
	}
}
