<?php

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

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

/**
 * Plus Addons Dynamic Tag - Product Title
 *
 * Provides a dynamic tag for Elementor to output the current product title.
 *
 * @since 6.4.5
 */
class ThePlus_Dynamic_Tag_Product_Title 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-title';
	}

    /**
     * Label shown in Elementor Dynamic Tags list.
     *
     * @since 6.4.5
     * @return string
     */
	public function get_title(): string {
		return esc_html__( 'Product Title', '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 (Text) for this dynamic tag.
     *
     * @since 6.4.5
     * @return array
     */
	public function get_categories(): array {
		return [
			Module::TEXT_CATEGORY,
		];
	}

    /**
     * Indicates that settings panel should be shown (even if empty).
     *
     * @since 6.4.5
     * @return bool
     */
    public function is_settings_required() {
		return true;
	}

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

	/**
	 * Resolves the current product ID.
	 *
	 * @since 6.4.5
	 * @return int|null The product ID or null if not found.
	 */
	private function resolve_product_id() {
		if ( function_exists( 'wc_get_product' ) ) {
			$product = wc_get_product();
			if ( $product && method_exists( $product, 'get_id' ) ) {
				return (int) $product->get_id();
			}
		}

		$post_id = get_the_ID();
		if ( $post_id && get_post_type( $post_id ) === 'product' ) {
			return (int) $post_id;
		}

		return null;
	}

	/**
	 * Gets the value of the dynamic tag.
	 *
	 * @since 6.4.5
	 * @param array $options Optional. Additional options for value retrieval.
	 * @return string The product title or an empty string if not found.
	 */
	public function get_value( array $options = [] ) {
		$product_id = $this->resolve_product_id();
		if ( ! $product_id ) {
			return '';
		}

		$title = get_the_title( $product_id );
		return $title ? $title : '';
	}

    /**
     * Render the dynamic product title on frontend.
     *
     * Gets the current product ID and prints its title.
     *
     * @since 6.4.5
     * @return void
     */
	public function render(): void {
		echo esc_html( $this->get_value() );
	}
}
