<?php
/**
 * Widget Name: Post Image
 * Description: Shows the current post's featured image — built for single
 *              post templates ( theme builder ). Supports image size, a
 *              fallback image, linking to the post or the full media file,
 *              an optional caption and hover effects. Ships with selectable
 *              visual styles — clean, soft card, accent frame, polaroid and
 *              editorial border. Only the selected style CSS file is loaded
 *              on the frontend.
 *
 * @package    captain-widgets-kit
 * @subpackage captain-widgets-kit/includes
 * @since      1.7.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Utils;

/**
 * Class Captwiki_Post_Image
 *
 * @since 1.7.0
 */
class Captwiki_Post_Image extends Widget_Base {

	/**
	 * Get widget name.
	 *
	 * @since 1.7.0
	 * @return string
	 */
	public function get_name(): string {
		return 'captwiki-post-image';
	}

	/**
	 * Get widget title.
	 *
	 * @since 1.7.0
	 * @return string
	 */
	public function get_title(): string {
		return esc_html__( 'Post Image', 'captain-widgets-kit' );
	}

	/**
	 * Get widget icon.
	 *
	 * @since 1.7.0
	 * @return string
	 */
	public function get_icon(): string {
		return 'eicon-featured-image captwiki-el-logo';
	}

	/**
	 * Get widget categories.
	 *
	 * @since 1.7.0
	 * @return array
	 */
	public function get_categories(): array {
		return array( 'captwiki-essential' );
	}

	/**
	 * Get widget keywords.
	 *
	 * @since 1.7.0
	 * @return array
	 */
	public function get_keywords(): array {
		return array( 'post', 'image', 'featured', 'thumbnail', 'single', 'captain-widgets-kit' );
	}

	/**
	 * Common stylesheet dependency.
	 *
	 * @since 1.7.0
	 * @return array
	 */
	public function get_style_depends(): array {
		return array( 'captwiki_post_image' );
	}

	/**
	 * Disable Elementor's default inner wrapper.
	 *
	 * @since 1.7.0
	 * @return bool
	 */
	public function has_widget_inner_wrapper(): bool {
		return ! \Elementor\Plugin::$instance->experiments->is_feature_active( 'e_optimized_markup' );
	}

	/**
	 * Selectable visual styles.
	 *
	 * @since 1.7.0
	 * @return array
	 */
	private function captwiki_style_options(): array {
		return array(
			'style-1' => esc_html__( 'Style 1 – Clean', 'captain-widgets-kit' ),
			'style-2' => esc_html__( 'Style 2 – Soft Card', 'captain-widgets-kit' ),
			'style-3' => esc_html__( 'Style 3 – Accent Frame', 'captain-widgets-kit' ),
			'style-4' => esc_html__( 'Style 4 – Polaroid', 'captain-widgets-kit' ),
			'style-5' => esc_html__( 'Style 5 – Editorial Border', 'captain-widgets-kit' ),
		);
	}

	/**
	 * Register widget controls.
	 *
	 * @since 1.7.0
	 * @return void
	 */
	protected function register_controls(): void {
		$this->register_content_controls();

		$this->register_layout_style_controls();
		$this->register_caption_style_controls();
	}

	/**
	 * Content tab — image settings.
	 *
	 * @since 1.7.0
	 * @return void
	 */
	private function register_content_controls(): void {

		$this->start_controls_section(
			'section_content',
			array(
				'label' => esc_html__( 'Post Image', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_CONTENT,
			)
		);

		$this->add_control(
			'widget_style',
			array(
				'label'   => esc_html__( 'Style', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'style-1',
				'options' => $this->captwiki_style_options(),
			)
		);

		$this->add_control(
			'image_size',
			array(
				'label'   => esc_html__( 'Image Size', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'large',
				'options' => array(
					'thumbnail'    => esc_html__( 'Thumbnail', 'captain-widgets-kit' ),
					'medium'       => esc_html__( 'Medium', 'captain-widgets-kit' ),
					'medium_large' => esc_html__( 'Medium Large', 'captain-widgets-kit' ),
					'large'        => esc_html__( 'Large', 'captain-widgets-kit' ),
					'full'         => esc_html__( 'Full', 'captain-widgets-kit' ),
				),
			)
		);

		$this->add_control(
			'link_to',
			array(
				'label'   => esc_html__( 'Link', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'none',
				'options' => array(
					'none'  => esc_html__( 'None', 'captain-widgets-kit' ),
					'post'  => esc_html__( 'Post', 'captain-widgets-kit' ),
					'media' => esc_html__( 'Media File', 'captain-widgets-kit' ),
				),
			)
		);

		$this->add_control(
			'show_caption',
			array(
				'label'        => esc_html__( 'Show Caption', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'default'      => '',
				'description'  => esc_html__( 'Uses the attachment caption when one exists.', 'captain-widgets-kit' ),
			)
		);

		$this->add_control(
			'fallback_image',
			array(
				'label'       => esc_html__( 'Fallback Image', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::MEDIA,
				'default'     => array( 'url' => '' ),
				'dynamic'     => array( 'active' => true ),
				'description' => esc_html__( 'Shown when the post has no featured image.', 'captain-widgets-kit' ),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Style tab — layout ( width, alignment, effects ).
	 *
	 * @since 1.7.0
	 * @return void
	 */
	private function register_layout_style_controls(): void {

		$this->start_controls_section(
			'section_layout_style',
			array(
				'label' => esc_html__( 'Layout', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_responsive_control(
			'box_width',
			array(
				'label'      => esc_html__( 'Width', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px', '%' ),
				'range'      => array(
					'px' => array(
						'min' => 100,
						'max' => 1400,
					),
					'%'  => array(
						'min' => 10,
						'max' => 100,
					),
				),
				'selectors'  => array(
					'{{WRAPPER}} .captwiki-post-image' => 'max-width: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->add_responsive_control(
			'box_align',
			array(
				'label'                => esc_html__( 'Alignment', 'captain-widgets-kit' ),
				'type'                 => Controls_Manager::CHOOSE,
				'default'              => 'center',
				'options'              => array(
					'left'   => array(
						'title' => esc_html__( 'Left', 'captain-widgets-kit' ),
						'icon'  => 'eicon-text-align-left',
					),
					'center' => array(
						'title' => esc_html__( 'Center', 'captain-widgets-kit' ),
						'icon'  => 'eicon-text-align-center',
					),
					'right'  => array(
						'title' => esc_html__( 'Right', 'captain-widgets-kit' ),
						'icon'  => 'eicon-text-align-right',
					),
				),
				'selectors_dictionary' => array(
					'left'   => 'margin-left: 0; margin-right: auto;',
					'center' => 'margin-left: auto; margin-right: auto;',
					'right'  => 'margin-left: auto; margin-right: 0;',
				),
				'selectors'            => array(
					'{{WRAPPER}} .captwiki-post-image' => '{{VALUE}}',
				),
			)
		);

		$this->add_control(
			'aspect_ratio',
			array(
				'label'                => esc_html__( 'Aspect Ratio', 'captain-widgets-kit' ),
				'type'                 => Controls_Manager::SELECT,
				'default'              => 'auto',
				'options'              => array(
					'auto' => esc_html__( 'Original Image', 'captain-widgets-kit' ),
					'1-1'  => '1:1',
					'4-3'  => '4:3',
					'3-2'  => '3:2',
					'16-9' => '16:9',
				),
				'selectors_dictionary' => array(
					'auto' => '--captwiki-pi-ratio: auto;',
					'1-1'  => '--captwiki-pi-ratio: 1 / 1;',
					'4-3'  => '--captwiki-pi-ratio: 4 / 3;',
					'3-2'  => '--captwiki-pi-ratio: 3 / 2;',
					'16-9' => '--captwiki-pi-ratio: 16 / 9;',
				),
				'selectors'            => array(
					'{{WRAPPER}} .captwiki-post-image' => '{{VALUE}}',
				),
			)
		);

		$this->add_control(
			'accent_color',
			array(
				'label'       => esc_html__( 'Accent Color', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::COLOR,
				'default'     => '',
				'selectors'   => array(
					'{{WRAPPER}} .captwiki-post-image' => '--captwiki-pi-accent: {{VALUE}};',
				),
				'description' => esc_html__( 'Used by the accent frame and editorial border styles.', 'captain-widgets-kit' ),
			)
		);

		$this->add_control(
			'hover_effect',
			array(
				'label'   => esc_html__( 'Hover Effect', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'none',
				'options' => array(
					'none'      => esc_html__( 'None', 'captain-widgets-kit' ),
					'zoom'      => esc_html__( 'Zoom', 'captain-widgets-kit' ),
					'lift'      => esc_html__( 'Lift', 'captain-widgets-kit' ),
					'grayscale' => esc_html__( 'Grayscale to Color', 'captain-widgets-kit' ),
				),
			)
		);

		$this->add_responsive_control(
			'box_border_radius',
			array(
				'label'      => esc_html__( 'Border Radius', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', '%' ),
				'selectors'  => array(
					'{{WRAPPER}} .captwiki-post-image__media' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Box_Shadow::get_type(),
			array(
				'name'     => 'box_shadow',
				'label'    => esc_html__( 'Box Shadow', 'captain-widgets-kit' ),
				'selector' => '{{WRAPPER}} .captwiki-post-image__media',
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Style tab — caption.
	 *
	 * @since 1.7.0
	 * @return void
	 */
	private function register_caption_style_controls(): void {

		$this->start_controls_section(
			'section_caption_style',
			array(
				'label'     => esc_html__( 'Caption', 'captain-widgets-kit' ),
				'tab'       => Controls_Manager::TAB_STYLE,
				'condition' => array( 'show_caption' => 'yes' ),
			)
		);

		$this->add_control(
			'caption_color',
			array(
				'label'     => esc_html__( 'Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-post-image__caption' => 'color: {{VALUE}};',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'     => 'caption_typography',
				'selector' => '{{WRAPPER}} .captwiki-post-image__caption',
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Render widget output on the frontend.
	 *
	 * @since 1.7.0
	 * @return void
	 */
	protected function render(): void {
		$settings = $this->get_settings_for_display();

		$allowed_styles = array_keys( $this->captwiki_style_options() );
		$style          = in_array( $settings['widget_style'], $allowed_styles, true ) ? $settings['widget_style'] : 'style-1';
		$allowed_sizes  = array( 'thumbnail', 'medium', 'medium_large', 'large', 'full' );
		$size           = in_array( $settings['image_size'], $allowed_sizes, true ) ? $settings['image_size'] : 'large';
		$link_to        = in_array( $settings['link_to'], array( 'none', 'post', 'media' ), true ) ? $settings['link_to'] : 'none';
		$hover          = in_array( $settings['hover_effect'], array( 'none', 'zoom', 'lift', 'grayscale' ), true ) ? $settings['hover_effect'] : 'none';

		$post_id  = get_the_ID();
		$thumb_id = $post_id ? get_post_thumbnail_id( $post_id ) : 0;
		$caption  = '';
		$img_html = '';

		if ( $thumb_id ) {
			$img_html = wp_get_attachment_image( $thumb_id, $size, false, array( 'class' => 'captwiki-post-image__img' ) );
			$caption  = (string) wp_get_attachment_caption( $thumb_id );
		} elseif ( ! empty( $settings['fallback_image']['url'] ) ) {
			$img_html = '<img class="captwiki-post-image__img" src="' . esc_url( $settings['fallback_image']['url'] ) . '" alt="" loading="lazy" />';
		} elseif ( \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
			// Editor preview without a featured image — show the placeholder
			// so the widget stays visible and styleable.
			$img_html = '<img class="captwiki-post-image__img" src="' . esc_url( Utils::get_placeholder_image_src() ) . '" alt="" />';
		}

		if ( '' === $img_html ) {
			return;
		}

		// Load only the active style stylesheet, depending on the common one.
		wp_enqueue_style(
			'captwiki-post-image-' . $style,
			CAPTWIKI_URL . 'assets/css/widgets/post-image/captwiki-post-image-' . $style . '.css',
			array( 'captwiki_post_image' ),
			CAPTWIKI_VERSION
		);

		$link_url = '';

		if ( 'post' === $link_to && $post_id ) {
			$link_url = (string) get_permalink( $post_id );
		} elseif ( 'media' === $link_to && $thumb_id ) {
			$link_url = (string) wp_get_attachment_url( $thumb_id );
		}

		$classes = 'captwiki-post-image captwiki-' . $style;

		if ( 'none' !== $hover ) {
			$classes .= ' captwiki-post-image--hover-' . $hover;
		}

		echo '<figure class="' . esc_attr( $classes ) . '">';
		echo '<div class="captwiki-post-image__media">';

		if ( '' !== $link_url ) {
			echo '<a class="captwiki-post-image__link" href="' . esc_url( $link_url ) . '">';
			echo $img_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- core-generated image markup.
			echo '</a>';
		} else {
			echo $img_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- core-generated image markup.
		}

		echo '</div>';

		if ( 'yes' === $settings['show_caption'] && '' !== $caption ) {
			echo '<figcaption class="captwiki-post-image__caption">' . esc_html( $caption ) . '</figcaption>';
		}

		echo '</figure>';
	}
}
