<?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 Count
 *
 * Outputs the post count of the current taxonomy term when used inside a
 * Dynamic Categories custom-skin template.
 *
 * Supports optional prefix and suffix text (e.g. "(" and " items)").
 *
 * 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_Count 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-count';
	}

	/**
	 * Label shown in the Elementor Dynamic Tags panel.
	 *
	 * @since  6.4.9
	 * @return string
	 */
	public function get_title(): string {
		return esc_html__( 'DC Term Count', '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 ];
	}

	// 'before' and 'after' are already registered by Elementor's base Tag class.
	// Do not re-declare them here — doing so causes "Cannot redeclare control" notices.

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

		$count = null;

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

			if ( $queried instanceof \WP_Term ) {
				$count = (int) $queried->count;
			}
		}

		if ( null === $count ) {
			return;
		}

		$before = $this->get_settings( 'before' );
		$after  = $this->get_settings( 'after' );

		echo wp_kses_post( $before . $count . $after );
	}
}
