<?php
/**
 * Replace layout.
 *
 * @link        https://wpsmartpost.com/
 * @since      2.3.2
 *
 * @package    Smart_Post_Show_Pro
 * @subpackage Smart_Post_Show_Pro/includes
 */

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

/**
 * Custom post class to register the carousel.
 */
class Smart_Post_Show_Pro_Replace_Layout {

	/**
	 * Instance
	 *
	 * @var instance
	 */
	private static $instance;

	/**
	 * Main query
	 *
	 * @var mixed
	 */
	private $main_query;
	/**
	 * Which page
	 *
	 * @var mixed
	 */
	private $which_page;
	/**
	 * Which view
	 *
	 * @var bool
	 */
	private $which_view = false;
	/**
	 * Fully replace
	 *
	 * @var bool
	 */
	private $full_replace = false;
	/**
	 * Default class
	 *
	 * @var string
	 */
	private $default_class = '';

	/**
	 * Get instance
	 *
	 * @return this
	 */
	public static function get_instance() {
		if ( ! self::$instance ) {
			self::$instance = new Smart_Post_Show_Pro_Replace_Layout();
		}
		return self::$instance;
	}
	/**
	 * Run on class init.
	 *
	 * @return void
	 */
	public function __construct() {
		add_action( 'pre_get_posts', array( $this, 'customize_default_hook_head' ) );
		add_action( 'loop_start', array( $this, 'start_impact_here' ), 0 );
		add_action( 'loop_end', array( $this, 'overwrite_default_data' ), 0 );
	}


	/**
	 * Customize default header info
	 *
	 * @param object $query  main query.
	 * @return void
	 */
	public function customize_default_hook_head( $query ) {
		if ( ! $query->is_main_query() ) {
			return;
		}
		$this->get_page_name( $query );
		$this->get_selected_show( $query );
	}

	/**
	 * Overwrite default data.
	 *
	 * @param  object $query query.
	 * @return void
	 */
	public function overwrite_default_data( $query ) {
		if ( $this->is_right_place( $query ) ) {
			global $wp_query;
			$this->remove_old_data();

			$this->get_new_data( $query );
			$this->which_view = false;
			if ( $this->full_replace ) {
				$wp_query->max_num_pages = 1;
				$wp_query->found_posts   = 1;

				if ( isset( $GLOBALS['woocommerce_loop']['total_pages'] ) ) {
					$GLOBALS['woocommerce_loop']['total_pages'] = 1;
				}
			}
			$this->default_class = '';
		}
	}

	/**
	 * Remove old data.
	 *
	 * @return void
	 */
	private function remove_old_data() {
		$old_layout = ob_get_clean();

		if ( apply_filters( 'spsp_replace_use_old_class', true ) ) {
			// Extract class from theme, to maintain style.
			$matches = array();
			preg_match( '/class="([^"]+)"/', $old_layout, $matches );
			if ( ! empty( $matches[1] ) ) {
				$first_class = preg_replace( '/\d/', '0', $matches[1] );
				// Exclude some classes name.
				$first_class         = preg_replace( '/\s?[^\s]*(google|ad|nocontent)[^\s]*\s?/i', ' ', $first_class );
				$extra_class         = preg_replace( '/\s+/', ' ', $first_class );
				$this->default_class = $extra_class;
			}
		}
	}

	/**
	 * Start impact here
	 *
	 * @param object $query main query.
	 * @return void
	 */
	public function start_impact_here( $query ) {
		if ( $this->is_right_place( $query ) ) {
			ob_start();
		}
	}

	/**
	 * Get check which page.
	 *
	 * @param  object $wp_query main query.
	 * @return void
	 */
	private function get_page_name( $wp_query ) {
		$arr = array(
			'is_date',
			'is_year',
			'is_month',
			'is_day',
			'is_time',
			'is_author',
			'is_category',
			'is_tag',
			'is_tax',
			'is_search',
			'is_home',
			'is_singular',
			'is_post_type_archive',
		);
		foreach ( $arr as $which ) {
			if ( ! empty( $wp_query->$which ) ) {
				$page = str_replace( 'is_', '', $which );

				switch ( $which ) :
					case 'is_date':
					case 'is_year':
					case 'is_month':
					case 'is_day':
					case 'is_time':
						$page = 'time';
						break;

					case 'is_category':
						$page = "tax-$page";
						break;

					case 'is_tag':
						$page = 'tax-post_tag';
						break;
					case 'is_tax':
						$detail = $wp_query->get_queried_object()->taxonomy;
						$page   = "tax-$detail";
						break;

					case 'is_singular':
						if ( $wp_query->is_single ) {
							$detail = ! empty( $wp_query->query_vars['post_type'] ) ? current( (array) $wp_query->query_vars['post_type'] ) : 'post';
						} elseif ( $wp_query->is_page ) {
							$detail = 'page';
						}

						$page = "is_singular-$detail";
						break;

					case 'is_post_type_archive':
						$detail = $wp_query->query_vars['post_type'];
						$page   = "post_type-$detail";
						break;
					endswitch;
				$this->which_page = $page;
				break;
			}
		}
	}

	/**
	 * Get selected show
	 *
	 * @param  mixed $query main query.
	 * @return void
	 */
	private function get_selected_show( $query ) {
		if ( ! $this->which_page ) {
			return;
		}
		$settings = get_option( 'sp_post_carousel_rpl' );
		$page     = $this->which_page;
		if ( strpos( $page, 'post_type' ) !== false ) {
			$settings = isset( $settings['cpt_replace'] ) ? $settings['cpt_replace'] : '';
		}
		if ( strpos( $page, 'tax' ) !== false ) {
			$settings = isset( $settings['tx_replace'] ) ? $settings['tx_replace'] : '';
		}
		$set_key = "sps_$page";
		$is_page = isset( $settings[ $page ] ) && $settings[ $page ] ? true : false;
		if ( $is_page ) {
			if ( $settings[ $set_key ] ) {
				$this->which_view   = $settings[ $set_key ]['pcp_which_show'];
				$this->full_replace = 'change_full' === $settings[ $set_key ]['replace_way'] ? true : false;
				$layout             = get_post_meta( $this->which_view, 'sp_pcp_layouts', true );
				$layout_preset      = isset( $layout['pcp_layout_preset'] ) ? $layout['pcp_layout_preset'] : 'carousel_layout';
				if ( 'carousel_layout' === $layout_preset || 'slider_layout' === $layout_preset || 'thumbnails_slider' === $layout_preset ) {
					$query->set( 'posts_per_page', -1 );
				}
				// Change sorting.
				if ( 'change_sort' === $settings[ $set_key ]['replace_way'] ) {
					$view_options = get_post_meta( $this->which_view, 'sp_pcp_view_options', true );
					// $advanced_filters = isset( $view_options['pcp_advanced_filter'] ) && ! empty( $view_options['pcp_advanced_filter'] ) ? $view_options['pcp_advanced_filter'] : '';
					if ( isset( $view_options['pcp_filter_by_order']['enable_sort_by_filter'] ) && ! empty( $view_options['pcp_filter_by_order']['enable_sort_by_filter'] ) ) {
						$orderby = isset( $view_options['pcp_filter_by_order']['pcp_select_filter_orderby'] ) ? $view_options['pcp_filter_by_order']['pcp_select_filter_orderby'] : '';
						$order   = isset( $view_options['pcp_filter_by_order']['pcp_select_filter_order'] ) ? $view_options['pcp_filter_by_order']['pcp_select_filter_order'] : '';
						$order   = $orderby ? $order : '';
						$query->set( 'orderby', $orderby );
						$query->set( 'order', $order );
					}
				}
				if ( $this->which_view && ! $this->full_replace ) {
					$custom_css          = '';
					$pcp_id              = $this->which_view;
					$view_options        = get_post_meta( $pcp_id, 'sp_pcp_view_options', true );
					$layouts             = get_post_meta( $pcp_id, 'sp_pcp_layouts', true );
					$setting_options     = get_option( 'sp_post_carousel_settings' );
					$pcp_custom_css      = isset( $setting_options['pcp_custom_css'] ) ? $setting_options['pcp_custom_css'] : '';
					$pcp_fontawesome_css = isset( $pcp_settings['pcp_fontawesome_css'] ) ? $pcp_settings['pcp_fontawesome_css'] : true;
					$pcp_swiper_css      = isset( $pcp_settings['pcp_swiper_css'] ) ? $pcp_settings['pcp_swiper_css'] : true;
					$pcp_bxslider_css    = isset( $pcp_settings['pcp_bxSlider_css'] ) ? $pcp_settings['pcp_bxSlider_css'] : true;
					$pcp_like_css        = isset( $pcp_settings['pcp_like_css'] ) ? $pcp_settings['pcp_like_css'] : true;
					$pcp_magnific_css    = isset( $pcp_settings['pcp_magnific_css'] ) ? $pcp_settings['pcp_magnific_css'] : true;
					if ( $pcp_fontawesome_css ) {
						wp_enqueue_style( 'pcp-font-awesome' );
					}
					if ( $pcp_swiper_css ) {
						wp_enqueue_style( 'pcp_swiper' );
					}
					if ( $pcp_bxslider_css ) {
						wp_enqueue_style( 'pcp-bxslider' );
					}
					if ( $pcp_like_css ) {
						wp_enqueue_style( 'pcp-likes' );
					}
					if ( $pcp_magnific_css ) {
						wp_enqueue_style( 'pcp-popup' );
					}
					wp_enqueue_style( 'pcp_fonttello_icon' );
					wp_enqueue_style( 'pcp-style' );
					include SP_PCP_PATH . 'public/dynamic-css/dynamic-css.php';
					include SP_PCP_PATH . 'public/dynamic-css/responsive-css.php';
					if ( ! empty( $pcp_custom_css ) ) {
						$custom_css .= $pcp_custom_css;
					}
					// Add dynamic style.
					wp_add_inline_style( 'pcp-style', SP_PCP_HTML::minify_output( $custom_css ) );
				}
			}
		}
	}

	/**
	 * Is right place
	 *
	 * @param  object $query main query.
	 * @return bool
	 */
	private function is_right_place( $query ) {
		return ! is_feed() && ! is_admin() && $query->is_main_query() && $this->which_view;
	}

	/**
	 * Get new data.
	 *
	 * @param  object $query main query.
	 * @return void
	 */
	public function get_new_data( $query ) {
		if ( ! $this->which_view ) {
			return;
		}
		ob_start();
		$smart_show_id = $this->which_view;
		if ( $this->full_replace ) {
			echo do_shortcode( "[smart_post_show id=$smart_show_id]" );
		} else {
			// Preset Layouts.
			$layout = get_post_meta( $smart_show_id, 'sp_pcp_layouts', true );
			// All the visible options for the Shortcode like – Global, Filter, Display, Popup, Typography etc.
			$view_options  = get_post_meta( $smart_show_id, 'sp_pcp_view_options', true );
			$section_title = get_the_title( $smart_show_id );
			echo '<div class="' . wp_kses_post( $this->default_class ) . '">';
			SP_PCP_HTML::pcp_html_show( $view_options, $layout, $smart_show_id, $section_title, $query );
			echo '</div>';
		}
		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		echo SP_PCP_HTML::minify_output( ob_get_clean() );
	}
}
Smart_Post_Show_Pro_Replace_Layout::get_instance();
