<?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 URL
 *
 * Outputs the archive URL 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_URL 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-url';
	}

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

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

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

	/**
	 * No standard controls needed.
	 *
	 * @since  6.4.9
	 * @return void
	 */
	protected function register_controls(): void {}

	/**
	 * No advanced section needed.
	 *
	 * @since  6.4.9
	 * @return void
	 */
	protected function register_advanced_section(): void {}

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

		$url  = '';
		$term = null;

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

			if ( $queried instanceof \WP_Term ) {
				$term = $queried;
			}
		}

		if ( $term ) {
			$link = get_term_link( $term );
			if ( ! is_wp_error( $link ) ) {
				$url = $link;
			}
		}

		echo esc_url( $url );
	}
}
