<?php

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

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

/**
 * Plus Addons Dynamic Tag - Product Tag URL
 *
 * Provides a dynamic tag for Elementor to output the current product tag url.
 *
 * @since 6.4.5
 */
class ThePlus_Dynamic_Tag_Product_Tag_URL extends Tag {

    /**
     * Unique dynamic tag name used internally by Elementor.
     *
     * @since 6.4.5
     * @return string
     */
	public function get_name(): string {
		return 'plus-tag-product-tag-url';
	}

    /**
     * Label shown in Elementor Dynamic Tags list.
     *
     * @since 6.4.5
     * @return string
     */
	public function get_title(): string {
		return esc_html__( 'Product Tag URL', 'theplus' );
	}

    /**
     * Registers the group under which this tag will appear.
     *
     * @since 6.4.5
     * @return array
     */
	public function get_group(): array {
		return [ 'plus-opt-woocommerce' ];
	}

    /**
     * Defines the category type (URL) for this dynamic tag.
     *
     * @since 6.4.5
     * @return array
     */
	public function get_categories(): array {
		return [
			Module::URL_CATEGORY,
		];
	}

    /**
     * Register controls for this dynamic tag.
     *
     * @since 6.4.5
     * @return void
     */
	protected function register_advanced_section() {}

	/**
     * Register controls for this dynamic tag.
     *
     * @since 6.4.5
     * @return void
     */
	protected function register_controls(): void {}

    /**
     * Render the dynamic product Tag URL on frontend.
     *
     * Gets the current product ID and prints its Tag URL.
     *
     * @since 6.4.5
     * @return void
     */
	public function render(): void {

		// On a product tag archive, return the queried tag's URL.
		if ( function_exists( 'is_product_tag' ) && is_product_tag() ) {
			$queried = get_queried_object();
			if ( $queried instanceof \WP_Term ) {
				$url = get_term_link( $queried );
				if ( ! is_wp_error( $url ) ) {
					echo esc_url( $url );
				}
			}
			return;
		}

		$product_id = get_the_ID();
		if ( ! $product_id ) {
			return;
		}

		$tags = get_the_terms( $product_id, 'product_tag' );
		if ( empty( $tags ) || is_wp_error( $tags ) ) {
			return;
		}

		$tag = $tags[0];
		$url = get_term_link( $tag );

		if ( is_wp_error( $url ) ) {
			return;
		}

		echo esc_url( $url );
	}
}
