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

namespace HCaptcha\Blocksy;

use HCaptcha\Helpers\API;
use HCaptcha\Helpers\HCaptcha;
use HCaptcha\Helpers\Request;
use WP_Error;

/**
 * Class Waitlist.
 */
class Waitlist {
	/**
	 * Script handle.
	 */
	private const HANDLE = 'hcaptcha-blocksy';

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

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

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

	/**
	 * Init hooks.
	 *
	 * @return void
	 */
	private function init_hooks(): void {
		add_action( 'blocksy:woocommerce:product:custom:layer', [ $this, 'before_layer' ], 0 );
		add_action( 'blocksy:woocommerce:product:custom:layer', [ $this, 'after_layer' ], 20 );

		add_filter( 'blocksy:ext:woocommerce-extra:waitlist:subscribe:validate', [ $this, 'verify' ], 10, 3 );

		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 );
	}

	/**
	 * Before Blocksy Waitlist layer.
	 *
	 * @param array|mixed $layer Layer.
	 *
	 * @return void
	 */
	public function before_layer( $layer ): void {
		$layer_id = $layer['id'] ?? '';

		if ( 'product_waitlist' !== $layer_id ) {
			return;
		}

		ob_start();
	}

	/**
	 * After Blocksy Waitlist layer.
	 *
	 * @param array|mixed $layer Layer.
	 *
	 * @return void
	 */
	public function after_layer( $layer ): void {
		$layer_id = $layer['id'] ?? '';

		if ( 'product_waitlist' !== $layer_id ) {
			return;
		}

		$output = ob_get_clean();

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

		// Find the last $search string and insert hcaptcha before it.
		$search  = '<button class="ct-button" type="submit">';
		$replace = HCaptcha::form( $args ) . "\n" . $search;

		$output = str_replace(
			$search,
			$replace,
			$output
		);

		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		echo $output;
	}

	/**
	 * Verify captcha.
	 *
	 * @param ?WP_Error|mixed $value      Validation value.
	 * @param int             $product_id Product ID.
	 * @param string          $email      Email.
	 *
	 * @return ?WP_Error
	 * @noinspection PhpUnusedParameterInspection
	 */
	public function verify( $value, int $product_id, string $email ): ?WP_Error {
		if ( ! ( null === $value || $value instanceof WP_Error ) ) {
			$value = null;
		}

		// phpcs:ignore WordPress.Security.NonceVerification
		$error_message = API::verify( $this->get_entry( $_POST ) );

		if ( null !== $error_message ) {
			$value = $value ?? new WP_Error( 'hcaptcha_error', $error_message );
			$value->add( 'hcaptcha_error', $error_message );
		}

		return $value;
	}

	/**
	 * 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-product-waitlist-form input[type="email"] {
		grid-row: 1;
	}

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

	.ct-product-waitlist-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 {
		$product_id = (int) Request::filter_input( INPUT_POST, 'product_id' );

		$post = get_post( $product_id );

		$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 ) {
			$type = $key;

			if ( ! in_array( $type, [ 'email', 'product_id' ], 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' => 'waitlist',
		];
	}
}
