<?php
/**
 * Essential Classy Addons For Elementor Load
 *
 * @package Ecafe
 * @since   3.0.24
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}


if ( ! class_exists( 'Ecafe_Elementor_Builder_Load' ) ) {

	class Ecafe_Elementor_Builder_Load {

		public static $instance = null;

		/**
		 * @var Ecafe_Elementor_Builder_Documents
		 */
		public $documents;

		/**
		 * Initiator
		 */
		public static function get_instance() {
			if ( ! isset( self::$instance ) ) {
				self::$instance = new self();
			}
			return self::$instance;
		}

		public function __construct() {
			if ( did_action( 'elementor/loaded' ) && class_exists( '\Elementor\Plugin' ) ) {
				add_action( 'init', array( $this, 'init_elementor' ), -999 );
			}
			add_filter( 'preview_post_link', array( $this, 'ecafe_preview_post_link' ), 10, 2 );
		}

		/*
		 * Init Elementor Documents
		 */
		public function init_elementor() {
			require ECAFE_CLASSES_URL . 'documents/class-ele-builder-documents.php';
			$this->documents = new Ecafe_Elementor_Builder_Documents();
		}

		/*
		 * Preview Post Link
		 */
		public function ecafe_preview_post_link( $link, \WP_Post $post ) {

			if ( isset( $post->post_type ) && ECAFE_POST != $post->post_type ) {
				return $link;
			}
			$curr_post_id = $post->ID;
			$preview      = array();

			$template_type = get_post_meta( $curr_post_id, 'ecafe_build_template_type', true );
			$preview_id    = get_post_meta( $curr_post_id, 'ecafe_build_display_prev', true );

			if ( ! empty( $preview_id ) ) {
				if ( $template_type == 'singular' ) {
					$preview_type = get_post_meta( $curr_post_id, 'ecafe_build_display_singular', true );
				} elseif ( $template_type == 'archives' ) {
					$preview_type = get_post_meta( $curr_post_id, 'ecafe_build_display_archives', true );
				}

				if ( ! empty( $preview_type ) ) {
					$preview['type']         = $template_type;
					$preview['preview_type'] = $preview_type;
					$preview['preview_id']   = $preview_id;
				}
			}

			if ( isset( $preview ) && empty( $preview ) ) {
				return $link;
			}

			if ( isset( $preview['type'] ) ) {
				if ( $preview['type'] == 'singular' ) {
					$post_id = ! empty( $preview['preview_id'] ) ? $preview['preview_id'] : $curr_post_id;
					$link    = get_permalink( $post_id );
				} elseif ( $preview['type'] == 'archives' ) {
					$category_id = ! empty( $preview['preview_id'] ) ? $preview['preview_id'] : $curr_post_id;
					$link        = esc_url( get_category_link( $category_id ) );
				}
			}

			return add_query_arg(
				array(
					'preview_nonce'  => wp_create_nonce( 'post_preview_' . $curr_post_id ),
					'ecafe_template' => $curr_post_id,
				),
				$link
			);
		}
	}

}

if ( ! function_exists( 'ecafe_theme_builder_load' ) ) {

	function ecafe_theme_builder_load() {
		return Ecafe_Elementor_Builder_Load::get_instance();
	}
}

ecafe_theme_builder_load();
