<?php


/**
Parsing and Preparing block content/text (parent first, children later)
 */
add_filter('render_block_data', 'dragblock_content_parser', 10, 1);
function dragblock_content_parser($parsed_block)
{
	// if ($parsed_block['blockName'] === 'dragblock/text') {
	// 	var_dump('dragblock_content_parser()', $parsed_block['attrs']['dragBlockText'][0]);
	// }
	// this is don't have multilingual text content
	if (empty($parsed_block['attrs']['dragBlockText'])) {
		return $parsed_block;
	}
	// var_dump('CONTENT ' . $parsed_block['attrs']['dragBlockClientId']);

	$content = '';

	$english_us_text = '';	
	$site_locale = get_locale();
	// search for the right text
	foreach ($parsed_block['attrs']['dragBlockText'] as $text) {
		// we may need to add device here later
		if (
			empty($text['slug']) ||
			!isset($text['value']) ||
			'' === $text['value'] ||
			!empty($text['disabled'])
		) {
			continue;
		}		

		// we want to find the text for our current locale only
		if ($site_locale === $text['slug']) {
			$content = $text['value'];
			break;
		}
		if ('' === $english_us_text) {
			$english_us_text = $text['value'];
		}

		// we collect English text for a fallback
		if ('en_US' === $text['slug']) {
			$english_us_text = $text['value'];
			continue;
		}
	}

	// if there is no content for the locale, return the english one
	if ('' === $content && '' !== $english_us_text) {
		$content = $english_us_text;
	}



	// otherwise, return what we collected
	$content = do_shortcode($content);



	// ! don't replace space with &nbsp; because it will disrupted the sentence
	// because the whole sentence now has no space and be considered as a single word
	// this also slowdown the server



	if ($content !== '') {
		$parsed_block['attrs']['dragBlockParsedContent'] = $content;
	}


	



	return $parsed_block;
}


/**
Insert block content/text to output tag (children first, parents later)
 */
add_filter('render_block', 'dragblock_content_inserter', 10, 2);
function dragblock_content_inserter($block_content, $parsed_block)
{
	// var_dump('dragblock_content_inserter()');
	if (!isset($parsed_block['attrs']['dragBlockParsedContent']) ||  $parsed_block['attrs']['dragBlockParsedContent'] === '') {
		return $block_content;
	}
	$tag_close = strrpos($block_content, '</');

	// there is no anchor to insert before
	if (false === $tag_close) {
		return $block_content;
	}

	return (
		substr($block_content, 0, $tag_close) .
		$parsed_block['attrs']['dragBlockParsedContent'] .
		substr($block_content, $tag_close)
	);
}
