<?php

namespace ToolsetBlocks\PublicDependencies;

use ToolsetBlocks\PublicDependencies\Dependency\IGeneral;


/**
 * Backend
 *
 * @since 1.1.0
 */
class Backend {
	const CONDITIONAL_SHORTCODE_START_TAG = '[wpv-conditional';

	/** @var IGeneral[] */
	private $dependencies = array();

	/**
	 * Add a content based dependecy
	 *
	 * @param IGeneral $dependency [description]
	 */
	public function add_dependency( IGeneral $dependency ) {
		$this->dependencies[] = $dependency;
	}

	/**
	 * Load registered dependencies
	 */
	public function load_dependencies() {
		if ( ! is_admin() ) {
			// no backend
			return;
		}

		foreach ( $this->dependencies as $dependency ) {
			$dependency->load_dependencies();
		}

		add_filter( 'content_save_pre', [ $this, 'fix_conditional_blocks_content' ], 1000, 1 );
	}

	/**
	 * There is a problem with `<InnerBlocks>`, they add new lines between blocks. It causes that the block is marked as invalid:
	 *   ```
	 *     Content generated by `save` function:
	 *     [wpv-conditional if=" NOT ( empty( '[wpv-current-user info="id"]') AND ( '2' = '223' ) ) " debug="true"][/wpv-conditional]
	 *     Content retrieved from post body:
	 *     [wpv-conditional if=" NOT ( empty( '[wpv-current-user info="id"]') AND ( '2' = '223' ) ) " debug="true"]
	 *     [/wpv-conditional]
	 *   ```
	 * To avoid that, the post content must be modified before it is saved, removing extra lines
	 *
	 * @since Views 3.3/Toolset Blocks 1.3 Changed from regex matching of conditional shortcodes in the content to string matching
	 *        them using a filter provided in Views.
	 */
	public function fix_conditional_blocks_content( $content ) {
		while ( (int) strpos( $content, self::CONDITIONAL_SHORTCODE_START_TAG ) > 0 ) {
			/**
			 * Filters the content and returns the innermost conditional shortcode along with its content.
			 *
			 * @param string $content
			 */
			$match = apply_filters( 'wpv_filter_match_innermost_conditional_shortcode', $content );
			$content = preg_replace( '#-->[\n|\r]+<!--#isU', '--><!--', $content );
			$aux = str_replace( self::CONDITIONAL_SHORTCODE_START_TAG, '[@@@wpv-conditional', $match );
			$content = str_replace( $match, $aux, $content );
		}

		$content = str_replace( '[@@@wpv-conditional', self::CONDITIONAL_SHORTCODE_START_TAG, $content );
		return $content;
	}
}
