<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
/**
 * Register and handle the section template shortcode
 * Handles both [section_template] and [sifency_template] shortcodes
 */
function sifency_addons_section_template_shortcode( $atts ) {
	$atts = shortcode_atts(
		array(
			'id' => 0,
		),
		$atts,
		'section_template'
	);

	$template_id = (int) $atts['id'];

	if ( ! $template_id ) {
		return '<!-- Sifency: No template ID provided -->';
	}

	$post = get_post( $template_id );

	if ( ! $post || 'section_templates' !== $post->post_type ) {
		return '<!-- Sifency: Template not found or incorrect post type -->';
	}

	if ( ! is_admin() && 'publish' !== $post->post_status && ! current_user_can( 'edit_posts' ) ) {
		return '<!-- Sifency: Template is not published -->';
	}

	static $rendering = array();
	if ( isset( $rendering[ $template_id ] ) ) {
		return '<!-- Sifency: Recursive template detected -->';
	}
	$rendering[ $template_id ] = true;

	$output = '';

	try {
		if ( class_exists( '\Elementor\Plugin' ) ) {
			$elementor_instance = \Elementor\Plugin::instance();

			$is_elementor_template = false;
			if ( method_exists( $elementor_instance->db, 'is_built_with_elementor' ) ) {
				$is_elementor_template = $elementor_instance->db->is_built_with_elementor( $template_id );
			} else {
				$is_elementor_template = ! empty( get_post_meta( $template_id, '_elementor_data', true ) );
			}

			if ( $is_elementor_template ) {
				if ( method_exists( $elementor_instance->frontend, 'get_builder_content_for_display' ) ) {
					if ( function_exists( 'sifency_addons_enqueue_elementor_template_assets' ) ) {
						sifency_addons_enqueue_elementor_template_assets( $template_id, true );
					}
					$output = $elementor_instance->frontend->get_builder_content_for_display( $template_id, true );
				} else {
					$output = $post->post_content;
				}
			} else {
				$output = do_shortcode( wpautop( $post->post_content ) );
			}
		} else {
			$output = do_shortcode( wpautop( $post->post_content ) );
		}
	} catch ( Exception $e ) {
		$output = do_shortcode( wpautop( $post->post_content ) );
	}
	unset( $rendering[ $template_id ] );

	return $output;
}

add_shortcode( 'section_template', 'sifency_addons_section_template_shortcode' );
add_shortcode( 'sifency_template', 'sifency_addons_section_template_shortcode' );
