<?php
namespace ElementorPro\Modules\ThemeBuilder\Widgets;

use Elementor\Widget_Image;
use ElementorPro\Base\Base_Widget_Trait;
use ElementorPro\Base\Markdown_Utils;
use ElementorPro\Plugin;

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

class Category_Image extends Widget_Image {

	use Base_Widget_Trait;

	public function get_name() {
		return 'woocommerce-category-image';
	}

	public function get_title() {
		return esc_html__( 'Category Image', 'elementor-pro' );
	}

	public function get_icon() {
		return 'eicon-featured-image';
	}

	public function get_categories() {
		return [ 'woocommerce-elements', 'woocommerce-elements-single' ];
	}

	public function get_keywords() {
		return [ 'woocommerce', 'category', 'image', 'thumbnail' ];
	}

	public function has_widget_inner_wrapper(): bool {
		return ! Plugin::elementor()->experiments->is_feature_active( 'e_optimized_markup' );
	}

	protected function register_controls() {
		parent::register_controls();

		$this->update_control(
			'image',
			[
				'dynamic' => [
					'default' => Plugin::elementor()->dynamic_tags->tag_data_to_tag_text( null, 'woocommerce-category-image-tag' ),
				],
			],
			[
				'recursive' => true,
			]
		);
	}

	protected function get_html_wrapper_class() {
		return parent::get_html_wrapper_class() . ' elementor-widget-' . parent::get_name();
	}

	public function get_group_name() {
		return 'woocommerce';
	}

	public function render_markdown(): string {
		$markdown = parent::render_markdown();

		if ( '' !== $markdown ) {
			return $markdown;
		}

		$term = get_queried_object();

		if ( ! $term || ! isset( $term->term_id ) ) {
			return '';
		}

		$thumbnail_id = get_term_meta( $term->term_id, 'thumbnail_id', true );

		if ( ! $thumbnail_id ) {
			return '';
		}

		$url = wp_get_attachment_image_url( $thumbnail_id, 'full' );

		if ( ! $url ) {
			return '';
		}

		return Markdown_Utils::image( $url, Markdown_Utils::get_attachment_alt( (int) $thumbnail_id ) );
	}
}
