<?php
/**
 * Dynamic Tag: Post Category Image (Image)
 *
 * @package captain-widgets-kit
 * @since   1.1.0
 */

use Elementor\Core\DynamicTags\Data_Tag;
use Elementor\Modules\DynamicTags\Module;
if ( ! defined( 'ABSPATH' ) ) {
	exit; }
/**
 * Class Captwiki_Tag_Post_Category_Image
 * Returns the thumbnail image attached to the first post category term.
 * Requires a theme or plugin that stores term thumbnails via term meta
 * key 'thumbnail_id'.
 */
class Captwiki_Tag_Post_Category_Image extends Data_Tag {
	/**
	 * Get tag name.
	 *
	 * @return string
	 */
	public function get_name(): string {
		return 'captwiki-tag-post-cat-image'; }
	/**
	 * Get tag title.
	 *
	 * @return string
	 */
	public function get_title(): string {
		return esc_html__( 'Post Category Image', 'captain-widgets-kit' ); }
	/**
	 * Get tag group.
	 *
	 * @return array
	 */
	public function get_group(): array {
		return array( 'captwiki-post' ); }
	/**
	 * Get tag categories.
	 *
	 * @return array
	 */
	public function get_categories(): array {
		return array( Module::IMAGE_CATEGORY, Module::MEDIA_CATEGORY ); }
	/**
	 * Check whether settings are required.
	 *
	 * @return bool
	 */
	public function is_settings_required() {
		return true; }
	/**
	 * Register tag controls.
	 *
	 * @return void
	 */
	protected function register_controls(): void {}
	/**
	 * Handle register advanced section.
	 *
	 * @return mixed
	 */
	protected function register_advanced_section() {}
	/**
	 * Get tag value.
	 *
	 * @param array $options Function parameter.
	 * @return mixed
	 */
	public function get_value( array $options = array() ) {
		$post_id = get_the_ID();
		if ( ! $post_id ) {
			return false; }
		$terms = get_the_terms( $post_id, 'category' );
		if ( empty( $terms ) || is_wp_error( $terms ) ) {
			return false; }
		$term_id  = $terms[0]->term_id;
		$image_id = get_term_meta( $term_id, 'thumbnail_id', true );
		if ( ! $image_id ) {
			return false; }
		$url = wp_get_attachment_image_url( $image_id, 'full' );
		return $url ? array(
			'id'  => $image_id,
			'url' => $url,
		) : false;
	}
	/**
	 * Render tag output.
	 *
	 * @return void
	 */
	public function render(): void {
		$value = $this->get_value();
		if ( ! empty( $value['url'] ) ) {
			echo esc_url( $value['url'] ); }
	}
}
