<?php
/**
 * Widget Name: Product Image
 * Description: Displays a WooCommerce product's featured image for the current
 *              product or a chosen product. Supports linking to the product, a
 *              custom URL or a built-in lightbox, an optional sale badge, hover
 *              effects and multiple attractive styles.
 *
 * @package    captain-widgets-kit
 * @subpackage captain-widgets-kit/includes
 * @since      1.3.0
 */

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

use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Image_Size;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Typography;

/**
 * Class Captwiki_Woo_Product_Image
 *
 * @since 1.3.0
 */
class Captwiki_Woo_Product_Image extends Widget_Base {

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

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

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

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

	/**
	 * Get widget keywords.
	 *
	 * @since 1.3.0
	 * @return array
	 */
	public function get_keywords(): array {
		return array( 'woocommerce', 'woo', 'product', 'image', 'featured', 'thumbnail', 'photo', 'captain-widgets-kit' );
	}

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

	/**
	 * Available visual styles.
	 *
	 * @since 1.3.0
	 * @return array
	 */
	private function captwiki_style_options(): array {
		return array(
			'style-1' => esc_html__( 'Style 1 – Classic', 'captain-widgets-kit' ),
			'style-2' => esc_html__( 'Style 2 – Card', 'captain-widgets-kit' ),
			'style-3' => esc_html__( 'Style 3 – Rounded', 'captain-widgets-kit' ),
		);
	}

	/**
	 * Build a list of published products for the source selector.
	 *
	 * @since 1.3.0
	 * @return array
	 */
	private function captwiki_get_products_options(): array {

		$options = array();

		if ( ! function_exists( 'wc_get_products' ) ) {
			return $options;
		}

		$products = wc_get_products(
			array(
				'status'  => 'publish',
				'limit'   => 50,
				'orderby' => 'title',
				'order'   => 'ASC',
				'return'  => 'objects',
			)
		);

		foreach ( $products as $product ) {
			$options[ $product->get_id() ] = $product->get_name();
		}

		return $options;
	}

	/**
	 * Register controls.
	 *
	 * @since 1.3.0
	 */
	protected function register_controls(): void {
		$this->register_content_controls();
		$this->register_image_style_controls();
		$this->register_badge_style_controls();
	}

	/**
	 * Content tab controls.
	 *
	 * @since 1.3.0
	 */
	private function register_content_controls(): void {

		$this->start_controls_section(
			'section_content',
			array(
				'label' => esc_html__( 'Product 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(
			'product_source',
			array(
				'label'   => esc_html__( 'Product', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'current',
				'options' => array(
					'current'  => esc_html__( 'Current Product', 'captain-widgets-kit' ),
					'specific' => esc_html__( 'Select a Product', 'captain-widgets-kit' ),
				),
			)
		);

		$this->add_control(
			'product_id',
			array(
				'label'       => esc_html__( 'Choose Product', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::SELECT2,
				'label_block' => true,
				'options'     => $this->captwiki_get_products_options(),
				'condition'   => array( 'product_source' => 'specific' ),
			)
		);

		$this->add_group_control(
			Group_Control_Image_Size::get_type(),
			array(
				'name'    => 'image',
				'default' => 'woocommerce_single',
			)
		);

		$this->add_control(
			'link_to',
			array(
				'label'   => esc_html__( 'Link', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'product',
				'options' => array(
					''         => esc_html__( 'None', 'captain-widgets-kit' ),
					'product'  => esc_html__( 'Product Page', 'captain-widgets-kit' ),
					'lightbox' => esc_html__( 'Lightbox (Zoom)', 'captain-widgets-kit' ),
					'custom'   => esc_html__( 'Custom URL', 'captain-widgets-kit' ),
				),
			)
		);

		$this->add_control(
			'custom_link',
			array(
				'label'         => esc_html__( 'Custom URL', 'captain-widgets-kit' ),
				'type'          => Controls_Manager::URL,
				'placeholder'   => 'https://your-link.com',
				'show_external' => true,
				'condition'     => array( 'link_to' => 'custom' ),
				'dynamic'       => array( 'active' => true ),
			)
		);

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

		$this->add_control(
			'show_sale_badge',
			array(
				'label'        => esc_html__( 'Show Sale Badge', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Yes', 'captain-widgets-kit' ),
				'label_off'    => esc_html__( 'No', 'captain-widgets-kit' ),
				'return_value' => 'yes',
				'default'      => 'yes',
			)
		);

		$this->add_control(
			'sale_badge_text',
			array(
				'label'       => esc_html__( 'Sale Badge Text', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => esc_html__( 'Sale!', 'captain-widgets-kit' ),
				'condition'   => array( 'show_sale_badge' => 'yes' ),
				'label_block' => true,
			)
		);

		$this->add_responsive_control(
			'image_align',
			array(
				'label'     => esc_html__( 'Alignment', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::CHOOSE,
				'options'   => array(
					'flex-start' => 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',
					),
					'flex-end'   => array(
						'title' => esc_html__( 'Right', 'captain-widgets-kit' ),
						'icon'  => 'eicon-text-align-right',
					),
				),
				'default'   => 'center',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-pi' => 'justify-content: {{VALUE}};',
				),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Image style controls.
	 *
	 * @since 1.3.0
	 */
	private function register_image_style_controls(): void {

		$frame_selector = '{{WRAPPER}} .captwiki-pi__frame';
		$img_selector   = '{{WRAPPER}} .captwiki-pi__img';

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

		$this->add_responsive_control(
			'image_width',
			array(
				'label'      => esc_html__( 'Width', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px', '%', 'vw' ),
				'range'      => array(
					'px' => array( 'min' => 50, 'max' => 1000, 'step' => 1 ),
					'%'  => array( 'min' => 10, 'max' => 100, 'step' => 1 ),
				),
				'default'    => array( 'size' => 100, 'unit' => '%' ),
				'selectors'  => array(
					$frame_selector => 'width: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->add_responsive_control(
			'image_height',
			array(
				'label'      => esc_html__( 'Height', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px', 'vh' ),
				'range'      => array( 'px' => array( 'min' => 50, 'max' => 1000, 'step' => 1 ) ),
				'selectors'  => array(
					$img_selector => 'height: {{SIZE}}{{UNIT}}; object-fit: cover;',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Border::get_type(),
			array(
				'name'     => 'image_border',
				'selector' => $frame_selector,
			)
		);

		$this->add_responsive_control(
			'image_radius',
			array(
				'label'      => esc_html__( 'Border Radius', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', '%' ),
				'selectors'  => array(
					$frame_selector => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}}; overflow: hidden;',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Box_Shadow::get_type(),
			array(
				'name'     => 'image_box_shadow',
				'selector' => $frame_selector,
			)
		);

		$this->add_responsive_control(
			'image_padding',
			array(
				'label'      => esc_html__( 'Padding', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', 'em' ),
				'selectors'  => array(
					$frame_selector => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Sale badge style controls.
	 *
	 * @since 1.3.0
	 */
	private function register_badge_style_controls(): void {

		$badge_selector = '{{WRAPPER}} .captwiki-pi__sale';

		$this->start_controls_section(
			'section_style_badge',
			array(
				'label'     => esc_html__( 'Sale Badge', 'captain-widgets-kit' ),
				'tab'       => Controls_Manager::TAB_STYLE,
				'condition' => array( 'show_sale_badge' => 'yes' ),
			)
		);

		$this->add_control(
			'badge_color',
			array(
				'label'     => esc_html__( 'Text Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array(
					$badge_selector => 'color: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'badge_bg',
			array(
				'label'     => esc_html__( 'Background Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array(
					$badge_selector => 'background-color: {{VALUE}};',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'     => 'badge_typography',
				'selector' => $badge_selector,
			)
		);

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

		$this->add_responsive_control(
			'badge_padding',
			array(
				'label'      => esc_html__( 'Padding', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', 'em' ),
				'selectors'  => array(
					$badge_selector => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->add_responsive_control(
			'badge_offset_v',
			array(
				'label'      => esc_html__( 'Vertical Offset', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px' ),
				'range'      => array( 'px' => array( 'min' => 0, 'max' => 80, 'step' => 1 ) ),
				'selectors'  => array(
					$badge_selector => 'top: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->add_responsive_control(
			'badge_offset_h',
			array(
				'label'      => esc_html__( 'Horizontal Offset', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px' ),
				'range'      => array( 'px' => array( 'min' => 0, 'max' => 80, 'step' => 1 ) ),
				'selectors'  => array(
					$badge_selector => 'left: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Resolve the product to render the image for.
	 *
	 * @since 1.3.0
	 * @param array $settings Widget settings.
	 * @return \WC_Product|false
	 */
	private function captwiki_resolve_product( array $settings ) {

		$source = ! empty( $settings['product_source'] ) ? $settings['product_source'] : 'current';

		if ( 'specific' === $source && ! empty( $settings['product_id'] ) ) {
			return wc_get_product( absint( $settings['product_id'] ) );
		}

		$product = wc_get_product( get_the_ID() );

		if ( $product ) {
			return $product;
		}

		// Editor / preview fallback — grab the latest published product.
		if ( \Elementor\Plugin::$instance->editor->is_edit_mode() || \Elementor\Plugin::$instance->preview->is_preview_mode() ) {
			$latest = wc_get_products(
				array(
					'status' => 'publish',
					'limit'  => 1,
				)
			);

			if ( ! empty( $latest ) ) {
				return $latest[0];
			}
		}

		return false;
	}

	/**
	 * Output an editor-only notice.
	 *
	 * @since 1.3.0
	 * @param string $message Notice text.
	 */
	private function captwiki_render_editor_notice( string $message ): void {

		if ( ! \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
			return;
		}

		echo '<div class="captwiki-pi captwiki-pi--notice"><p>' . esc_html( $message ) . '</p></div>';
	}

	/**
	 * Render widget output on the frontend.
	 *
	 * @since 1.3.0
	 */
	protected function render(): void {

		if ( ! class_exists( 'WooCommerce' ) || ! function_exists( 'wc_get_product' ) ) {
			$this->captwiki_render_editor_notice( esc_html__( 'WooCommerce is required for the Product Image widget.', 'captain-widgets-kit' ) );
			return;
		}

		$settings = $this->get_settings_for_display();
		$product  = $this->captwiki_resolve_product( $settings );

		if ( ! $product instanceof \WC_Product ) {
			$this->captwiki_render_editor_notice( esc_html__( 'No product found. Place this widget on a product template or select a product.', 'captain-widgets-kit' ) );
			return;
		}

		$allowed_styles = array_keys( $this->captwiki_style_options() );
		$style          = ! empty( $settings['widget_style'] ) && in_array( $settings['widget_style'], $allowed_styles, true ) ? $settings['widget_style'] : 'style-1';

		wp_enqueue_style(
			'captwiki-woo-product-image-' . $style,
			CAPTWIKI_URL . 'assets/css/widgets/woo-product-image/captwiki-woo-product-image-' . $style . '.css',
			array( 'captwiki-woo-product-image' ),
			CAPTWIKI_VERSION
		);

		$link_to     = isset( $settings['link_to'] ) ? $settings['link_to'] : 'product';
		$hover       = ! empty( $settings['hover_effect'] ) ? sanitize_html_class( $settings['hover_effect'] ) : 'none';
		$show_sale   = ! empty( $settings['show_sale_badge'] ) && 'yes' === $settings['show_sale_badge'] && $product->is_on_sale();
		$sale_text   = ! empty( $settings['sale_badge_text'] ) ? $settings['sale_badge_text'] : esc_html__( 'Sale!', 'captain-widgets-kit' );

		$image_id = (int) $product->get_image_id();

		// Build the <img> markup at the chosen size (placeholder if none).
		if ( $image_id ) {
			$image_html = Group_Control_Image_Size::get_attachment_image_html(
				array_merge( $settings, array( 'image' => array( 'id' => $image_id ) ) ),
				'image'
			);
			$full_src = wp_get_attachment_image_url( $image_id, 'full' );
		} else {
			$image_html = '<img src="' . esc_url( wc_placeholder_img_src( 'woocommerce_single' ) ) . '" alt="' . esc_attr( $product->get_name() ) . '" />';
			$full_src   = wc_placeholder_img_src( 'full' );
		}

		// Force our class onto the rendered <img> for styling hooks.
		$image_html = str_replace( '<img ', '<img class="captwiki-pi__img" ', $image_html );

		$lightbox = ( 'lightbox' === $link_to );

		if ( $lightbox ) {
			wp_enqueue_script( 'captwiki-woo-product-image' );
		}

		// Resolve link target.
		$href        = '';
		$target_attr = '';
		$rel_attr    = '';

		if ( 'product' === $link_to ) {
			$href = get_permalink( $product->get_id() );
		} elseif ( 'custom' === $link_to && ! empty( $settings['custom_link']['url'] ) ) {
			$href = $settings['custom_link']['url'];
			if ( ! empty( $settings['custom_link']['is_external'] ) ) {
				$target_attr = ' target="_blank"';
			}
			if ( ! empty( $settings['custom_link']['nofollow'] ) ) {
				$rel_attr = ' rel="nofollow"';
			}
		}

		$wrapper_classes = array(
			'captwiki-pi',
			'captwiki-' . $style,
			'captwiki-pi--hover-' . $hover,
			'captwiki-widget-' . $this->get_id(),
		);

		echo '<div class="' . esc_attr( implode( ' ', $wrapper_classes ) ) . '">';
		echo '<div class="captwiki-pi__frame">';

		if ( $show_sale ) {
			echo '<span class="captwiki-pi__sale">' . esc_html( $sale_text ) . '</span>';
		}

		if ( $lightbox ) {
			echo '<button type="button" class="captwiki-pi__link captwiki-pi__lightbox" data-full="' . esc_url( $full_src ) . '" aria-label="' . esc_attr__( 'Zoom image', 'captain-widgets-kit' ) . '">';
			echo $image_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			echo '</button>';
		} elseif ( $href ) {
			echo '<a class="captwiki-pi__link" href="' . esc_url( $href ) . '"' . $target_attr . $rel_attr . '>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			echo $image_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			echo '</a>';
		} else {
			echo $image_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		}

		echo '</div>';
		echo '</div>';
	}
}
