<?php

namespace GPLoker\Inc;

class Advertisement {
	private $enable_auto_insert;
	private $disable_gutenberg;

	public function __construct() {
		$this->enable_auto_insert = Option::get( 'enable_auto_insert_ads', false );

		$this->disable_gutenberg = Option::get( 'disable_gutenberg', false );

		add_action( 'generate_before_header', [ $this, 'adsBeforeHeader' ] );
		add_action( 'generate_after_header', [ $this, 'adsAfterHeader' ] );

		add_shortcode( 'gploker_place_ads1', [ $this, 'ads1' ] );
		add_shortcode( 'gploker_place_ads2', [ $this, 'ads2' ] );
		add_shortcode( 'gploker_place_ads3', [ $this, 'ads3' ] );

		add_action( 'the_content', [ $this, 'autoInsert' ] );
	}

	public function adsBeforeHeader() {
		echo do_shortcode( Option::get( 'place_ads_before_header' ) );
	}

	public function adsAfterHeader() {
		echo do_shortcode( Option::get( 'place_ads_after_header' ) );
	}

	public function ads1() {
		return do_shortcode( Option::get( 'place_ads1' ) );
	}

	public function ads2() {
		return do_shortcode( Option::get( 'place_ads2' ) );
	}

	public function ads3() {
		return do_shortcode( Option::get( 'place_ads3' ) );
	}

	public function autoInsert( $content ) {

		if (
			$this->enable_auto_insert &&
			( is_singular() &&
			  ( empty($this->postTypeAllowed()) || in_array( get_post_type(), $this->postTypeAllowed() ) )
			)
		) {
			$new_content = '';

			if ( $this->disable_gutenberg ) {

				# if user using classic editor
				$explode_p = explode( '</p>', $content );
				$count     = count( $explode_p );
				$half      = ceil( $count / 2 );

				for ( $i = 0; $i < $count; $i ++ ) {
					$new_content .= $explode_p[ $i ] . '</p>';
					if ( $i + 1 == $half ) {
						$new_content .= $this->ads2();
					}
				}

			} else {

				# if user using gutenberg editor
				global $post;
				$blocks = parse_blocks( $post->post_content );
				$count  = count( $blocks );
				if ( $count ) {
					$half = ceil( $count / 2 );
					$n    = 1;
					foreach ( $blocks as $block ) {
						if ( ! empty( $block['blockName'] ) && $block['blockName'] == 'core/paragraph' ) {
							$n ++;
						}

						$new_content .= render_block( $block );

						if ( $n == $half ) {
							$new_content .= $this->ads2();
						}
					}
				}
			}


			return $this->ads1() . $new_content . $this->ads3();
		}

		return $content;
	}

	private function postTypeAllowed() {
		return Option::get( 'post_type_auto_insert_allowed', [] );
	}
}

//new Advertisement();