<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; }
use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Image_Size;
use Elementor\Group_Control_Css_Filter;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Typography;
use Elementor\Utils;
use Sifency\Traits\Sifency_Addons_Image_Style_Controls;
use Sifency\Traits\Sifency_Addons_Animation_Controls;
use Sifency\Traits\Sifency_Addons_Animation_Manager;
use Sifency\Traits\Sifency_Addons_Master_Typography;
use Sifency\Traits\Sifency_Addons_Help_Controls;

class Sifency_Widget_Postmedia extends Widget_Base {
	use Sifency_Addons_Animation_Controls;
	use Sifency_Addons_Image_Style_Controls;
	use Sifency_Addons_Master_Typography;
	use Sifency_Addons_Help_Controls;

	public function __construct( $data = array(), $args = null ) {
		parent::__construct( $data, $args );
		$this->wg_config = array(
			'name'          => 'post-media',
			'title'         => 'Sifency Feature Image',
			'icon'          => 'eicon-featured-image',
			'category'      => array( 'sifency-post-components' ),
			'style_depends' => array( 'sifency-typo-style', 'sifency-frontend-style' ),
			'keywords'      => array( 'image', 'post', 'article', 'text', 'dynamic', 'sifency' ),
		);}

	protected function register_controls() {
		$this->start_controls_section(
			'image_section',
			array( 'label' => esc_html__( 'Image', 'sifency-addons' ) )
		);
		$this->add_control(
			'img_source',
			array(
				'label'   => 'Source',
				'type'    => Controls_Manager::SELECT,
				'options' => array(
					'post_thumbnail' => 'Featured Image',
					'custom'         => 'Custom Image',
				),
				'default' => 'post_thumbnail',
			)
		);
		$this->add_control(
			'image',
			array(
				'label'     => 'Custom Image',
				'type'      => Controls_Manager::MEDIA,
				'default'   => array( 'url' => Utils::get_placeholder_image_src() ),
				'condition' => array( 'img_source' => 'custom' ),
				'dynamic'   => array( 'active' => true ),
			)
		);
		$this->add_group_control(
			Group_Control_Image_Size::get_type(),
			array(
				'name'    => 'image',
				'default' => 'large',
			)
		);
		$this->add_responsive_control(
			'align',
			array(
				'label'     => 'Alignment',
				'type'      => Controls_Manager::CHOOSE,
				'options'   => array(
					'left'   => array(
						'title' => 'Left',
						'icon'  => 'eicon-text-align-left',
					),
					'center' => array(
						'title' => 'Center',
						'icon'  => 'eicon-text-align-center',
					),
					'right'  => array(
						'title' => 'Right',
						'icon'  => 'eicon-text-align-right',
					),
				),
				'selectors' => array( '{{WRAPPER}}' => 'text-align: {{VALUE}};' ),
			)
		);
		$this->add_control(
			'caption_source',
			array(
				'label'   => 'Caption',
				'type'    => Controls_Manager::SELECT,
				'options' => array(
					'none'       => 'None',
					'attachment' => 'Attachment Caption',
					'custom'     => 'Custom Caption',
				),
				'default' => 'none',
			)
		);
		$this->add_control(
			'caption',
			array(
				'label'     => 'Custom Caption',
				'type'      => Controls_Manager::TEXTAREA,
				'condition' => array( 'caption_source' => 'custom' ),
				'dynamic'   => array( 'active' => true ),
			)
		);
		$this->add_control(
			'link_to',
			array(
				'label'   => 'Link',
				'type'    => Controls_Manager::SELECT,
				'default' => 'none',
				'options' => array(
					'none'   => 'None',
					'file'   => 'Media File (Lightbox)',
					'post'   => 'Post URL',
					'custom' => 'Custom URL',
				),
			)
		);
		$this->add_control(
			'link',
			array(
				'label'      => 'Link',
				'type'       => Controls_Manager::URL,
				'dynamic'    => array( 'active' => true ),
				'condition'  => array( 'link_to' => 'custom' ),
				'show_label' => false,
			)
		);
		$this->end_controls_section();
		$this->add_sifency_addons_help_controls();
		$this->add_sifency_addons_image_style_controls(
			array(
				'selectors' => array(
					'image'      => '.sifency-dynamic-image img',
					'container'  => '.sifency-dynamic-image img',
					'dimensions' => '.sifency-dynamic-image img',
					'overlay'    => '.sifency-image-overlay',
				),
			)
		);
		$this->add_sifency_addons_master_typography_controls(
			array(
				'prefix'   => 'caption_style',
				'label'    => 'Caption Style',
				'selector' => '.sifency-caption-style',
			)
		);
		$this->add_Sifency_Addons_Animation_Controls();
		$this->update_control(
			'sifency_animation_target',
			array(
				'type'    => Controls_Manager::HIDDEN,
				'default' => 'wrapper',
			)
		);
	}

		/**
		 * Render the widget output on the frontend.
		 *
		 * @since 1.0.4
		 * @access protected
		 */
	protected function render() {
		$settings          = $this->get_settings_for_display();
		$animation_manager = new Sifency_Addons_Animation_Manager( $settings );
		$image_id          = null;
		$image_html        = '';

		if ( 'custom' === $settings['img_source'] ) {
			$image_id = $settings['image']['id'];
		} else {
			$image_id = get_post_thumbnail_id();
		}

		if ( ! empty( $image_id ) ) {
			$image_html = wp_get_attachment_image( $image_id, $settings['image_size'] );
		} elseif ( \Elementor\Plugin::$instance->editor->is_edit_mode() || 'custom' === $settings['img_source'] ) {
				$image_html = sprintf( '<img src="%s" alt="Placeholder Image" />', esc_url( \Elementor\Utils::get_placeholder_image_src() ) );
		} else {
			return;
		}

		$caption_text = '';
		if ( ! empty( $settings['caption_source'] ) && ! empty( $image_id ) ) {
			if ( 'attachment' === $settings['caption_source'] ) {
				$caption_text = wp_get_attachment_caption( $image_id );
			} elseif ( 'custom' === $settings['caption_source'] ) {
				$caption_text = $settings['caption'];
			}
		} elseif ( \Elementor\Plugin::$instance->editor->is_edit_mode() && ! empty( $settings['caption_source'] ) ) {
			if ( 'custom' === $settings['caption_source'] ) {
				$caption_text = $settings['caption'];
			} else {
				$caption_text = esc_html__( 'Image caption placeholder', 'sifency-addons' );
			}
		}

		$link_url = '';
		if ( 'none' !== $settings['link_to'] ) {
			if ( 'custom' === $settings['link_to'] && ! empty( $settings['link']['url'] ) ) {
				$link_url = $settings['link']['url'];
				$this->add_link_attributes( 'link', $settings['link'] );
			} elseif ( 'file' === $settings['link_to'] ) {
				$image_src = wp_get_attachment_image_src( $image_id, 'full' );
				if ( $image_src ) {
					$link_url = $image_src[0];
					$this->add_render_attribute(
						'link',
						array(
							'href'                         => $link_url,
							'data-elementor-open-lightbox' => 'yes',
						)
					);
				}
			} elseif ( 'post' === $settings['link_to'] ) {
				$link_url = get_permalink();
				$this->add_render_attribute( 'link', 'href', $link_url );
			}
		}

		$wrapper_attrs_string = $animation_manager->get_wrapper_attributes( array( 'sifency-dynamic-image-wrapper' ) );
		$this->add_render_attribute( 'image-wrapper', 'class', 'sifency-dynamic-image sifency-image' );
		if ( ! empty( $settings['hover_animation'] ) ) {
			$this->add_render_attribute( 'image-wrapper', 'class', 'elementor-animation-' . $settings['hover_animation'] );
		}
		?>
		<div <?php echo wp_kses_post( $wrapper_attrs_string ); ?>>
			<figure class="sifency-dynamic-image-figure sifency-image-container">
				<?php if ( $link_url ) : ?>
					<a <?php echo wp_kses_post( $this->get_render_attribute_string( 'link' ) ); ?>>
				<?php endif; ?>

				<div <?php echo wp_kses_post( $this->get_render_attribute_string( 'image-wrapper' ) ); ?>>
					<?php echo wp_kses_post( $image_html ); ?>
					<div class="sifency-image-overlay"></div>
				</div>

				<?php if ( $link_url ) : ?>
					</a>
				<?php endif; ?>

				<?php if ( ! empty( $caption_text ) ) : ?>
					<figcaption class="sifency-image-caption sifency-caption-style">
						<?php echo wp_kses_post( $caption_text ); ?>
					</figcaption>
				<?php endif; ?>
			</figure>
		</div>
		<?php
	}

	/**
	 * Render the widget output in the editor.
	 *
	 * Written as a Backbone JavaScript template and used to generate the live preview.
	 *
	 * @since 1.0.4
	 * @access protected
	 */
	protected function _content_template() {
		?>
		<#
		var imageUrl = '<?php echo esc_url( \Elementor\Utils::get_placeholder_image_src() ); ?>';
		if ( 'custom' === settings.img_source && settings.image.url ) {
			imageUrl = settings.image.url;
		}
		var imageHtml = '<img src="' + imageUrl + '" alt="Preview Image" />';

		var captionText = '';
		if ( settings.caption_source ) {
			if ( 'attachment' === settings.caption_source ) {
				// We can't get the real attachment caption, so we show a placeholder.
				captionText = 'Image caption placeholder';
			} else if ( 'custom' === settings.caption_source ) {
				captionText = settings.caption;
			}
		}
		
		var linkUrl = '';
		if ( 'none' !== settings.link_to ) {
			if ( 'custom' === settings.link_to && settings.link.url ) {
				linkUrl = settings.link.url;
				view.addRenderAttribute( 'link', 'href', settings.link.url );
				if ( settings.link.is_external ) {
					view.addRenderAttribute( 'link', 'target', '_blank' );
				}
				if ( settings.link.nofollow ) {
					view.addRenderAttribute( 'link', 'rel', 'nofollow' );
				}
			} else if ( 'file' === settings.link_to ) {
				linkUrl = imageUrl; // Link to the image itself for lightbox
				view.addRenderAttribute( 'link', {
					'href': linkUrl,
					'data-elementor-open-lightbox': 'yes'
				});
			} else if ( 'post' === settings.link_to ) {
				linkUrl = '#'; // Placeholder link for post
				view.addRenderAttribute( 'link', 'href', '#' );
			}
		}

		view.addRenderAttribute( 'image-wrapper', 'class', 'sifency-dynamic-image sifency-image' );
		if ( settings.hover_animation ) {
			view.addRenderAttribute( 'image-wrapper', 'class', 'elementor-animation-' + settings.hover_animation );
		}
		#>
		<div class="sifency-dynamic-image-wrapper">
			<figure class="sifency-dynamic-image-figure sifency-image-container">
				<# if ( linkUrl ) { #>
					<a {{{ view.getRenderAttributeString( 'link' ) }}}>
				<# } #>

				<div {{{ view.getRenderAttributeString( 'image-wrapper' ) }}}>
					{{{ imageHtml }}}
					<div class="sifency-image-overlay"></div>
				</div>

				<# if ( linkUrl ) { #>
					</a>
				<# } #>

				<# if ( captionText ) { #>
					<figcaption class="sifency-image-caption sifency-caption-style">
						{{{ captionText }}}
					</figcaption>
				<# } #>
			</figure>
		</div>
		<?php
	}
}
