<?php
/**
 * The public-facing functionality of the plugin.
 *
 * @link        https://wpsmartpost.com/
 * @since      2.0.0
 *
 * @package    Smart_Post_Show_Pro
 * @subpackage Smart_Post_Show_Pro/public
 */

/**
 * The public-facing functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the public-facing stylesheet and JavaScript.
 */
class Smart_Post_Show_Pro_Public {

	/**
	 * Script and style suffix
	 *
	 * @since 2.0.0
	 * @access protected
	 * @var string
	 */
	protected $suffix;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    2.0.0
	 */
	public function __construct() {
		$this->load_public_dependencies();
		$this->pcp_public_action();
	}

	/**
	 * Public dependencies.
	 *
	 * @return void
	 */
	private function load_public_dependencies() {
		require_once SP_PCP_PATH . 'public/helpers/class-post-functions.php';
		require_once SP_PCP_PATH . 'public/helpers/class-pcp-user-like.php';
		new SP_PCP_User_Like();
		require_once SP_PCP_PATH . 'public/helpers/class-pcp-queryinside.php';
		require_once SP_PCP_PATH . 'public/helpers/class-pcp-customfieldprocess.php';
		require_once SP_PCP_PATH . 'public/helpers/compatible/acf.php';
		require_once SP_PCP_PATH . 'public/helpers/class-pcp-shuffle-filter.php';
		require_once SP_PCP_PATH . 'public/helpers/class-pcp-live-filter.php';
		new SP_PCP_Live_Filter();
		require_once SP_PCP_PATH . 'public/helpers/class-loop-html.php';
	}

	/**
	 * Public Action
	 *
	 * @return void
	 */
	private function pcp_public_action() {
		add_action( 'template_redirect', array( $this, 'pcp_handle_site_mode_redirection' ) );
		add_action( 'wp_head', array( $this, 'sp_pcp_post_view' ) );

		add_action( 'wp_ajax_post_grid_ajax', array( $this, 'post_grid_ajax' ) );
		add_action( 'wp_ajax_nopriv_post_grid_ajax', array( $this, 'post_grid_ajax' ) );

		add_action( 'wp_ajax_pcp_post_popup', array( $this, 'pcp_post_popup' ) );
		add_action( 'wp_ajax_nopriv_pcp_post_popup', array( $this, 'pcp_post_popup' ) );

		add_action( 'wp_ajax_pcp_post_popup_next_prev', array( $this, 'pcp_post_popup_next_prev' ) );
		add_action( 'wp_ajax_nopriv_pcp_post_popup_next_prev', array( $this, 'pcp_post_popup_next_prev' ) );

		add_filter( 'et_builder_load_actions', array( $this, 'sp_pcp_divi_builder_load_actions' ) );

		add_action( 'wp_ajax_post_pagination_bar', array( $this, 'post_pagination_bar' ) );
		add_action( 'wp_ajax_nopriv_post_pagination_bar', array( $this, 'post_pagination_bar' ) );

		add_action( 'wp_ajax_post_pagination_bar_mobile', array( $this, 'post_pagination_bar_mobile' ) );
		add_action( 'wp_ajax_nopriv_post_pagination_bar_mobile', array( $this, 'post_pagination_bar_mobile' ) );

		add_action( 'wp_ajax_pcp_post_order', array( $this, 'pcp_post_order' ) );
		add_action( 'wp_ajax_nopriv_pcp_post_order', array( $this, 'pcp_post_order' ) );

		add_shortcode( 'sp_postcarousel', array( $this, 'pcp_shortcode_render' ) );
		add_shortcode( 'smart_post_show', array( $this, 'pcp_shortcode_render' ) );
		// Polylang support.
		add_filter( 'pll_get_post_types', array( $this, 'pcp_polylang_cpt_to_pll' ), 10, 2 );
		// The Events Calendar plugin support.
		if ( is_plugin_active( 'the-events-calendar/the-events-calendar.php' ) || is_plugin_active_for_network( 'the-events-calendar/the-events-calendar.php' ) ) {
			add_filter( 'sp_pcp_custom_meta_filter_value', array( $this, 'sp_event_calendar_cpt_filter_value_modified' ), 10, 2 );
			add_filter( 'sp_pcp_custom_meta_value', array( $this, 'sp_event_calendar_cpt_value_modified' ), 10, 3 );
		}

		/**
		 * YASR plugin compatibility.
		 */
		if ( is_plugin_active( 'yet-another-stars-rating/yet-another-stars-rating.php' ) || is_plugin_active_for_network( 'yet-another-stars-rating/yet-another-stars-rating.php' ) ) {
			add_filter( 'sp_pcp_custom_meta_value', array( $this, 'sp_yasr_cpt_overall_value_modified' ), 10, 3 );
		}

		$this->suffix = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) || ( defined( 'WP_DEBUG' ) && WP_DEBUG ) ? '' : '.min';
		add_action( 'save_post', array( $this, 'delete_page_pcp_option_on_save' ) );
	}

	/**
	 * SPS pro divi builder load actions
	 *
	 * @param  mixed $actions old action param.
	 * @return array
	 */
	public function sp_pcp_divi_builder_load_actions( $actions ) {
		$actions[] = 'pcp_post_popup';
		$actions[] = 'post_grid_ajax';
		$actions[] = 'pcp_post_popup_next_prev';
		$actions[] = 'spf_preview_meta_box';
		$actions[] = 'pcp_admin_post_popup';
		$actions[] = 'post_admin_grid_ajax';
		$actions[] = 'pcp_post_admin_popup_next_prev';
		return $actions;
	}

	/**
	 * Delete page shortcode ids array option on save.
	 *
	 * @param  int $post_ID current post id.
	 * @return void
	 */
	public function delete_page_pcp_option_on_save( $post_ID ) {
		$post_ID    = absint( $post_ID );
		$option_key = 'smart_post_show_page_shortcode_data';

		// Get all stored data (an array of page_id => shortcode IDs).
		$all_data = get_option( $option_key, array() );

		// Remove the entry for this page/post ID if exists.
		if ( isset( $all_data[ $post_ID ] ) ) {
			unset( $all_data[ $post_ID ] );

			update_option( $option_key, $all_data, false ); // Do not autoload.
		}
	}

	/**
	 * * Get current page shortcode data.
	 *
	 * @return array {
	 *     @type int    $page_id       Current page ID.
	 *     @type array  $generator_id  List of shortcode IDs used on this page.
	 *     @type string $option_key    Option key used for retrieval.
	 * }
	 */
	public static function get_page_data() {
		$current_page_id = is_singular() ? absint( get_queried_object_id() ) : 0;

		$option_key = 'smart_post_show_page_shortcode_data';
		$all_data   = get_option( $option_key, array() );

		// Ensure array and sanitize values.
		$found_generator_id = array();
		if ( isset( $all_data[ $current_page_id ] ) && is_array( $all_data[ $current_page_id ] ) ) {
			$found_generator_id = array_map( 'absint', $all_data[ $current_page_id ] );
		}

		return array(
			'page_id'      => $current_page_id,
			'generator_id' => $found_generator_id,
			'option_key'   => $option_key,
		);
	}

	/**
	 * The load google fonts function merge all fonts from shortcodes.
	 *
	 * @param  array $typography store the all shortcode typography.
	 * @return array
	 */
	public static function load_google_fonts( $typography ) {
		$enqueue_fonts = array();
		if ( ! empty( $typography ) ) {
			foreach ( $typography as $font ) {
				if ( isset( $font['font-family'] ) && isset( $font['type'] ) && 'google' === $font['type'] ) {
					$variant         = ( isset( $font['font-weight'] ) && '' !== $font['font-weight'] ) ? ':' . $font['font-weight'] : '';
					$enqueue_fonts[] = $font['font-family'] . $variant;
				}
			}
		}
		$enqueue_fonts = array_unique( $enqueue_fonts );
		return $enqueue_fonts;
	}

	/**
	 * Load dynamic style of the existing shortcode id.
	 *
	 * @param  mixed $found_shows_id to push id option for getting how many shortcode in the page.
	 * @param  mixed $view_options to push all options.
	 * @param  mixed $layouts gets layout type of the plugin.
	 * @return array dynamic style and typography use in the specific shortcode.
	 */
	public static function load_dynamic_style( $found_shows_id, $view_options = '', $layouts = '' ) {
		$setting_options         = get_option( 'sp_post_carousel_settings' );
		$pcp_custom_css          = isset( $setting_options['pcp_custom_css'] ) ? trim( html_entity_decode( $setting_options['pcp_custom_css'] ) ) : '';
		$pcp_enqueue_google_font = isset( $setting_options['pcp_enqueue_google_font'] ) ? $setting_options['pcp_enqueue_google_font'] : true;
		$custom_css              = '';
		$pcp_typography          = array();
		// If multiple shortcode found in the page.
		if ( is_array( $found_shows_id ) ) {
			foreach ( $found_shows_id as $pcp_id ) {
				if ( $pcp_id && is_numeric( $pcp_id ) && get_post_status( $pcp_id ) !== 'trash' ) {
					// Include dynamic style file.
					$view_options = get_post_meta( $pcp_id, 'sp_pcp_view_options', true );
					$layouts      = get_post_meta( $pcp_id, 'sp_pcp_layouts', true );
					if ( is_array( $view_options ) ) {
						include SP_PCP_PATH . 'public/dynamic-css/dynamic-css.php';
					}
				}
			}
		} else {
			// If single shortcode found in the page.
			$pcp_id = $found_shows_id;
			include SP_PCP_PATH . 'public/dynamic-css/dynamic-css.php';
		}
		// Include responsive style.
		include SP_PCP_PATH . 'public/dynamic-css/responsive-css.php';
		// Custom css merge with dynamic style.
		if ( ! empty( $pcp_custom_css ) ) {
			$custom_css .= $pcp_custom_css;
		}
		// Google font enqueue dequeue check.
		$pcp_typography = $pcp_enqueue_google_font ? $pcp_typography : array();
		$dynamic_style  = array(
			'dynamic_css' => SP_PCP_HTML::minify_output( $custom_css ),
			'typography'  => $pcp_typography,
		);
		return $dynamic_style;
	}

	/**
	 * If the option does not exist, it will be created.
	 *
	 * It will be serialized before it is inserted into the database.
	 *
	 * @param  string $post_id existing shortcode id.
	 * @param  array  $get_page_data get current page-id, shortcode-id and option-key from the page.
	 * @return void
	 */
	public static function sps_db_options_update( $post_id, $get_page_data ) {
		$post_id         = absint( $post_id );
		$current_page_id = absint( $get_page_data['page_id'] );
		$option_key      = isset( $get_page_data['option_key'] ) ? sanitize_key( $get_page_data['option_key'] ) : '';
		$found_ids       = isset( $get_page_data['generator_id'] ) && is_array( $get_page_data['generator_id'] )
		? array_map( 'absint', $get_page_data['generator_id'] )
		: array();

		// Exit early if the post ID is already stored.
		if ( in_array( $post_id, $found_ids, true ) || empty( $current_page_id ) ) {
			return;
		}

		$found_ids[] = $post_id;
		$all_data    = get_option( $option_key, array() );

		// Update the page ID's entry with the new list of post IDs.
		$all_data[ $current_page_id ] = $found_ids;
		update_option( $option_key, $all_data, false ); // Do not autoload.
	}

	/**
	 * Polylang_cpt_to_pll
	 *
	 * @param  mixed $post_types post types.
	 * @param  mixed $is_settings hide.
	 * @return array
	 */
	public function pcp_polylang_cpt_to_pll( $post_types, $is_settings ) {

		// enables language and translation management.
		$post_types['sp_post_carousel'] = 'sp_post_carousel';
		return $post_types;
	}

	/**
	 * Custom meta filter value modified for The Events Calendar plugin.
	 *
	 * @param  mixed $value meta value.
	 * @param  mixed $key meta key.
	 * @return statement
	 */
	public function sp_event_calendar_cpt_filter_value_modified( $value, $key ) {
		if ( '_EventOrganizerID' === $key ) {
			$organizer = get_post( $value );
			$value     = isset( $organizer->post_title ) ? $organizer->post_title : '';
		}
		if ( '_EventVenueID' === $key ) {
			$event_venue = get_post( $value );
			$value       = isset( $event_venue->post_title ) ? $event_venue->post_title : '';
		}
		return $value;
	}

	/**
	 * Custom meta value modified for Yasr Rating plugin.
	 *
	 * @param  mixed $value meta value.
	 * @param  mixed $key meta key.
	 * @param  mixed $cf_type fields type.
	 * @return statement
	 */
	public function sp_yasr_cpt_overall_value_modified( $value, $key ) {
		if ( 'yasr_overall_rating' === $key ) {

			// Calculate overall rating.
			$calculate_overall_rating = $value / 5 * 100;

			ob_start();?>

			<div class="yasr-overall-rating">
				<div class="yasr-rater-stars yasr-star-rating" data-rating="<?php echo esc_attr( $value ); ?>" data-rater-starsize="16" style="width: 80px; height: 16px; background-size: 16px;">
					<div class="yasr-star-value" style="background-size: 16px; width: <?php echo esc_attr( $calculate_overall_rating ); ?>%;"></div>
				</div>
			</div>

			<?php
			$value = ob_get_clean();
		}
		return $value;
	}

	/**
	 * Custom meta value modified for The Events Calendar plugin
	 *
	 * @param  mixed $cf_value meta value.
	 * @param  mixed $key meta key.
	 * @param  mixed $cf_type fields type.
	 * @return statement
	 */
	public function sp_event_calendar_cpt_value_modified( $cf_value, $key, $cf_type ) {
		if ( '_EventVenueID' === $key ) {
			$event_venue = get_post( $cf_value );
			if ( is_object( $event_venue ) ) {
				$venue_address = get_post_meta( $cf_value, '_VenueAddress', true );
				$venue_address = isset( $venue_address ) ? ', ' . $venue_address : '';
				$venue_city    = get_post_meta( $cf_value, '_VenueCity', true );
				$venue_city    = isset( $venue_city ) ? ', ' . $venue_city : '';
				$cf_value      = '<strong>' . $event_venue->post_title . '</strong>' . $venue_address . $venue_city;
			}
		}
		if ( '_EventStartDate' === $key ) {
			$event_start_date = apply_filters( 'sp_smart_post_event_start_date_format', 'M d, Y h:i a' );
			$cf_value         = date_i18n( $event_start_date, strtotime( $cf_value ) );
		}
		if ( '_EventEndDate' === $key ) {
			$event_end_date = apply_filters( 'sp_smart_post_event_end_date_format', 'M d, Y h:i a' );
			$cf_value       = date_i18n( $event_end_date, strtotime( $cf_value ) );
		}
		if ( '_EventDuration' === $key ) {
			$time     = (int) $cf_value; // time duration in seconds.
			$days     = floor( $time / ( 60 * 60 * 24 ) );
			$time    -= $days * ( 60 * 60 * 24 );
			$days     = $days > 0 ? $days . __( 'd ', 'smart-post-show-pro' ) : '';
			$hours    = floor( $time / ( 60 * 60 ) );
			$time    -= $hours * ( 60 * 60 );
			$hours    = $hours ? $hours . __( 'h ', 'smart-post-show-pro' ) : '';
			$minutes  = floor( $time / 60 );
			$time    -= $minutes * 60;
			$minutes  = $minutes ? $minutes . __( 'm ', 'smart-post-show-pro' ) : '';
			$seconds  = floor( $time );
			$time    -= $seconds;
			$seconds  = $seconds ? $seconds . __( 's ', 'smart-post-show-pro' ) : '';
			$cf_value = $days . $hours . $minutes . $seconds;
		}
		if ( '_EventOrganizerID' === $key ) {
			$organizer = get_post( $cf_value );
			if ( is_object( $organizer ) ) {
				$organizer_phone = get_post_meta( $cf_value, '_OrganizerPhone', true );
				$organizer_phone = isset( $organizer_phone ) ? ', ' . $organizer_phone : '';
				$organizer_email = get_post_meta( $cf_value, '_OrganizerEmail', true );
				$organizer_email = isset( $organizer_email ) ? ', ' . $organizer_email : '';
				$cf_value        = '<strong>' . $organizer->post_title . '</strong>' . $organizer_phone . $organizer_email;
			}
		}
		return $cf_value;
	}
	/**
	 * Register the stylesheets for the public-facing side of the site.
	 *
	 * @since    2.0.0
	 */
	public function enqueue_styles() {
		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Smart_Post_Show_Pro_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Smart_Post_Show_Pro_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */
		$get_page_data  = self::get_page_data();
		$found_shows_id = $get_page_data['generator_id'];

		if ( empty( $found_shows_id ) || ! is_array( $found_shows_id ) ) {
			return;
		}

		wp_enqueue_style( 'pcp-font-awesome' );
		wp_enqueue_style( 'pcp_swiper' );
		wp_enqueue_style( 'pcp-bxslider' );
		wp_enqueue_style( 'pcp-likes' );
		wp_enqueue_style( 'pcp-popup' );
		wp_enqueue_style( 'pcp_fonttello_icon' );
		wp_enqueue_style( 'pcp_social_icons_style' );
		wp_enqueue_style( 'pcp-style' );
		// Load dynamic style.
		$dynamic_style = self::load_dynamic_style( $found_shows_id );
		$enqueue_fonts = self::load_google_fonts( $dynamic_style['typography'] );
		// Enqueue Google fonts.
		if ( ! empty( $enqueue_fonts ) ) {
			wp_enqueue_style( 'pcp-google-fonts', esc_url( add_query_arg( 'family', rawurlencode( implode( '|', $enqueue_fonts ) ), '//fonts.googleapis.com/css' ) ), array(), SP_PCP_VERSION, false );
		}
		// Add dynamic style.
		wp_add_inline_style( 'pcp-style', $dynamic_style['dynamic_css'] );
	}

	/**
	 * Register the JavaScript and CSS for the public-facing side of the site.
	 *
	 * @since    2.0.0
	 */
	public function register_all_scripts() {
		$pcp_settings        = get_option( 'sp_post_carousel_settings' );
		$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;
		$pcp_swiper_js       = isset( $pcp_settings['pcp_swiper_js'] ) ? $pcp_settings['pcp_swiper_js'] : true;
		/**
		 * This function is provided for demonstration purposes only.
		 *
		 * An instance of this class should be passed to the run() function
		 * defined in Smart_Post_Show_Pro_Loader as all of the hooks are defined
		 * in that particular class.
		 *
		 * The Smart_Post_Show_Pro_Loader will then create the relationship
		 * between the defined hooks and the functions defined in this
		 * class.
		 */
		wp_register_script( 'pcp_swiper', SP_PCP_URL . 'public/assets/js/swiper-bundle.min.js', array( 'jquery' ), SP_PCP_VERSION, true );
		wp_register_script( 'pcp_isotope', SP_PCP_URL . 'public/assets/js/isotope.min.js', array( 'jquery' ), SP_PCP_VERSION, true );
		wp_register_script( 'pcp_bxslider', SP_PCP_URL . 'public/assets/js/jquery.bxslider.min.js', array( 'jquery' ), SP_PCP_VERSION, true );
		wp_register_script( 'pcp_popup', SP_PCP_URL . 'public/assets/js/jquery.magnific-popup.min.js', array( 'jquery' ), SP_PCP_VERSION, true );
		wp_register_script( 'pcp_lazy', SP_PCP_URL . 'public/assets/js/sps-lazyload.min.js', array( 'jquery' ), SP_PCP_VERSION, true );
		wp_register_script( 'pcp_script', SP_PCP_URL . 'public/assets/js/scripts.min.js', array( 'jquery' ), SP_PCP_VERSION, true );
		wp_localize_script(
			'pcp_script',
			'sppcp',
			array(
				'ajaxurl'       => admin_url( 'admin-ajax.php' ),
				'nonce'         => wp_create_nonce( 'sppcp_nonce' ),
				'pcp_swiper_js' => $pcp_swiper_js,
			)
		);
		if ( $pcp_fontawesome_css ) {
			wp_register_style( 'pcp-font-awesome', SP_PCP_URL . 'public/assets/css/font-awesome.min.css', array(), SP_PCP_VERSION, 'all' );
		}
		if ( $pcp_swiper_css ) {
			wp_register_style( 'pcp_swiper', SP_PCP_URL . 'public/assets/css/swiper-bundle.min.css', array(), SP_PCP_VERSION, 'all' );
		}
		if ( $pcp_bxslider_css ) {
			wp_register_style( 'pcp-bxslider', SP_PCP_URL . 'public/assets/css/jquery.bxslider.min.css', array(), SP_PCP_VERSION, 'all' );
		}
		if ( $pcp_like_css ) {
			wp_register_style( 'pcp-likes', SP_PCP_URL . 'public/assets/css/pcp-likes-public.min.css', array(), SP_PCP_VERSION, 'all' );
		}
		if ( $pcp_magnific_css ) {
			wp_register_style( 'pcp-popup', SP_PCP_URL . 'public/assets/css/magnific-popup.min.css', array(), SP_PCP_VERSION, 'all' );
		}
		wp_register_style( 'pcp_fonttello_icon', SP_PCP_URL . 'admin/css/fontello.min.css', array(), SP_PCP_VERSION, 'all' );
		// Social share icon css.
		wp_register_style( 'pcp_social_icons_style', SP_PCP_URL . 'blocks/assets/css/icons.min.css', array(), SP_PCP_VERSION, 'all' );

		wp_register_style( 'pcp-style', SP_PCP_URL . 'public/assets/css/style.min.css', array(), SP_PCP_VERSION, 'all' );

		wp_register_script( 'sp-smart-post-back-to-top', SP_PCP_URL . 'blocks/assets/js/back-to-top.min.js', array(), SMART_POST_SHOW_PRO_VERSION, true );
	}

	/**
	 * Post modal.
	 * No Need to check nonce for readonly data.
	 */
	public static function pcp_post_popup() {
		$post_id              = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : '';
		$smart_show_id        = isset( $_POST['scode_id'] ) ? absint( $_POST['scode_id'] ) : '';
		$view_options         = get_post_meta( $smart_show_id, 'sp_pcp_view_options', true );
		$popup_content_sorter = isset( $view_options['popup_post_content_sorter'] ) ? $view_options['popup_post_content_sorter'] : '';
		$popup_type           = isset( $view_options['pcp_popup_type'] ) ? $view_options['pcp_popup_type'] : 'single_popup';
		$pcp_post             = get_post( $post_id );
		// Modal content divi builder support.
		if ( function_exists( 'et_builder_add_main_elements' ) ) {
			et_builder_add_main_elements();
		}
		?>
		<div class="pcp-modal pcp-modal-<?php echo esc_attr( $smart_show_id ); ?> white-popup">
			<div class="popup_ajax_content">
				<?php
				SP_PCP_HTML::sp_pcp_single_post( $pcp_post, $popup_content_sorter, $view_options );
				?>
			</div>
			<?php if ( 'multi_popup' === $popup_type ) { ?>
				<div class="pcp-popup-button-prev"><i class="fa fa-chevron-left"></i></div>
				<div class="pcp-popup-button-next"><i class="fa fa-chevron-right"></i></div>
			<?php } ?>
		</div>
		<?php
		die();
	}
	/**
	 * Post next prev modal.
	 * No Need to check nonce for readonly data.
	 */
	public static function pcp_post_popup_next_prev() {
		$post_id              = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : '';
		$smart_show_id        = isset( $_POST['scode_id'] ) ? absint( $_POST['scode_id'] ) : '';
		$view_options         = get_post_meta( $smart_show_id, 'sp_pcp_view_options', true );
		$popup_content_sorter = isset( $view_options['popup_post_content_sorter'] ) ? $view_options['popup_post_content_sorter'] : '';
		$pcp_post             = get_post( $post_id );
		SP_PCP_HTML::sp_pcp_single_post( $pcp_post, $popup_content_sorter, $view_options );
		die();
	}

	/**
	 * Post Ajax Pagination.
	 */
	public static function post_grid_ajax() {
		$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'sppcp_nonce' ) ) {
			return false;
		}
		$smart_show_id       = isset( $_POST['id'] ) ? absint( $_POST['id'] ) : '';
		$keyword             = isset( $_POST['keyword'] ) ? sanitize_text_field( wp_unslash( $_POST['keyword'] ) ) : '';
		$orderby             = isset( $_POST['orderby'] ) ? sanitize_text_field( wp_unslash( $_POST['orderby'] ) ) : '';
		$order               = isset( $_POST['order'] ) ? sanitize_text_field( wp_unslash( $_POST['order'] ) ) : '';
		$taxonomy            = isset( $_POST['taxonomy'] ) ? sanitize_text_field( wp_unslash( $_POST['taxonomy'] ) ) : '';
		$term_id             = isset( $_POST['term_id'] ) ? sanitize_text_field( wp_unslash( $_POST['term_id'] ) ) : '';
		$pcp_lang            = isset( $_POST['lang'] ) ? sanitize_text_field( wp_unslash( $_POST['lang'] ) ) : '';
		$author_id           = isset( $_POST['author_id'] ) ? sanitize_text_field( wp_unslash( $_POST['author_id'] ) ) : '';
		$paged               = isset( $_POST['page'] ) ? sanitize_text_field( wp_unslash( $_POST['page'] ) ) : '';
		$custom_fields_array = isset( $_POST['custom_fields_array'] ) ? wp_unslash( $_POST['custom_fields_array'] ) : '';
		$selected_term_list  = isset( $_POST['term_list'] ) ? wp_unslash( $_POST['term_list'] ) : '';
		$layout              = get_post_meta( $smart_show_id, 'sp_pcp_layouts', true );
		$layout_preset       = isset( $layout['pcp_layout_preset'] ) ? $layout['pcp_layout_preset'] : '';
		$view_options        = get_post_meta( $smart_show_id, 'sp_pcp_view_options', true );
		// Post display settings.
		if ( 'filter_layout' === $layout_preset ) {
			$pagination_type        = isset( $view_options['filter_pagination_type'] ) ? $view_options['filter_pagination_type'] : '';
			$pagination_type_mobile = isset( $view_options['filter_pagination_type'] ) ? $view_options['filter_pagination_type'] : '';
		} else {
			$pagination_type        = isset( $view_options['post_pagination_type'] ) ? $view_options['post_pagination_type'] : '';
			$pagination_type_mobile = isset( $view_options['post_pagination_type_mobile'] ) ? $view_options['post_pagination_type_mobile'] : '';
		}

		if ( 'ajax_number' === $pagination_type ) {
			if ( empty( $paged ) ) {
				$paged = isset( $_POST['page'] ) ? sanitize_text_field( wp_unslash( $_POST['page'] ) ) : '';
			}
		}
		$post_content_sorter              = isset( $view_options['post_content_sorter'] ) ? $view_options['post_content_sorter'] : '';
		$query_args                       = SP_PCP_QueryInside::get_filtered_content( $view_options, $smart_show_id, $layout );
		$post_limit                       = isset( $view_options['pcp_post_limit'] ) && ! empty( $view_options['pcp_post_limit'] ) ? $view_options['pcp_post_limit'] : 10000;
		$post_offset                      = isset( $view_options['pcp_post_offset'] ) ? $view_options['pcp_post_offset'] : 0;
		$new_query_args                   = $query_args;
		$new_query_args['fields']         = 'ids';
		$new_query_args['posts_per_page'] = $post_limit;
		$query_post_ids                   = get_posts( $new_query_args );
		$relation                         = isset( $view_options['pcp_filter_by_taxonomy']['pcp_taxonomies_relation'] ) ? $view_options['pcp_filter_by_taxonomy']['pcp_taxonomies_relation'] : 'AND';
		$query_args                       = SP_PCP_Functions::modify_query_params( $query_args, $keyword, $author_id, $custom_fields_array, $orderby, $order, $selected_term_list, $post_offset, $relation, $query_post_ids, $pcp_lang );
		$new_query_args                   = $query_args;
		$new_query_args['fields']         = 'ids';
		$new_query_args['posts_per_page'] = $post_limit;
		$total_posts                      = count( get_posts( $new_query_args ) );
		$post_limit                       = $total_posts;
		if ( $post_limit > 0 ) {
			$post_per_page  = isset( $view_options['post_per_page'] ) ? $view_options['post_per_page'] : '';
			$post_per_click = isset( $view_options['post_load_per_click'] ) ? $view_options['post_load_per_click'] : 12;
			$post_per_page  = ( $post_per_page > $post_limit ) ? $post_limit : $post_per_page;
			$show_adv       = SP_PCP_Functions::pcp_metabox_value( 'show_adv', $view_options );
			if ( $show_adv ) {
				$post_per_page = SP_PCP_Functions::adv_adjust_with_post_per_page( $view_options, $post_per_page );
			}
			if ( $post_limit < 1 ) {
				$total_page = 0;
			} elseif ( ( 'ajax_load_more' === $pagination_type || 'infinite_scroll' === $pagination_type ) && $post_per_click ) {
					$total_page = SP_PCP_Functions::pcp_per_click_max_pages( $post_limit, $post_per_page, $post_per_click );
			} else {
				$total_page = SP_PCP_Functions::pcp_max_pages( $post_limit, $post_per_page );
			}
			$pcp_last_page_post = SP_PCP_Functions::pcp_last_page_post( $post_limit, $post_per_page, $total_page );
			$offset             = (int) $post_per_page * ( $paged - 1 );
			if ( ( 'ajax_load_more' === $pagination_type || 'infinite_scroll' === $pagination_type ) && $post_per_click ) {
				$first_offset = (int) $post_per_page;
				if ( $paged == 2 ) {
					$offset                       = $first_offset;
					$query_args['posts_per_page'] = $post_per_click;
				}
				if ( $paged > 2 ) {
					$offset                       = (int) $post_per_click * ( $paged - 2 );
					$offset                       = $first_offset + $offset;
					$query_args['posts_per_page'] = $post_per_click;
				}
			}
			$query_args['offset'] = (int) $offset + (int) $post_offset;
			if ( $total_page == $paged ) {
				$query_args['posts_per_page'] = $pcp_last_page_post;
			}
			if ( $paged > $total_page ) {
				return false;
			}
		}
		$query_args['paged'] = $paged;
		$pcp_query           = new WP_Query( $query_args );
		SP_PCP_HTML::pcp_get_posts( $view_options, $layout, $post_content_sorter, $pcp_query, $smart_show_id );
		die();
	}

	/**
	 * Post Ajax Pagination.
	 */
	public static function post_pagination_bar() {
		$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'sppcp_nonce' ) ) {
			return false;
		}
		$smart_show_id       = isset( $_POST['id'] ) ? absint( $_POST['id'] ) : '';
		$keyword             = isset( $_POST['keyword'] ) ? sanitize_text_field( wp_unslash( $_POST['keyword'] ) ) : '';
		$orderby             = isset( $_POST['orderby'] ) ? sanitize_text_field( wp_unslash( $_POST['orderby'] ) ) : '';
		$order               = isset( $_POST['order'] ) ? sanitize_text_field( wp_unslash( $_POST['order'] ) ) : '';
		$taxonomy            = isset( $_POST['taxonomy'] ) ? sanitize_text_field( wp_unslash( $_POST['taxonomy'] ) ) : '';
		$term_id             = isset( $_POST['term_id'] ) ? sanitize_text_field( wp_unslash( $_POST['term_id'] ) ) : '';
		$pcp_lang            = isset( $_POST['lang'] ) ? sanitize_text_field( wp_unslash( $_POST['lang'] ) ) : '';
		$author_id           = isset( $_POST['author_id'] ) ? sanitize_text_field( wp_unslash( $_POST['author_id'] ) ) : '';
		$paged               = isset( $_POST['page'] ) ? sanitize_text_field( wp_unslash( $_POST['page'] ) ) : '';
		$custom_fields_array = isset( $_POST['custom_fields_array'] ) ? wp_unslash( $_POST['custom_fields_array'] ) : '';
		$selected_term_list  = isset( $_POST['term_list'] ) ? wp_unslash( $_POST['term_list'] ) : '';
		$view_options        = get_post_meta( $smart_show_id, 'sp_pcp_view_options', true );
		$layout              = get_post_meta( $smart_show_id, 'sp_pcp_layouts', true );
		$layout_preset       = isset( $layout['pcp_layout_preset'] ) ? $layout['pcp_layout_preset'] : '';
		$pagination_type     = isset( $view_options['post_pagination_type'] ) ? $view_options['post_pagination_type'] : '';
		$pagination_type     = isset( $view_options['post_pagination_type_mobile'] ) ? $view_options['post_pagination_type_mobile'] : '';
		$query_args          = SP_PCP_QueryInside::get_filtered_content( $view_options, $smart_show_id, $layout );

		$post_offset                      = isset( $view_options['pcp_post_offset'] ) ? $view_options['pcp_post_offset'] : 0;
		$new_query_args                   = $query_args;
		$new_query_args['fields']         = 'ids';
		$post_limit                       = isset( $view_options['pcp_post_limit'] ) && ! empty( $view_options['pcp_post_limit'] ) ? $view_options['pcp_post_limit'] : 10000;
		$new_query_args['posts_per_page'] = $post_limit;
		$query_post_ids                   = get_posts( $new_query_args );

		$relation           = isset( $view_options['pcp_filter_by_taxonomy']['pcp_taxonomies_relation'] ) ? $view_options['pcp_filter_by_taxonomy']['pcp_taxonomies_relation'] : 'AND';
		$query_args         = SP_PCP_Functions::modify_query_params( $query_args, $keyword, $author_id, $custom_fields_array, $orderby, $order, $selected_term_list, $post_offset, $relation, $query_post_ids, $pcp_lang );
		$query_args['lang'] = '';
		$pcp_query          = new WP_Query( $query_args );
		SP_PCP_HTML::pcp_pagination_bar( $pcp_query, $view_options, $layout, $smart_show_id, $paged );
		die();
	}

	/**
	 * Post Ajax mobile Pagination.
	 */
	public static function post_pagination_bar_mobile() {
		$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'sppcp_nonce' ) ) {
			return false;
		}
		$smart_show_id       = isset( $_POST['id'] ) ? absint( $_POST['id'] ) : '';
		$keyword             = isset( $_POST['keyword'] ) ? sanitize_text_field( wp_unslash( $_POST['keyword'] ) ) : '';
		$orderby             = isset( $_POST['orderby'] ) ? sanitize_text_field( wp_unslash( $_POST['orderby'] ) ) : '';
		$order               = isset( $_POST['order'] ) ? sanitize_text_field( wp_unslash( $_POST['order'] ) ) : '';
		$taxonomy            = isset( $_POST['taxonomy'] ) ? sanitize_text_field( wp_unslash( $_POST['taxonomy'] ) ) : '';
		$term_id             = isset( $_POST['term_id'] ) ? sanitize_text_field( wp_unslash( $_POST['term_id'] ) ) : '';
		$pcp_lang            = isset( $_POST['lang'] ) ? sanitize_text_field( wp_unslash( $_POST['lang'] ) ) : '';
		$author_id           = isset( $_POST['author_id'] ) ? sanitize_text_field( wp_unslash( $_POST['author_id'] ) ) : '';
		$paged               = isset( $_POST['page'] ) ? sanitize_text_field( wp_unslash( $_POST['page'] ) ) : '';
		$selected_term_list  = isset( $_POST['term_list'] ) ? wp_unslash( $_POST['term_list'] ) : '';
		$custom_fields_array = isset( $_POST['custom_fields_array'] ) ? wp_unslash( $_POST['custom_fields_array'] ) : '';
		$view_options        = get_post_meta( $smart_show_id, 'sp_pcp_view_options', true );
		$layout              = get_post_meta( $smart_show_id, 'sp_pcp_layouts', true );
		$layout_preset       = isset( $layout['pcp_layout_preset'] ) ? $layout['pcp_layout_preset'] : '';
		$pagination_type     = isset( $view_options['post_pagination_type'] ) ? $view_options['post_pagination_type'] : '';
		$pagination_type     = isset( $view_options['post_pagination_type_mobile'] ) ? $view_options['post_pagination_type_mobile'] : '';
		$query_args          = SP_PCP_QueryInside::get_filtered_content( $view_options, $smart_show_id, $layout, 'on_mobile' );
		$tax_settings        = array();
		$post_offset         = isset( $view_options['pcp_post_offset'] ) ? $view_options['pcp_post_offset'] : 0;

		$new_query_args                   = $query_args;
		$new_query_args['fields']         = 'ids';
		$post_limit                       = isset( $view_options['pcp_post_limit'] ) && ! empty( $view_options['pcp_post_limit'] ) ? $view_options['pcp_post_limit'] : 10000;
		$new_query_args['posts_per_page'] = $post_limit;
		$query_post_ids                   = get_posts( $new_query_args );
		$query_post_ids                   = array( '' );

		$relation   = isset( $view_options['pcp_filter_by_taxonomy']['pcp_taxonomies_relation'] ) ? $view_options['pcp_filter_by_taxonomy']['pcp_taxonomies_relation'] : 'AND';
		$query_args = SP_PCP_Functions::modify_query_params( $query_args, $keyword, $author_id, $custom_fields_array, $orderby, $order, $selected_term_list, $post_offset, $relation, $query_post_ids, $pcp_lang );
		$pcp_query  = new WP_Query( $query_args );
		SP_PCP_HTML::pcp_pagination_bar( $pcp_query, $view_options, $layout, $smart_show_id, $paged, 'on_mobile' );
		die();
	}

	/**
	 * Post Ajax filter.
	 */
	public static function pcp_post_order() {
		$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'sppcp_nonce' ) ) {
			return false;
		}

		$pcp_current_post_id = isset( $_POST['current_post_id'] ) ? sanitize_text_field( wp_unslash( $_POST['current_post_id'] ) ) : 0;

		$smart_show_id                    = isset( $_POST['id'] ) ? absint( $_POST['id'] ) : '';
		$keyword                          = isset( $_POST['keyword'] ) ? sanitize_text_field( wp_unslash( $_POST['keyword'] ) ) : '';
		$orderby                          = isset( $_POST['orderby'] ) ? sanitize_text_field( wp_unslash( $_POST['orderby'] ) ) : '';
		$order                            = isset( $_POST['order'] ) ? sanitize_text_field( wp_unslash( $_POST['order'] ) ) : '';
		$taxonomy                         = isset( $_POST['taxonomy'] ) ? sanitize_text_field( wp_unslash( $_POST['taxonomy'] ) ) : '';
		$term_id                          = isset( $_POST['term_id'] ) ? sanitize_text_field( wp_unslash( $_POST['term_id'] ) ) : '';
		$pcp_lang                         = isset( $_POST['lang'] ) ? sanitize_text_field( wp_unslash( $_POST['lang'] ) ) : '';
		$author_id                        = isset( $_POST['author_id'] ) ? sanitize_text_field( wp_unslash( $_POST['author_id'] ) ) : '';
		$selected_term_list               = isset( $_POST['term_list'] ) ? wp_unslash( $_POST['term_list'] ) : '';
		$custom_fields_array              = isset( $_POST['custom_fields_array'] ) ? wp_unslash( $_POST['custom_fields_array'] ) : '';
		$layout                           = get_post_meta( $smart_show_id, 'sp_pcp_layouts', true );
		$layout_preset                    = isset( $layout['pcp_layout_preset'] ) ? $layout['pcp_layout_preset'] : '';
		$view_options                     = get_post_meta( $smart_show_id, 'sp_pcp_view_options', true );
		$pagination_type                  = isset( $view_options['post_pagination_type'] ) ? $view_options['post_pagination_type'] : '';
		$pagination_type_mobile           = isset( $view_options['post_pagination_type_mobile'] ) ? $view_options['post_pagination_type_mobile'] : '';
		$post_content_sorter              = isset( $view_options['post_content_sorter'] ) ? $view_options['post_content_sorter'] : '';
		$query_args                       = SP_PCP_QueryInside::get_filtered_content( $view_options, $smart_show_id, $layout );
		$post_offset                      = isset( $view_options['pcp_post_offset'] ) ? $view_options['pcp_post_offset'] : 0;
		$new_query_args                   = $query_args;
		$new_query_args['fields']         = 'ids';
		$post_limit                       = isset( $view_options['pcp_post_limit'] ) && ! empty( $view_options['pcp_post_limit'] ) ? $view_options['pcp_post_limit'] : 10000;
		$new_query_args['posts_per_page'] = $post_limit;
		$query_post_ids                   = get_posts( $new_query_args );

		// Removed current post id.
		$removed_id     = array( $pcp_current_post_id );
		$query_post_ids = array_diff( $query_post_ids, $removed_id );

		$relation   = isset( $view_options['pcp_filter_by_taxonomy']['pcp_taxonomies_relation'] ) ? $view_options['pcp_filter_by_taxonomy']['pcp_taxonomies_relation'] : 'AND';
		$query_args = SP_PCP_Functions::modify_query_params( $query_args, $keyword, $author_id, $custom_fields_array, $orderby, $order, $selected_term_list, $post_offset, $relation, $query_post_ids, $pcp_lang );

		$pcp_query = new WP_Query( $query_args );

		SP_PCP_HTML::pcp_get_posts( $view_options, $layout, $post_content_sorter, $pcp_query, $smart_show_id );
		die();
	}
	/**
	 * Post View Count.
	 */
	public function sp_pcp_post_view() {
		if ( is_single() ) {
			global $post;
			$count_post = esc_attr( get_post_meta( $post->ID, '_post_views_count', true ) );
			if ( '' === $count_post ) {
				$count_post = 1;
				add_post_meta( $post->ID, '_post_views_count', $count_post );
			} else {
				$count_post = (int) $count_post + 1;
				update_post_meta( $post->ID, '_post_views_count', $count_post );
			}
		}
	}

	/**
	 * Handle Site Mode (Maintenance/Coming Soon) redirection.
	 *
	 * @return void
	 */
	public function pcp_handle_site_mode_redirection() {
		$settings         = get_option( 'sp_post_carousel_settings', array() );
		$site_mode        = isset( $settings['pcp_site_mode'] ) ? $settings['pcp_site_mode'] : 'live';
		$redirect_page_id = isset( $settings['pcp_select_page'] ) ? absint( $settings['pcp_select_page'] ) : 0;
		$user_capability  = apply_filters( 'pcp_user_role_permission', 'manage_options' );

		if ( 'live' !== $site_mode && ! empty( $redirect_page_id ) ) {
			if ( ! current_user_can( $user_capability ) ) {
				$current_page_id = get_queried_object_id();
				if ( $current_page_id !== $redirect_page_id ) {
					wp_safe_redirect( get_permalink( $redirect_page_id ) );
					exit;
				}
			}
		}
	}

	/**
	 * Function get layout from atts and create class depending on it.
	 *
	 * @since 2.0
	 * @param array $attribute attribute of this shortcode.
	 */
	public function pcp_shortcode_render( $attribute ) {
		$manage_license     = new Smart_Post_Show_Pro_License( SMART_POST_SHOW_PRO_FILE, SP_PCP_VERSION, 'ShapedPlugin', SP_SPSP_STORE_URL, SP_SPSP_ITEM_ID, SP_PCP_PLUGIN_NAME );
		$license_key_status = $manage_license->get_license_status();
		$license_status     = ( is_object( $license_key_status ) && $license_key_status ? $license_key_status->license : '' );
		$valid_and_expired  = array( 'valid', 'expired' );
		$activation_notice  = '';
		if ( ! in_array( $license_status, $valid_and_expired ) ) {
			if ( current_user_can( apply_filters( 'pcp_user_role_permission', 'manage_options' ) ) ) {
				$activation_notice = sprintf(
					'<div class="spsp-license-notice">Please <strong><a href="%1$s">activate</a></strong> the license key to get the output of the <strong>Smart Post Pro</strong> plugin.</div>',
					esc_url( admin_url( 'edit.php?post_type=sp_post_carousel&page=pcp_blocks#settings=license-key' ) )
				);
			}
			return $activation_notice;
		}
		if ( empty( $attribute['id'] ) || 'sp_post_carousel' !== get_post_type( $attribute['id'] ) || 'trash' === get_post_status( $attribute['id'] ) || 'auto-draft' === get_post_status( $attribute['id'] ) ) {
			return;
		}
		// Smart Post Pro global ID for Shortcode metaboxes.
		$smart_show_id = esc_attr( (int) $attribute['id'] );

		// Preset Layouts.
		$layouts = get_post_meta( $smart_show_id, 'sp_pcp_layouts', true );
		$preset  = isset( $layouts['pcp_layout_preset'] ) ? $layouts['pcp_layout_preset'] : 'carousel_layout';
		// 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 );
		ob_start();
		// Shortcode id to push page id option for getting how many shortcode in the page.
		$get_page_data     = self::get_page_data();
		$found_shows_id    = $get_page_data['generator_id'];
		$shortcode_in_page = in_array( (int) $smart_show_id, $found_shows_id, true );
		$carouse_mode      = isset( $layouts['pcp_carousel_mode'] ) ? $layouts['pcp_carousel_mode'] : 'standard';

		// Enqueue styles and scripts only one time if multiple shortcodes are used in a page.
		if ( ! $shortcode_in_page ) {
			wp_enqueue_style( 'pcp-font-awesome' );
			if ( ( 'carousel_layout' === $preset || 'slider_layout' === $preset || 'thumbnails_slider' === $preset ) && 'ticker' !== $carouse_mode ) {
				wp_enqueue_style( 'pcp_swiper' );
			}
			if ( ( 'carousel_layout' === $preset || 'slider_layout' === $preset || 'thumbnails_slider' === $preset ) && 'ticker' === $carouse_mode ) {
				wp_enqueue_style( 'pcp-bxslider' );
			}
			if ( 'popup' === $view_options['pcp_page_link_type'] ) {
				wp_enqueue_style( 'pcp-popup' );
			}
			wp_enqueue_style( 'pcp-likes' );
			wp_enqueue_style( 'pcp_fonttello_icon' );
			wp_enqueue_style( 'pcp-style' );

			// Load dynamic style.
			$dynamic_style = self::load_dynamic_style( $smart_show_id, $view_options, $layouts );
			$enqueue_fonts = self::load_google_fonts( $dynamic_style['typography'] );
			// Enqueue Google fonts.
			if ( ! empty( $enqueue_fonts ) ) {
				wp_enqueue_style( 'pcp-google-fonts' . $smart_show_id, esc_url( add_query_arg( 'family', rawurlencode( implode( '|', $enqueue_fonts ) ), '//fonts.googleapis.com/css' ) ), array(), SP_PCP_VERSION, false );
			}
			// Add dynamic style.
			$is_block_theme = function_exists( 'wp_is_block_theme' ) && wp_is_block_theme();
			$is_admin       = ! empty( $attributes['is_admin'] ) ? true : false;
			// For the Block theme frontend page.
			if ( $is_block_theme && ! $is_admin ) {
				wp_add_inline_style( 'pcp-style', $dynamic_style['dynamic_css'] );
			} else {
				echo '<style id="smart_post_show_dynamic_css' . $smart_show_id . '">' . wp_strip_all_tags( $dynamic_style['dynamic_css'] ) . '</style>';
			}
		}
		// Update options if the existing shortcode id option not found.
		self::sps_db_options_update( $smart_show_id, $get_page_data );
		SP_PCP_HTML::pcp_html_show( $view_options, $layouts, $smart_show_id, $section_title );
		return SP_PCP_HTML::minify_output( ob_get_clean() );
	}
}
