<?php

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

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

/**
 * Plus Addons Dynamic Tag – DC Term Image
 *
 * Returns the image (id + url) of the current taxonomy term when used inside
 * a Dynamic Categories custom-skin template.
 *
 * Meta key priority — mirrors the DC widget's own image resolution:
 *   1. tp_taxonomy_image_id   TPAE term image (attachment ID)
 *   2. tp_taxonomy_image      TPAE term image (direct URL fallback)
 *   3. thumbnail_id           WooCommerce product_cat / product_tag
 *   4. Fallback image chosen in the tag settings
 *   5. Elementor placeholder
 *
 * 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_Image extends Data_Tag {

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

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

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

	/**
	 * Elementor tag categories – Image / Media fields.
	 *
	 * @since  6.4.9
	 * @return array
	 */
	public function get_categories(): array {
		return [
			Module::IMAGE_CATEGORY,
			Module::MEDIA_CATEGORY,
		];
	}

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

		$this->add_control(
			'fallback_image',
			[
				'label' => esc_html__( 'Fallback Image', 'theplus' ),
				'type'  => \Elementor\Controls_Manager::MEDIA,
			]
		);
	}

	/**
	 * Resolve image data from a WP_Term using TPAE's own meta key priority.
	 *
	 * @since  6.4.9
	 *
	 * @param  \WP_Term $term  The term to resolve the image for.
	 * @return array           Array with 'id' (int) and 'url' (string).
	 */
	private function resolve_term_image( \WP_Term $term ): array {

		$image_id  = 0;
		$image_url = '';

		// 1. TPAE attachment ID (tp_taxonomy_image_id).
		$tpae_id = get_term_meta( $term->term_id, 'tp_taxonomy_image_id', true );
		if ( ! empty( $tpae_id ) && is_numeric( $tpae_id ) ) {
			$url = wp_get_attachment_image_url( (int) $tpae_id, 'full' );
			if ( $url ) {
				return [
					'id'  => (int) $tpae_id,
					'url' => $url,
				];
			}
		}

		// 2. TPAE direct image URL (tp_taxonomy_image).
		$tpae_url = get_term_meta( $term->term_id, 'tp_taxonomy_image', true );
		if ( ! empty( $tpae_url ) && filter_var( $tpae_url, FILTER_VALIDATE_URL ) ) {
			return [
				'id'  => 0,
				'url' => $tpae_url,
			];
		}

		// 3. WooCommerce thumbnail_id (product_cat / product_tag).
		$wc_id = get_term_meta( $term->term_id, 'thumbnail_id', true );
		if ( ! empty( $wc_id ) && is_numeric( $wc_id ) ) {
			$url = wp_get_attachment_image_url( (int) $wc_id, 'full' );
			if ( $url ) {
				return [
					'id'  => (int) $wc_id,
					'url' => $url,
				];
			}
		}

		return [
			'id'  => $image_id,
			'url' => $image_url,
		];
	}

	/**
	 * Return the image array consumed by Elementor's image/media controls.
	 *
	 * @since  6.4.9
	 *
	 * @param  array $options  Optional options (unused).
	 * @return array           Array with 'id' (int) and 'url' (string).
	 */
	public function get_value( array $options = [] ): array {

		$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;
			}
		}

		// Resolve term image if we have a term.
		if ( $term ) {
			$resolved = $this->resolve_term_image( $term );
			if ( ! empty( $resolved['url'] ) ) {
				return $resolved;
			}
		}

		// 4. Fallback image set in the tag settings panel.
		$fallback = $this->get_settings( 'fallback_image' );
		if ( ! empty( $fallback['url'] ) ) {
			return [
				'id'  => isset( $fallback['id'] ) ? (int) $fallback['id'] : 0,
				'url' => $fallback['url'],
			];
		}

		// 5. Elementor placeholder.
		return [
			'id'  => 0,
			'url' => \Elementor\Utils::get_placeholder_image_src(),
		];
	}

	/**
	 * Render – echo the resolved image URL.
	 *
	 * @since  6.4.9
	 * @return void
	 */
	public function render(): void {
		$value = $this->get_value();
		echo esc_url( $value['url'] ?? '' );
	}
}
