<?php
/**
 * Handles enqueuing of JQUEST scripts, when the block is present on a page.
 *
 * @package jQuestPlugin\Scripts
 */

namespace jQuestPlugin\Scripts;

/**
 * Checks the post content for JQUEST blocks and inserts the script if found.
 *
 * @return void
 */
function maybe_insert_jquest_script() {

	if ( ! has_blocks() || ! has_block( 'jquest-inserter/jquest-inserter' ) ) {
		return;
	}

	$has_jquest_blocks = false;
	$version           = false;

	$post = get_post();
	if ( ! $post ) {
		return;
	}

	$blocks = parse_blocks( $post->post_content );
	foreach ( $blocks as $block ) {

		$results = contains_jquest_insterter( $block );

		$has_jquest_blocks = $results['has_jquest_blocks'];
		$version           = $results['version'];
		if ( !$version ) {
			break;
		}
	}
	if ( $has_jquest_blocks ) {

		if($version == 'stable') {
			$url = 'https://files.jquest.fi/jquest/stable/jquest.js';
		} else if($version == 'latest') {
			$url = 'https://files.jquest.fi/jquest/latest/jquest-latest.js';
		}
     // phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped
		?>
		<script
				data-cookieconsent-ignore='true'
				type='module'
				src='<?php echo $url; ?>'></script>
		<?php
     // phpcs:enable WordPress.Security.EscapeOutput.OutputNotEscaped
	}
}

function contains_jquest_insterter( $block ): array {

	$return_value = array(
		'has_jquest_blocks' => false,
		'version'           => false
	);

	if ( 'jquest-inserter/jquest-inserter' === $block['blockName'] ) {
		$return_value['has_jquest_blocks'] = true;
		if ( false === $return_value['version'] ) {
			// Unfortunately, this is the only way to get the default attributes from the block...
			// This could be avoided by just assuming the default value, but then we would need to keep the block.json in sync with this.
			$rendered_block = apply_filters( 'the_content', render_block( $block ) );
			if ( strpos( $rendered_block, 'data-version="stable"' ) !== false ) {
				$return_value['version'] = "stable";
			} if ( strpos( $rendered_block, 'data-version="latest"' ) !== false ) {
				$return_value['version'] = "latest";
			}
		}
	}

	if ( array_key_exists( 'innerBlocks', $block ) ) {
		foreach ( $block['innerBlocks'] as $inner_block ) {
			$inner_values = contains_jquest_insterter( $inner_block );

			$return_value['has_jquest_blocks'] = $return_value['has_jquest_blocks'] || $inner_values['has_jquest_blocks'];
			$return_value['version']     = $return_value['version'];
		}
	}

	return $return_value;
}

add_action( 'wp_head', __NAMESPACE__ . '\maybe_insert_jquest_script' );
