<?php
/**
 * Dynamic Categories – Custom Skin
 *
 * @package Theplus
 * @since   6.3.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( empty( $template_id ) || '0' === (string) $template_id ) {
	echo esc_html__( 'Select a Template', 'theplus' );
	return;
}

global $tp_current_dc_term, $tp_dc_render, $tp_index, $wp_query;

if ( ! isset( $tp_index ) ) {
	$tp_index = 0;
}
++$tp_index;

$tp_current_dc_term = $prod_cat;

$template_id = apply_filters( 'Dynamic_Categories_template', $template_id, $prod_cat, $tp_index );
$template_id = get_current_ID( $template_id );

if ( ! $template_id ) {
	$tp_current_dc_term = null;
	return;
}

$tp_dc_render = $prod_cat->term_id . ',' . $template_id;

$_query_injected = ( $wp_query instanceof \WP_Query );

if ( $_query_injected ) {
	$_old = array(
		'queried_object'    => $wp_query->queried_object    ?? null,
		'queried_object_id' => $wp_query->queried_object_id ?? 0,
		'is_tax'            => $wp_query->is_tax            ?? false,
		'is_category'       => $wp_query->is_category       ?? false,
		'is_tag'            => $wp_query->is_tag            ?? false,
		'is_archive'        => $wp_query->is_archive        ?? false,
		'is_singular'       => $wp_query->is_singular       ?? false,
		'is_single'         => $wp_query->is_single         ?? false,
		'is_page'           => $wp_query->is_page           ?? false,
	);

	$wp_query->queried_object    = $prod_cat;
	$wp_query->queried_object_id = (int) $prod_cat->term_id;
	$wp_query->is_tax            = true;
	$wp_query->is_archive        = true;
	$wp_query->is_singular       = false;
	$wp_query->is_single         = false;
	$wp_query->is_page           = false;
	$wp_query->is_category       = ( 'category' === $prod_cat->taxonomy );
	$wp_query->is_tag            = ( 'post_tag' === $prod_cat->taxonomy );
}

$_rendered = \Elementor\Plugin::instance()->frontend->get_builder_content_for_display( $template_id, true );

if ( $_query_injected ) {
	$wp_query->queried_object    = $_old['queried_object'];
	$wp_query->queried_object_id = $_old['queried_object_id'];
	$wp_query->is_tax            = $_old['is_tax'];
	$wp_query->is_archive        = $_old['is_archive'];
	$wp_query->is_category       = $_old['is_category'];
	$wp_query->is_tag            = $_old['is_tag'];
	$wp_query->is_singular       = $_old['is_singular'];
	$wp_query->is_single         = $_old['is_single'];
	$wp_query->is_page           = $_old['is_page'];
}

$tp_current_dc_term = null;
$tp_dc_render       = false;

echo $_rendered;
