<?php
namespace Jet_Engine_Divi_Views\Components\Jet_Engine\Listing;

use ET\Builder\FrontEnd\Assets\CriticalCSS;
use ET\Builder\FrontEnd\Assets\StaticCSS;

// Prevent direct access to the file.
if ( ! defined( 'WPINC' ) ) {
	die;
}

/**
 * Listing preview manager
 */
class Preview {

	protected $view_id;

	/**
	 * Constructor
	 */
	public function __construct( string $view_id ) {

		$this->view_id = $view_id;

		// Custom listing template for Divi Builder listing item preview
		add_filter( 'template_include', [ $this, 'custom_listing_template' ] );

		// Enqueue preview assets for Divi Builder
		if ( ! empty( $_GET['et_fb'] ) && 1 == $_GET['et_fb'] ) {
			add_action( 'wp_enqueue_scripts', [ $this, 'preview_assets' ] );
		}
	}

	/**
	 * Custom listing template
	 *
	 * @param string $template Template path.
	 *
	 * @return string
	 */
	public function custom_listing_template( $template ) {

		global $post;

		if ( is_single()
			&& isset( $post )
			&& jet_engine()->post_type->slug() === $post->post_type
			&& $this->is_divi_view( $post->ID )
		) {
			add_action( 'jet-engine/blank-page/before-content', [ $this, 'open_preview_wrap' ] );
			add_action( 'jet-engine/blank-page/after-content', [ $this, 'close_preview_wrap' ] );

			$template = jet_engine()->plugin_path( 'templates/blank.php' );
		}

		return $template;
	}

	/**
	 * Enqueue preview assets
	 *
	 * @return void
	 */
	public function preview_assets() {
		jet_engine()->frontend->frontend_styles();
		jet_engine()->frontend->preview_scripts();
	}

	/**
	 * Check if current listing is Divi view
	 *
	 * @param int $post_id Post ID.
	 *
	 * @return boolean
	 */
	public function is_divi_view( $post_id ) {

		$view_type = jet_engine()->listings->data->get_listing_type( $post_id );

		return ( $this->view_id === $view_type ) ? true : false;
	}

	/**
	 * Open preview wrap
	 *
	 * @return void
	 */
	public function open_preview_wrap() {
		?>
		<div id="et-boc" class="et-boc" style="max-width: 80%; margin: 40px auto;">
		<?php
	}

	/**
	 * Close preview wrap
	 *
	 * @return void
	 */
	public function close_preview_wrap() {
		?>
		</div>
		<?php
	}
}
