<?php

use Elementor\Core\DynamicTags\Tag;
use Elementor\Modules\DynamicTags\Module;

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

/**
 * Plus Addons Dynamic Tag – DC Term Description
 *
 * Outputs the description of the current taxonomy term when used inside a
 * Dynamic Categories custom-skin template.
 *
 * Data source priority:
 *   1. $GLOBALS['tp_current_dc_term']  – set by dc-custom.php for each loop item
 *   2. get_queried_object()            – fallback for real taxonomy archive pages
 *
 * @package  Theplus
 * @since    6.4.9
 */
class ThePlus_Dynamic_Tag_DC_Term_Description extends Tag {

	/**
	 * Unique tag slug used internally by Elementor.
	 *
	 * @since  6.4.9
	 * @return string
	 */
	public function get_name(): string {
		return 'plus-tag-dc-term-description';
	}

	/**
	 * Label shown in the Elementor Dynamic Tags panel.
	 *
	 * @since  6.4.9
	 * @return string
	 */
	public function get_title(): string {
		return esc_html__( 'DC Term Description', 'theplus' );
	}

	/**
	 * Group this tag belongs to.
	 *
	 * @since  6.4.9
	 * @return array
	 */
	public function get_group(): array {
		return [ 'plus-opt-dc' ];
	}

	/**
	 * Elementor tag category – Text field.
	 *
	 * @since  6.4.9
	 * @return array
	 */
	public function get_categories(): array {
		return [ Module::TEXT_CATEGORY ];
	}

	// 'fallback' is already registered by Elementor's base Tag class.
	// Do not re-declare it here — doing so causes "Cannot redeclare control" notices.

	/**
	 * Render – echo the term description.
	 *
	 * @since  6.4.9
	 * @return void
	 */
	public function render(): void {

		$description = '';

		// Priority 1: DC custom-skin loop context.
		if (
			isset( $GLOBALS['tp_current_dc_term'] ) &&
			$GLOBALS['tp_current_dc_term'] instanceof \WP_Term
		) {
			$description = $GLOBALS['tp_current_dc_term']->description;
		} else {
			// Priority 2: real taxonomy archive page.
			$queried = get_queried_object();

			if ( $queried instanceof \WP_Term && ! empty( $queried->description ) ) {
				$description = $queried->description;
			}
		}

		if ( empty( $description ) ) {
			$description = $this->get_settings( 'fallback' );
		}

		echo wp_kses_post( $description );
	}
}
