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

use Elementor\Controls_Manager;
use Elementor\Group_Control_Image_Size;
use Elementor\Group_Control_Css_Filter;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Group_Control_Text_Shadow;
use Elementor\Core\Kits\Documents\Tabs\Global_Colors;
use Elementor\Core\Kits\Documents\Tabs\Global_Typography;
use Elementor\Utils;
use Elementor\Widget_Base;
use Elementor\Group_Control_Typography;
use Elementor\Plugin;


class Rswpthemes_Awt_Widget_Image extends Widget_Base {

	public function get_name() {
		return 'rswpthemes_awt_image';
	}

	public function get_title() {
		return esc_html__( 'AWT Image', 'elementor' );
	}

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

	public function get_categories() {
		return [ 'basic' ];
	}

	public function get_keywords() {
		return [ 'image', 'photo', 'visual' ];
	}

	protected function is_dynamic_content(): bool {
		return false;
	}

	public function get_style_depends(): array {
		return [ 'rswpthemes_awt_widget-image' ];
	}

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

	protected function register_controls() {
		$this->start_controls_section(
			'rswpthemes_awt_section_image',
			[
				'label' => esc_html__( 'Image', 'elementor' ),
			]
		);

		$this->add_control(
			'rswpthemes_awt_image',
			[
				'label'   => esc_html__( 'Choose Image', 'elementor' ),
				'type'    => Controls_Manager::MEDIA,
				'dynamic' => [ 'active' => true ],
				'media_types'	=> array('image'),
				'default' => [
					'url' => Utils::get_placeholder_image_src(),
				],
			]
		);

		$this->add_control(
		    'rswpthemes_awt_image_url',
		    [
		        'label'   => esc_html__( 'Hidden Image URL', 'elementor' ),
		        'type'    => Controls_Manager::HIDDEN,
		        'default' => '',
		    ]
		);

		// Important: Must match the same control name as above so ID + sizes line up.
		$this->add_group_control(
			Group_Control_Image_Size::get_type(),
			[
				'name'      => 'rswpthemes_awt_image',
				'default'   => 'large',
				'condition' => [
					'rswpthemes_awt_image[url]!' => '',
				],
			]
		);

		$this->add_control(
			'rswpthemes_awt_caption_source',
			[
				'label'     => esc_html__( 'Caption', 'elementor' ),
				'type'      => Controls_Manager::SELECT,
				'options'   => [
					'none'       => esc_html__( 'None', 'elementor' ),
					'attachment' => esc_html__( 'Attachment Caption', 'elementor' ),
					'custom'     => esc_html__( 'Custom Caption', 'elementor' ),
				],
				'default'   => 'none',
				'condition' => [
					'rswpthemes_awt_image[url]!' => '',
				],
			]
		);

		$this->add_control(
			'rswpthemes_awt_caption',
			[
				'label'       => esc_html__( 'Custom Caption', 'elementor' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => '',
				'placeholder' => esc_html__( 'Enter your image caption', 'elementor' ),
				'condition'   => [
					'rswpthemes_awt_image[url]!'       => '',
					'rswpthemes_awt_caption_source' => 'custom',
				],
				'dynamic'     => [ 'active' => true ],
			]
		);

		// Only "none" or "custom" for link_to
		$this->add_control(
			'rswpthemes_awt_link_to',
			[
				'label'     => esc_html__( 'Link', 'elementor' ),
				'type'      => Controls_Manager::SELECT,
				'default'   => 'none',
				'options'   => [
					'none'   => esc_html__( 'None', 'elementor' ),
					'custom' => esc_html__( 'Custom URL', 'elementor' ),
				],
				'condition' => [
					'rswpthemes_awt_image[url]!' => '',
				],
			]
		);

		$this->add_control(
			'rswpthemes_awt_link',
			[
				'label'       => esc_html__( 'Link', 'elementor' ),
				'type'        => Controls_Manager::URL,
				'dynamic'     => [ 'active' => true ],
				'condition'   => [
					'rswpthemes_awt_image[url]!' => '',
					'rswpthemes_awt_link_to'     => 'custom',
				],
				'show_label'  => false,
			]
		);

		// No "Lightbox" control, since you don’t want to use it.

		$this->end_controls_section();

		// ------------------------
		// Image Style Controls
		// ------------------------
		$this->start_controls_section(
			'rswpthemes_awt_section_style_image',
			[
				'label' => esc_html__( 'Image', 'elementor' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			]
		);

		$this->add_responsive_control(
			'rswpthemes_awt_align',
			[
				'label'     => esc_html__( 'Alignment', 'elementor' ),
				'type'      => Controls_Manager::CHOOSE,
				'options'   => [
					'left'   => [
						'title' => esc_html__( 'Left', 'elementor' ),
						'icon'  => 'eicon-text-align-left',
					],
					'center' => [
						'title' => esc_html__( 'Center', 'elementor' ),
						'icon'  => 'eicon-text-align-center',
					],
					'right'  => [
						'title' => esc_html__( 'Right', 'elementor' ),
						'icon'  => 'eicon-text-align-right',
					],
				],
				'selectors' => [
					'{{WRAPPER}}' => 'text-align: {{VALUE}};',
				],
			]
		);

		$this->add_responsive_control(
			'rswpthemes_awt_width',
			[
				'label'      => esc_html__( 'Width', 'elementor' ),
				'type'       => Controls_Manager::SLIDER,
				'default'    => [ 'unit' => '%' ],
				'size_units' => [ 'px', '%', 'em', 'rem', 'vw', 'custom' ],
				'range'      => [
					'%'  => [ 'min' => 1, 'max' => 100 ],
					'px' => [ 'min' => 1, 'max' => 1000 ],
					'vw' => [ 'min' => 1, 'max' => 100 ],
				],
				'selectors'  => [
					'{{WRAPPER}} img' => 'width: {{SIZE}}{{UNIT}};',
				],
			]
		);

		$this->add_responsive_control(
			'rswpthemes_awt_space',
			[
				'label'      => esc_html__( 'Max Width', 'elementor' ),
				'type'       => Controls_Manager::SLIDER,
				'default'    => [ 'unit' => '%' ],
				'size_units' => [ 'px', '%', 'em', 'rem', 'vw', 'custom' ],
				'range'      => [
					'%'  => [ 'min' => 1, 'max' => 100 ],
					'px' => [ 'min' => 1, 'max' => 1000 ],
					'vw' => [ 'min' => 1, 'max' => 100 ],
				],
				'selectors'  => [
					'{{WRAPPER}} img' => 'max-width: {{SIZE}}{{UNIT}};',
				],
			]
		);

		$this->add_responsive_control(
			'rswpthemes_awt_height',
			[
				'label'      => esc_html__( 'Height', 'elementor' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => [ 'px', '%', 'em', 'rem', 'vh', 'custom' ],
				'range'      => [
					'px' => [ 'min' => 1, 'max' => 500 ],
					'vh' => [ 'min' => 1, 'max' => 100 ],
				],
				'selectors'  => [
					'{{WRAPPER}} img' => 'height: {{SIZE}}{{UNIT}};',
				],
			]
		);

		$this->add_responsive_control(
			'rswpthemes_awt_object_fit',
			[
				'label'     => esc_html__( 'Object Fit', 'elementor' ),
				'type'      => Controls_Manager::SELECT,
				'condition' => [
					'rswpthemes_awt_height[size]!' => '',
				],
				'options'   => [
					''           => esc_html__( 'Default', 'elementor' ),
					'fill'       => esc_html__( 'Fill', 'elementor' ),
					'cover'      => esc_html__( 'Cover', 'elementor' ),
					'contain'    => esc_html__( 'Contain', 'elementor' ),
					'scale-down' => esc_html__( 'Scale Down', 'elementor' ),
				],
				'default'   => '',
				'selectors' => [
					'{{WRAPPER}} img' => 'object-fit: {{VALUE}};',
				],
			]
		);

		$this->add_responsive_control(
			'rswpthemes_awt_object_position',
			[
				'label'     => esc_html__( 'Object Position', 'elementor' ),
				'type'      => Controls_Manager::SELECT,
				'options'   => [
					'center center' => esc_html__( 'Center Center', 'elementor' ),
					'center left'   => esc_html__( 'Center Left', 'elementor' ),
					'center right'  => esc_html__( 'Center Right', 'elementor' ),
					'top center'    => esc_html__( 'Top Center', 'elementor' ),
					'top left'      => esc_html__( 'Top Left', 'elementor' ),
					'top right'     => esc_html__( 'Top Right', 'elementor' ),
					'bottom center' => esc_html__( 'Bottom Center', 'elementor' ),
					'bottom left'   => esc_html__( 'Bottom Left', 'elementor' ),
					'bottom right'  => esc_html__( 'Bottom Right', 'elementor' ),
				],
				'default'   => 'center center',
				'selectors' => [
					'{{WRAPPER}} img' => 'object-position: {{VALUE}};',
				],
				'condition' => [
					'rswpthemes_awt_height[size]!' => '',
					'rswpthemes_awt_object_fit'    => [ 'cover', 'contain', 'scale-down' ],
				],
			]
		);

		$this->add_control(
			'rswpthemes_awt_separator_panel_style',
			[
				'type'  => Controls_Manager::DIVIDER,
				'style' => 'thick',
			]
		);

		$this->start_controls_tabs( 'rswpthemes_awt_image_effects' );

		$this->start_controls_tab(
			'rswpthemes_awt_normal',
			[
				'label' => esc_html__( 'Normal', 'elementor' ),
			]
		);

		$this->add_control(
			'rswpthemes_awt_opacity',
			[
				'label'     => esc_html__( 'Opacity', 'elementor' ),
				'type'      => Controls_Manager::SLIDER,
				'range'     => [
					'px' => [
						'max'  => 1,
						'min'  => 0.10,
						'step' => 0.01,
					],
				],
				'selectors' => [
					'{{WRAPPER}} img' => 'opacity: {{SIZE}};',
				],
			]
		);

		$this->add_group_control(
			Group_Control_Css_Filter::get_type(),
			[
				'name'     => 'rswpthemes_awt_css_filters',
				'selector' => '{{WRAPPER}} img',
			]
		);

		$this->end_controls_tab();

		$this->start_controls_tab(
			'rswpthemes_awt_hover',
			[
				'label' => esc_html__( 'Hover', 'elementor' ),
			]
		);

		$this->add_control(
			'rswpthemes_awt_opacity_hover',
			[
				'label'     => esc_html__( 'Opacity', 'elementor' ),
				'type'      => Controls_Manager::SLIDER,
				'range'     => [
					'px' => [
						'max'  => 1,
						'min'  => 0.10,
						'step' => 0.01,
					],
				],
				'selectors' => [
					'{{WRAPPER}}:hover img' => 'opacity: {{SIZE}};',
				],
			]
		);

		$this->add_group_control(
			Group_Control_Css_Filter::get_type(),
			[
				'name'     => 'rswpthemes_awt_css_filters_hover',
				'selector' => '{{WRAPPER}}:hover img',
			]
		);

		$this->add_control(
			'rswpthemes_awt_background_hover_transition',
			[
				'label'     => esc_html__( 'Transition Duration', 'elementor' ) . ' (s)',
				'type'      => Controls_Manager::SLIDER,
				'range'     => [
					'px' => [
						'min'  => 0,
						'max'  => 3,
						'step' => 0.1,
					],
				],
				'selectors' => [
					'{{WRAPPER}} img' => 'transition-duration: {{SIZE}}s',
				],
			]
		);

		$this->add_control(
			'rswpthemes_awt_hover_animation',
			[
				'label' => esc_html__( 'Hover Animation', 'elementor' ),
				'type'  => Controls_Manager::HOVER_ANIMATION,
			]
		);

		$this->end_controls_tab();
		$this->end_controls_tabs();

		$this->add_group_control(
			Group_Control_Border::get_type(),
			[
				'name'     => 'rswpthemes_awt_image_border',
				'selector' => '{{WRAPPER}} img',
				'separator'=> 'before',
			]
		);

		$this->add_responsive_control(
			'rswpthemes_awt_image_border_radius',
			[
				'label'     => esc_html__( 'Border Radius', 'elementor' ),
				'type'      => Controls_Manager::DIMENSIONS,
				'size_units'=> [ 'px', '%', 'em', 'rem', 'custom' ],
				'selectors' => [
					'{{WRAPPER}} img' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				],
			]
		);

		$this->add_group_control(
			Group_Control_Box_Shadow::get_type(),
			[
				'name'     => 'rswpthemes_awt_image_box_shadow',
				'exclude'  => [ 'box_shadow_position' ],
				'selector' => '{{WRAPPER}} img',
			]
		);

		$this->end_controls_section();

		// ------------------------
		// Caption Style Controls
		// ------------------------
		$this->start_controls_section(
			'rswpthemes_awt_section_style_caption',
			[
				'label'     => esc_html__( 'Caption', 'elementor' ),
				'tab'       => Controls_Manager::TAB_STYLE,
				'condition' => [
					'rswpthemes_awt_image[url]!'       => '',
					'rswpthemes_awt_caption_source!'    => 'none',
				],
			]
		);

		$this->add_responsive_control(
			'rswpthemes_awt_caption_align',
			[
				'label'     => esc_html__( 'Alignment', 'elementor' ),
				'type'      => Controls_Manager::CHOOSE,
				'options'   => [
					'left'    => [
						'title' => esc_html__( 'Left', 'elementor' ),
						'icon'  => 'eicon-text-align-left',
					],
					'center'  => [
						'title' => esc_html__( 'Center', 'elementor' ),
						'icon'  => 'eicon-text-align-center',
					],
					'right'   => [
						'title' => esc_html__( 'Right', 'elementor' ),
						'icon'  => 'eicon-text-align-right',
					],
					'justify' => [
						'title' => esc_html__( 'Justified', 'elementor' ),
						'icon'  => 'eicon-text-align-justify',
					],
				],
				'default'   => '',
				'selectors' => [
					'{{WRAPPER}} .widget-image-caption' => 'text-align: {{VALUE}};',
				],
			]
		);

		$this->add_control(
			'rswpthemes_awt_text_color',
			[
				'label'     => esc_html__( 'Text Color', 'elementor' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '',
				'selectors' => [
					'{{WRAPPER}} .widget-image-caption' => 'color: {{VALUE}};',
				],
				'global'    => [
					'default' => Global_Colors::COLOR_TEXT,
				],
			]
		);

		$this->add_control(
			'rswpthemes_awt_caption_background_color',
			[
				'label'     => esc_html__( 'Background Color', 'elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .widget-image-caption' => 'background-color: {{VALUE}};',
				],
			]
		);

		$this->add_group_control(
			\Elementor\Group_Control_Typography::get_type(),
			[
				'name'     => 'rswpthemes_awt_caption_typography',
				'selector' => '{{WRAPPER}} .widget-image-caption',
				'global'   => [
					'default' => Global_Typography::TYPOGRAPHY_TEXT,
				],
			]
		);

		$this->add_group_control(
			Group_Control_Text_Shadow::get_type(),
			[
				'name'     => 'rswpthemes_awt_caption_text_shadow',
				'selector' => '{{WRAPPER}} .widget-image-caption',
			]
		);

		$this->add_responsive_control(
			'rswpthemes_awt_caption_space',
			[
				'label'     => esc_html__( 'Spacing', 'elementor' ),
				'type'      => Controls_Manager::SLIDER,
				'size_units'=> [ 'px', 'em', 'rem', 'custom' ],
				'range'     => [
					'px' => [ 'max' => 100 ],
					'em' => [ 'min' => 0, 'max' => 10 ],
					'rem'=> [ 'min' => 0, 'max' => 10 ],
				],
				'selectors' => [
					'{{WRAPPER}} .widget-image-caption' => 'margin-block-start: {{SIZE}}{{UNIT}};',
				],
			]
		);

		$this->end_controls_section();
	}

	/**
	 * Check if the current widget has caption
	 */
	private function has_caption( $settings ) {
		return ( ! empty( $settings['rswpthemes_awt_caption_source'] ) && 'none' !== $settings['rswpthemes_awt_caption_source'] );
	}

	/**
	 * Get the caption for current widget.
	 */
	private function get_caption( $settings ) {
		$caption = '';
		if ( ! empty( $settings['rswpthemes_awt_caption_source'] ) ) {
			switch ( $settings['rswpthemes_awt_caption_source'] ) {
				case 'attachment':
					$caption = wp_get_attachment_caption( $settings['rswpthemes_awt_image']['id'] );
					break;
				case 'custom':
					$caption = ! Utils::is_empty( $settings['rswpthemes_awt_caption'] ) ? $settings['rswpthemes_awt_caption'] : '';
					break;
			}
		}
		return $caption;
	}

	/**
	 * Render image widget output on the frontend.
	 */
	protected function render() {
		$settings = $this->get_settings_for_display();
		// Make sure an image URL was chosen at all
		if ( empty( $settings['rswpthemes_awt_image']['url'] ) ) {
			return;
		}

		$has_caption = $this->has_caption( $settings );
		$link        = $this->get_link_url( $settings );

		// Build link attributes if "custom" link
		if ( $link ) {
			$this->add_link_attributes( 'link', $link );
			if ( \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
				$this->add_render_attribute( 'link', [ 'class' => 'elementor-clickable' ] );
			}
		}
		?>
		<?php if ( $has_caption ) : ?>
			<figure class="wp-caption">
		<?php endif; ?>

		<?php if ( $link ) : ?>
			<a <?php $this->print_render_attribute_string( 'link' ); ?>>
		<?php endif;
		$image_url = $settings['rswpthemes_awt_image']['url'] ?? '';
		$image_id = $settings['rswpthemes_awt_image']['id'] ?? '';

		// Get current site's host (e.g., "localhost" or "demo.rswpthemes.com")
		$current_host = parse_url(site_url(), PHP_URL_HOST);
		$image_host = parse_url($image_url, PHP_URL_HOST);

		// Check if the image is from the current site
		if (!empty($image_id) && $image_host === $current_host) {
		    // Use WP image resizing (fetch the correct sized image)
		    $final_url = Group_Control_Image_Size::get_attachment_image_src(
		        $image_id,
		        'rswpthemes_awt_image',
		        $settings
		    );

		    if ($final_url) {
		        echo '<img src="' . esc_url($final_url) . '" alt="" />';
		    }
		} else {
		    // External image (or no attachment ID), use the raw URL
		    if (!empty($image_url)) {
		        echo '<img src="' . esc_url($image_url) . '" alt="" />';
		    }
		}
		if ( $link ) : ?>
			</a>
		<?php endif; ?>

		<?php if ( $has_caption ) : ?>
				<figcaption class="widget-image-caption wp-caption-text">
					<?php echo wp_kses_post( $this->get_caption( $settings ) ); ?>
				</figcaption>
			</figure>
		<?php endif; ?>
		<?php
	}


	/**
	 * Render image widget output in the editor (Backbone JS template).
	 */
	protected function content_template() {
		?>
		<# if ( settings.rswpthemes_awt_image.url ) {
			var imageData = {
				id: settings.rswpthemes_awt_image.id,
				url: settings.rswpthemes_awt_image.url,
				size: settings.rswpthemes_awt_image_size,
				dimension: settings.rswpthemes_awt_image_custom_dimension,
				model: view.getEditModel()
			};

			var image_url = elementor.imagesManager.getImageUrl( imageData );
			if ( ! image_url ) {
				return;
			}

			var hasCaption = function() {
				if ( ! settings.rswpthemes_awt_caption_source || 'none' === settings.rswpthemes_awt_caption_source ) {
					return false;
				}
				return true;
			};

			var ensureAttachmentData = function( id ) {
				if ( 'undefined' === typeof wp.media.attachment( id ).get( 'caption' ) ) {
					wp.media.attachment( id ).fetch().then( function() {
						view.render();
					} );
				}
			};

			var getAttachmentCaption = function( id ) {
				if ( ! id ) {
					return '';
				}
				ensureAttachmentData( id );
				return wp.media.attachment( id ).get( 'caption' );
			};

			var getCaption = function() {
				if ( ! hasCaption() ) {
					return '';
				}
				if ( 'custom' === settings.rswpthemes_awt_caption_source ) {
					return settings.rswpthemes_awt_caption;
				}
				return getAttachmentCaption( settings.rswpthemes_awt_image.id );
			};

			// Build link if link_to is "custom"
			var link_url = false;
			if ( 'custom' === settings.rswpthemes_awt_link_to && settings.rswpthemes_awt_link.url ) {
				link_url = settings.rswpthemes_awt_link.url;
			}

			var imgClass = '';
			if ( '' !== settings.rswpthemes_awt_hover_animation ) {
				imgClass = 'elementor-animation-' + settings.rswpthemes_awt_hover_animation;
			}

			if ( hasCaption() ) { #>
				<figure class="wp-caption">
			<# }

			if ( link_url ) { #>
				<a class="elementor-clickable" href="{{ link_url }}">
			<# } #>
					<img src="{{ image_url }}" class="{{ imgClass }}" />
			<# if ( link_url ) { #>
				</a>
			<# }

			if ( hasCaption() ) { #>
				<figcaption class="widget-image-caption wp-caption-text">{{{ getCaption() }}}</figcaption>
				</figure>
			<# } #>
		<# } #>
		<?php
	}

	/**
	 * Get link URL if "custom" is selected, otherwise false.
	 */
	protected function get_link_url( $settings ) {
		if ( 'none' === $settings['rswpthemes_awt_link_to'] ) {
			return false;
		}

		// "custom" link
		if ( empty( $settings['rswpthemes_awt_link']['url'] ) ) {
			return false;
		}
		return $settings['rswpthemes_awt_link'];
	}
}

