<?php

namespace GP_Entry_Blocks\Blocks;


use GP_Entry_Blocks\GF_Queryer;

/**
 * Entry Blocks base block class that handles PHP registration and dynamic rendering if desired.
 *
 * @since 1.0
 */
abstract class Block {
	public $use_php_rendering = true;

	public $tag = 'div';

	public function __construct( $path ) {
		$args = array();

		if ( $this->use_php_rendering ) {
			$args['render_callback'] = array( $this, 'render_with_hooks' );
		}

		register_block_type( $path, $args );
	}

	public function is_block_editor_preview() {
		if ( ! wp_verify_nonce( rgpost( 'blockEditorXHRNonce' ), 'gpeb_block_editor_xhr' ) ) {
			return false;
		}

		return rgpost( 'action' ) === 'gpeb_block_preview';
	}

	/**
	 * Wraps the render method with actions.
	 *
	 * @param array $attributes Block attributes.
	 * @param string $content Block content.
	 * @param \WP_Block $block Block instance.
	 *
	 * @return string
	 */
	public function render_with_hooks( $attributes, $content, $block ) {
		/**
		 * Do something before a GPEB block is rendered.
		 *
		 * This is useful for adding other filters/actions specific to a GPEB block.
		 *
		 * @param \WP_Block $block The block instance.
		 */
		do_action( 'gpeb_before_render_block', $block );

		GF_Queryer::set_current_block( $block );

		$wrapper_attributes = get_block_wrapper_attributes( rgar( $attributes, 'wrapperExtraAttributes', array() ) );

		$output = sprintf(
			'<%1$s %2$s>%3$s</%1$s>',
			$this->tag,
			$wrapper_attributes,
			$this->render( $attributes, $content, $block )
		);

		/**
		 * Do something after a GPEB block is rendered.
		 *
		 * This is useful for removing other filters/actions specific to a GPEB block.
		 *
		 * @param \WP_Block $block The block instance.
		 */
		do_action( 'gpeb_after_render_block', $block );

		GF_Queryer::clear_current_block();

		return $output;
	}

	/**
	 * @param array $attributes Block attributes.
	 * @param string $content Block content.
	 * @param \WP_Block $block Block instance.
	 *
	 * @return string
	 */
	public function render( $attributes, $content, $block ) {
		return $content;
	}

	/**
	 * Escapes Gravity Forms merge tags to prevent replacement in blocks that should not have merge tags replaced in (such as Edit Form).
	 *
	 * @param string $content String with merge tags to escape.
	 *
	 * @return string
	 */
	public function escape_merge_tags( $content ) {
		$content = preg_replace( '/{((.*?)(?::([0-9]+?\.?[0-9]*?))?(:(.+?))?)}/', '#!GPEB!!$1!!GPEB!#', $content );

		return $content;
	}

	/**
	 * Unescapes escaped Gravity Forms merge tags by GP Entry Blocks.
	 *
	 * @param string $content String with escaped merge tags.
	 *
	 * @return string
	 */
	public function unescape_merge_tags( $content ) {
		$content = preg_replace( '/#!GPEB!!(.*?)!!GPEB!#/', '{$1}', $content );

		return $content;
	}
}
