<?php
/**
 * Dynamic Tag: Post Featured Image (Image/Media)
 *
 * @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_Featured_Image
 * Returns the featured image array (id, url) for use in image/background controls.
 */
class Captwiki_Tag_Post_Featured_Image extends Data_Tag {
	/**
	 * Get tag name.
	 *
	 * @return string
	 */
	public function get_name(): string {
		return 'captwiki-tag-post-featured-image'; }
	/**
	 * Get tag title.
	 *
	 * @return string
	 */
	public function get_title(): string {
		return esc_html__( 'Post Featured 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 {
		$this->add_control(
			'captwiki_fallback_image',
			array(
				'label' => esc_html__( 'Fallback Image', 'captain-widgets-kit' ),
				'type'  => \Elementor\Controls_Manager::MEDIA,
			)
		);
	}
	/**
	 * 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 ) {
			$queried_id = get_queried_object_id();
			if ( $queried_id && get_post( $queried_id ) ) {
				$post_id = $queried_id; }
		}
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( ! $post_id && ! empty( $_REQUEST['post_id'] ) ) {
			$post_id = absint( $_REQUEST['post_id'] ); } // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( ! $post_id ) {
			return false; }
		$thumb_id = get_post_thumbnail_id( $post_id );
		if ( $thumb_id ) {
			return array(
				'id'  => $thumb_id,
				'url' => wp_get_attachment_image_url( $thumb_id, 'full' ),
			);
		}
		$fallback = $this->get_settings( 'captwiki_fallback_image' );
		if ( ! empty( $fallback['id'] ) && ! empty( $fallback['url'] ) ) {
			return array(
				'id'  => $fallback['id'],
				'url' => $fallback['url'],
			);
		}
		return false;
	}
	/**
	 * Render tag output.
	 *
	 * @return void
	 */
	public function render(): void {
		$value = $this->get_value();
		if ( ! empty( $value['url'] ) ) {
			echo esc_url( $value['url'] ); }
	}
}
