<?php

namespace wpbuddy\rich_snippets\pro;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
} // Exit if accessed directly


/**
 * Class Admin.
 *
 * Starts up all the frontend things.
 *
 * @package wpbuddy\rich_snippets
 *
 * @since   2.19.0
 */
class Frontend_Controller extends \wpbuddy\rich_snippets\Frontend_Controller {

	public function __construct() {
		Rules_Model::init_filters();
		add_action( 'get_header', [ $this, 'maybe_strip_microdata' ] );
		parent::__construct();

	}

	/**
	 * Initializes values model.
	 *
	 * @since 2.19.0
	 */
	public function init_values_model() {
		new Values_Model();
		$this->values_model_initialized = true;
	}

	/**
	 * Starts the output buffering and filters the content for old microdata.
	 * @since 2.20.0
	 * @see Frontend_Controller::maybe_strip_microdata_end()
	 */
	public function maybe_strip_microdata() {

		if ( is_admin() ) {
			return;
		}

		if ( ! (bool) get_option( 'wpb_rs/setting/remove_microdata_schema', false ) ) {
			return;
		}

		ob_start( function ( $content ) {

			# Finds: itemscope
			$content = preg_replace_callback( '#<[^+>]+(itemscope)#miU', function ( $matches ) {
				return str_replace( $matches[1], '', $matches[0] );
			}, $content );

			# Finds: itemscope="itemscope"
			$content = preg_replace_callback( '#<[^+>]+(itemscope[\s]?=[\s]?"itemscope")#miU', function ( $matches ) {
				return str_replace( $matches[1], '', $matches[0] );
			}, $content );

			# Finds: itemprop="WHATEVER"
			$content = preg_replace_callback( '#<[^+>]+(itemprop[\s]?=[\s]?"[a-zA-Z]+")#miU', function ( $matches ) {
				return str_replace( $matches[1], '', $matches[0] );
			}, $content );

			# Finds: itemtype="https://schema.org/WHATEVER"
			$content = preg_replace_callback( '#<[^+>]+(itemtype[\s]?=[\s]?"http[s]?:\/\/schema.org\/[a-zA-Z]+")#miU', function ( $matches ) {
				return str_replace( $matches[1], '', $matches[0] );
			}, $content );

			return $content;
		} );
	}

}