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

class Ec_Template_Builder_Content {

	public static $instance = null;

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

	public function ec_get_render_content( $template_ids = '' ) {
		$content = '';
		if ( is_array( $template_ids ) ) {
			foreach ( $template_ids as $post_id ) {
				$content .= $this->ec_render_content( $post_id );
			}
		} else {
			$content .= $this->ec_render_content( $template_ids );
		}

		return $content;
	}

	public function ec_render_content( $post_id = '' ) {
		global $wp_post_types;

		// Check if the post is published
		if ( 'publish' !== get_post_status( $post_id ) ) {
			return esc_html__( 'Template Not Yet Published.', 'essential-classy-addons-for-elementor' );
		}

		// Elementor Builder
		if ( class_exists( '\Elementor\Plugin' ) && $this->ec_is_elementor_build( $post_id ) ) {
			$has_css = false;
			if ( ( 'internal' === get_option( 'elementor_css_print_method' ) ) || \Elementor\Plugin::$instance->preview->is_preview_mode() ) {
				$has_css = true;
			}
			$content = \Elementor\Plugin::instance()->frontend->get_builder_content_for_display( $post_id, $has_css );  // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			if ( empty( $content ) ) {
				$content = \Elementor\Plugin::instance()->frontend->get_builder_content( $post_id );
			}

			return $content;
		}

		$has_rest_support = $wp_post_types[ ECAFE_POST ]->show_in_rest;

		if ( $has_rest_support ) {
			$output    = '';
			$curr_post = get_post( $post_id, OBJECT );

			if ( has_blocks( $curr_post ) ) {
				$blocks = parse_blocks( $curr_post->post_content );
				foreach ( $blocks as $block ) {
					$output .= render_block( $block );
				}
			} elseif ( isset( $curr_post->post_content ) && ! empty( $curr_post->post_content ) ) {
				$output = $curr_post->post_content;
			}

			ob_start();
			echo do_shortcode( $output );
			return ob_get_clean();  // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		}
	}

	/**
	 * Check Elementor Builder
	 */
	public function ec_is_elementor_build( $post_id ) {
		if ( class_exists( '\Elementor\Plugin' ) ) {
			$document = \Elementor\Plugin::$instance->documents->get( $post_id );
			if ( $document ) {
				return $document->is_built_with_elementor();
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
}
