<?php

/**
children first, parent later
 */
global $dragblock_form_script_required;
$dragblock_form_script_required = false;

/**
 * Render order
 * 
attributes-uid.php:20 'dragblock_uid_parser()'
database-render.php:62 'dragblock_database_collector()'
content-render.php:10 'dragblock_content_parser()'
attributes-render.php:9 'dragblock_attributes_parsing()'
renderability-render.php:7 'dragblock_renderability_render()'
form-render.php:15 'dragblock_form_render()'
content-render.php:79 'dragblock_content_inserter()'
appearance-enqueue.php:56 'dragblock_appearance_collect_css()'
attributes-uid.php:70 'dragblock_uid_inserter()'
attributes-render.php:231 'dragblock_attributes_insert()'
interactions-enqueue.php:31 'dragblock_interactions_collect_js()'

priority 20 to stay after the attribute-inserter
 */
add_filter('render_block', 'dragblock_form_render', 20, 2);
function dragblock_form_render($block_content, $parsed_block)
{
	// var_dump('dragblock_form_render()', $parsed_block['blockName']);

	// only process blocks from our plugins
	if (
		'dragblock/form' !== $parsed_block['blockName'] ||
		empty($parsed_block['attrs']['dragBlockClientId'])
	) {
		return $block_content;
	}

	// var_dump('dragblock_form_render', $parsed_block['blockName']);
	// if ('dragblock/form' == $parsed_block['blockName'] ) 
	// var_dump('dragblock_form_render', $block_content, $parsed_block);

	// enable form script for the en
	global $dragblock_form_script_required;
	$dragblock_form_script_required = true;

	// only forms that selected to be processed by DragBlock will have to be processed
	// we check in the attributes object, instead of the content to avoid
	// same raw text input in block content
	$has_dragblock_form_action = false;
	if (!empty($parsed_block['attrs']['dragBlockAttrs']) && is_array($parsed_block['attrs']['dragBlockAttrs'])) {
		foreach ($parsed_block['attrs']['dragBlockAttrs'] as $attr) {
			if ('action' === $attr['slug']) {
				if (trim($attr['value']) === DRAGBLOCK_FORM_ACTION_SHORTCODE) {
					$has_dragblock_form_action = true;
				}
				break;
			}
		}
	}

	// we process only the form that is intentionally selected with dragblock.form.action
	if (!$has_dragblock_form_action) {
		// restore back the reserved word because they may be named like that intentionally 
		$block_content = str_replace(DRAGBLOCK_WP_RESEVED_TERMS_PLACEHOLDER, '', $block_content);
		return $block_content;
	}

	// fill the form id
	$form_client_id = '';

	foreach ($parsed_block['attrs']['dragBlockAttrs'] as $attr) {
		if ('name' === $attr['slug']) {
			if ($attr['value']) {
				$form_client_id = $attr['value'];
			}
			break;
		}
	}

	if (!$form_client_id && $parsed_block['attrs']['dragBlockClientId']) {
		$form_client_id = $parsed_block['attrs']['dragBlockClientId'];
	}


	// insert extra inputs to build the security for the form
	$post_end_form = strrpos($block_content, '</form>');
	if (false !== $post_end_form) {
		$extra_input = '';
		// allow us to know which is the form we are working with
		if ($form_client_id) {
			// longer than the rerquirement of register_taxonomy
			if (strlen($form_client_id) > 32) {
				$form_client_id = substr($form_client_id, 0, 32);
			}

			// always sanitize keys
			$form_client_id = sanitize_key($form_client_id);

			$extra_input .= '<input type="hidden" name="' . DRAGBLOCK_FORM_CLIENT_ID_FIELD_NAME . '" value="' . esc_attr($form_client_id) . '"/>';
		}

		// this is to make sure we are working with a from from out plugin
		// at this time, we use JS to field this field to prevent bot to fill the form
		// $extra_input .= wp_nonce_field('dragblock/form-nonce-action', 'dragblock/form-nonce-field', true, false);

		// we use this input to trap bots to fill the input
		// we hide this using our front-end css
		$extra_input .= '<input type="text" name="' . DRAGBLOCK_FORM_TITLE_FIELD_NAME . '" value="">';
		$block_content = substr($block_content, 0, $post_end_form) . ' ' . $extra_input . substr($block_content, $post_end_form);
	}

	// adjust form classes depending on the submission status
	global $dragblock_form_entries_message_error;

	// - alter class name
	// class="wp-block-dragblock-form
	$class_anchor = 'class="';
	$post_class_start = strpos($block_content, $class_anchor);
	if (false === $post_class_start) {
		$class_anchor = 'class=\'';
		$post_class_start = strpos($block_content, $class_anchor);
	}

	if (false !== $post_class_start && isset($dragblock_form_entries_message_error[$form_client_id])) {
		$post_class_start += strlen($class_anchor);
		if (false === $dragblock_form_entries_message_error[$form_client_id]) {
			// dragblock-form-success
			$block_content = substr($block_content, 0, $post_class_start) . 'pass ' . substr($block_content, $post_class_start);
		} else {
			// dragblock-form-error
			$block_content = substr($block_content, 0, $post_class_start) . 'fail ' . substr($block_content, $post_class_start);
		}
	}

	// - fill the form error message
	$block_content = str_replace(
		'[dragblock.form.message.error]',
		!empty($dragblock_form_entries_message_error[$form_client_id]) ? $dragblock_form_entries_message_error[$form_client_id] : '',
		$block_content
	);

	// - empty the dragBlock action
	$block_content = str_replace(DRAGBLOCK_FORM_ACTION_SHORTCODE, '', $block_content);

	return $block_content;
}
