<?php

/**
Parsing and Preparing attribute values (parent first, children later)
Note: before attribute inserting, the only available attribute in the block content is "class"
 */
add_filter('render_block_data', 'dragblock_attributes_parsing', 10, 1);
function dragblock_attributes_parsing($parsed_block)
{
	// var_dump('dragblock_attributes_parsing()');
	// var_dump('dragblock_attributes_parsing ()', $parsed_block['blockName'], $parsed_block['attrs']);

	if (empty($parsed_block['attrs']['dragBlockAttrs'])) {
		return $parsed_block;
	}

	// var_dump('ATTR ' . $parsed_block['attrs']['dragBlockClientId']);

	$renderedAttrs = array();
	$site_locale = get_locale();
	foreach ($parsed_block['attrs']['dragBlockAttrs'] as $attr) {
		// render enabled attr only
		if (
			!empty($attr['disabled']) ||
			!isset($attr['value']) ||
			empty($attr['slug'])
		) {
			continue;
		}

		// !note: we don't call do shortcode here because
		// we need evidence for the pre-attribute processing

		// attributes that require for a specific language
		if (!empty($attr['locale'])) {
			// if matching locale, assign immediately
			if ($site_locale === $attr['locale']) {
				$renderedAttrs[$attr['slug']] = $attr['value'];
			}
			// otherwise we assign the en_US as a fallback if did not assign before
			else if ('en_US' === $attr['locale'] && empty($renderedAttrs[$attr['slug']])) {
				$renderedAttrs[$attr['slug']] = $attr['value'];
			}
			continue;
		}



		// preprocess some special attributes
		// for sizes attribute
		if ('sizes' === $attr['slug']) {
			if (!empty($attr['devices']) && strlen($attr['devices']) < 3) {
				if ('d' === $attr['devices']) {
					$attr['value'] = '(min-width: 1025px) ' . $attr['value'];
				}
				if ('t' === $attr['devices']) {
					$attr['value'] = '(min-width: 768px) and (max-width: 1024px) ' . $attr['value'];
				}
				if ('m' === $attr['devices']) {
					$attr['value'] = '(max-width: 767px) ' . $attr['value'];
				}
				if ('dt' === $attr['devices'] || 'td' === $attr['devices']) {
					$attr['value'] =  '(min-width: 768px) ' . $attr['value'];
				}
				if ('dm' === $attr['devices'] || 'md' === $attr['devices']) {
					$attr['value'] =  '(min-width: 1025px) ' . $attr['value'] . ', (max-width: 767px) ' . $attr['value'];
				}
				if ('tm' === $attr['devices'] || 'mt' === $attr['devices']) {
					$attr['value'] =  '(max-width: 1024px) ' . $attr['value'];
				}
			}
		}

		// save attributes
		if (empty($renderedAttrs[$attr['slug']])) {
			$renderedAttrs[$attr['slug']] = $attr['value'];
		} else {
			$renderedAttrs[$attr['slug']] .= ', ' . $attr['value'];
		}
	} // and of preprocessed attributes

	// preprocessing missing attributes    
	$is_post_image = false;
	if ('dragblock/image' === $parsed_block['blockName']) {


		// optimize bandwidth using srcset
		if (!empty($renderedAttrs['src'])) {
			// src set for performance
			if (strpos($renderedAttrs['src'], '[dragblock.post.image.src') !== false) {
				$is_post_image = true;
				// $start = strpos($renderedAttrs['src'], '[dragblock.post.image.src');
				// $end = strpos($renderedAttrs['src'], ']', $start);
				// if (empty($renderedAttrs['sizes']) && $end !== false) {
				//     $renderedAttrs['sizes'] = str_replace('[dragblock.post.image.src', '[dragblock.post.image.sizes', substr($renderedAttrs['src'], $start, $end - $start + 1));
				// }
				if (empty($renderedAttrs['alt'])) {
					$renderedAttrs['alt'] = '[dragblock.post.title]';
				}
				if (empty($renderedAttrs['srcset'])) {
					$renderedAttrs['srcset'] = '[dragblock.post.image.srcset]';
				}
			} else {
				$srcsets = dragblock_get_image_srcsets($renderedAttrs['src']);

				if ($srcsets) {
					$renderedAttrs['srcset'] = $srcsets;
				}
			}
		}

		if (empty($renderedAttrs['alt'])) {
			$alt = empty($renderedAttrs['src']) ? '' : esc_attr(basename($renderedAttrs['src']));
			$renderedAttrs['alt'] = empty($alt) ? __('Just a placeholder', 'dragblock') : $alt;
		}

		// if (!empty($renderedAttrs['rel'])) {
		//     if ('preload' === $renderedAttrs['rel'] && !empty($renderedAttrs['src'])) {
		//         global $dragblock_preload;
		//         $dragblock_preload[] = 
		//     }
		//     unset($renderedAttrs['rel'])
		// }

		// load image asynchronously
		if (empty($renderedAttrs['loading'])) {
			$renderedAttrs['loading'] = 'lazy';
			if (empty($renderedAttrs['decoding'])) {
				$renderedAttrs['decoding'] = 'async';
			}
		}
	}

	// fix accessibility
	if ('dragblock/link' === $parsed_block['blockName']) {
		// load image asynchronously
		if (empty($renderedAttrs['aria-label']) && !empty($parsed_block['innerBlocks'])) {
			$aria_label = '';
			foreach ($parsed_block['innerBlocks'] as $child) {
				if (empty($child['attrs'])) {
					continue;
				}
				if ('dragblock/icon' === $child['blockName']) {
					$aria_label = 'Icon';
					continue;
				}
				if ('dragblock/text' !== $child['blockName']) {
					continue;
				}
				if (empty($child['attrs']['dragBlockText'])) {
					continue;
				}


				foreach ($child['attrs']['dragBlockText'] as $text) {
					if (
						empty($text['slug']) ||
						!isset($text['value']) || '' === $text['value'] ||
						!empty($text['disabled'])
					) {
						continue;
					}

					// if matching locale, assign immediately
					if ($site_locale === $text['slug']) {
						$aria_label = $text['value'];
						break;
					}
					// otherwise we assign the en_US as a fallback if did not assign before
					else if ('en_US' === $text['slug']) {
						$aria_label = $text['value'];
					}
				}

				if (!$aria_label) {
					break;
				}

				continue;
			}
			if ($aria_label) {
				$renderedAttrs['aria-label'] = $aria_label;
			}
		}
	}

	// inserting the attributes
	// do_shortcode before esc_attr to avoid escaping "" characters of shortcodes attributes
	// ex: [dragblock.post.image.url size="medium"] will be 
	// [dragblock.post.image.url size=&quot;medium&quot;] if escaped
	$attrString = '';

	/**
	 * If a field in a form has the same name as one of the reseved terms,
	 * then wordpress will redirect to the according page for that name
	 * ex: if a form has a field name "s", then when you submit that form
	 * WP will consider that as a search query and redirect to the search page
	 * then we have to replace that to: __dragblock_wp_reseved_terms_s
	 * when you expect to send that field to your server
	 * 
	 * This is only necessary when the form method is GET and action is [dragblock.form.action]
	 */
	if (!empty($renderedAttrs['name']) && dragblock_is_reseved_terms($renderedAttrs['name'])) {
		$renderedAttrs['name'] .= DRAGBLOCK_WP_RESEVED_TERMS_PLACEHOLDER;
	}


	foreach ($renderedAttrs as $slug => $value) {
		$attr_value = esc_attr(do_shortcode($value));
		// remove empty post images
		if ($slug === 'src' && $is_post_image && empty($attr_value)) {
			$parsed_block['attrs']['dragBlockParsedAttrs'] = '';
			return $parsed_block;
		}
		$attrString .= (sanitize_key($slug) . '="' . $attr_value . '"');
	}

	if ($attrString) {
		$parsed_block['attrs']['dragBlockParsedAttrs'] = $attrString;
	}
	// var_dump('dragblock_attributes_parsing ()', $parsed_block);

	return $parsed_block;
}

/**
Insert attributes to output tag (children first, parents later)
 */
add_filter('render_block', 'dragblock_attributes_insert', 10, 2);
function dragblock_attributes_insert($block_content, $parsed_block)
{
	// var_dump('dragblock_attributes_insert()', $parsed_block['blockName']);

	if (empty($parsed_block['attrs']['dragBlockParsedAttrs'])) {
		// remove empty post images
		if ('dragblock/image' === $parsed_block['blockName']) {
			return '';
		}

		return $block_content;
	}
	$tag_start = strpos($block_content, '<');
	if (false === $tag_start) {
		return $block_content;
	}

	$first_space = strpos($block_content, ' ', $tag_start);
	$tag_end = strpos($block_content, '>', $tag_start);
	$insert_index = $first_space;

	if (false === $insert_index) {
		$insert_index = $tag_end;
	} elseif (false !== $tag_end && $tag_end < $insert_index) {
		$insert_index = $tag_end;
	}

	if (false === $insert_index) {
		return $block_content;
	}

	$block_content = (substr($block_content, 0, $insert_index) . ' ' .
		$parsed_block['attrs']['dragBlockParsedAttrs'] .
		substr($block_content, $insert_index)
	);

	
	return $block_content;
}
