<?php
/**
 * Widget Name: Wishlist Button
 * Description: A self-contained add-to-wishlist button. Stores product IDs in the
 *              browser (localStorage) so it works without a third-party wishlist
 *              plugin. Supports current/selected product, custom icon + labels and
 *              multiple visual styles.
 *
 * @package    captain-widgets-kit
 * @subpackage captain-widgets-kit/includes
 * @since      1.2.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\Group_Control_Border;
use Elementor\Group_Control_Background;
use Elementor\Icons_Manager;

/**
 * Class Captwiki_Woo_Wishlist
 *
 * @since 1.2.0
 */
class Captwiki_Woo_Wishlist extends Widget_Base {

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

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

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

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

	/**
	 * Get widget keywords.
	 *
	 * @since 1.2.0
	 * @return array
	 */
	public function get_keywords(): array {
		return array( 'woocommerce', 'woo', 'wishlist', 'favourite', 'save', 'heart', 'captain-widgets-kit' );
	}

	/**
	 * Disable Elementor's default inner wrapper.
	 *
	 * @since 1.2.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.2.0
	 * @return array
	 */
	private function captwiki_style_options(): array {
		return array(
			'style-1' => esc_html__( 'Style 1 – Icon Solid', 'captain-widgets-kit' ),
			'style-2' => esc_html__( 'Style 2 – Outline Pill', 'captain-widgets-kit' ),
			'style-3' => esc_html__( 'Style 3 – Text Link', 'captain-widgets-kit' ),
		);
	}

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

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

		$this->start_controls_section(
			'section_content',
			array(
				'label' => esc_html__( 'Wishlist', '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_control(
			'show_icon',
			array(
				'label'        => esc_html__( 'Show Icon', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Show', 'captain-widgets-kit' ),
				'label_off'    => esc_html__( 'Hide', 'captain-widgets-kit' ),
				'return_value' => 'yes',
				'default'      => 'yes',
			)
		);

		$this->add_control(
			'wishlist_icon',
			array(
				'label'            => esc_html__( 'Icon', 'captain-widgets-kit' ),
				'type'             => Controls_Manager::ICONS,
				'fa4compatibility' => 'icon',
				'default'          => array(
					'value'   => 'fas fa-heart',
					'library' => 'fa-solid',
				),
				'condition'        => array( 'show_icon' => 'yes' ),
			)
		);

		$this->add_control(
			'icon_position',
			array(
				'label'     => esc_html__( 'Icon Position', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::SELECT,
				'default'   => 'left',
				'options'   => array(
					'left'  => esc_html__( 'Before Text', 'captain-widgets-kit' ),
					'right' => esc_html__( 'After Text', 'captain-widgets-kit' ),
				),
				'condition' => array( 'show_icon' => 'yes' ),
			)
		);

		$this->add_control(
			'show_text',
			array(
				'label'        => esc_html__( 'Show Text', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Show', 'captain-widgets-kit' ),
				'label_off'    => esc_html__( 'Hide', 'captain-widgets-kit' ),
				'return_value' => 'yes',
				'default'      => 'yes',
			)
		);

		$this->add_control(
			'add_text',
			array(
				'label'       => esc_html__( 'Add Label', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => esc_html__( 'Add to Wishlist', 'captain-widgets-kit' ),
				'label_block' => true,
				'condition'   => array( 'show_text' => 'yes' ),
				'dynamic'     => array( 'active' => true ),
			)
		);

		$this->add_control(
			'added_text',
			array(
				'label'       => esc_html__( 'Added Label', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => esc_html__( 'In Wishlist', 'captain-widgets-kit' ),
				'label_block' => true,
				'condition'   => array( 'show_text' => 'yes' ),
				'dynamic'     => array( 'active' => true ),
			)
		);

		$this->add_responsive_control(
			'wishlist_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'   => 'flex-start',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-woo-wishlist' => 'justify-content: {{VALUE}};',
				),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Style tab controls.
	 *
	 * @since 1.2.0
	 */
	private function register_style_controls(): void {

		$btn_selector  = '{{WRAPPER}} .captwiki-woo-wishlist__btn';
		$icon_selector = '{{WRAPPER}} .captwiki-woo-wishlist__icon';

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

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

		$this->add_responsive_control(
			'icon_size',
			array(
				'label'      => esc_html__( 'Icon Size', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px', 'em' ),
				'range'      => array( 'px' => array( 'min' => 8, 'max' => 60, 'step' => 1 ) ),
				'selectors'  => array(
					$icon_selector . ' svg' => 'width: {{SIZE}}{{UNIT}}; height: {{SIZE}}{{UNIT}};',
					$icon_selector          => 'font-size: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->add_responsive_control(
			'icon_spacing',
			array(
				'label'      => esc_html__( 'Icon Spacing', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px', 'em' ),
				'range'      => array( 'px' => array( 'min' => 0, 'max' => 40, 'step' => 1 ) ),
				'selectors'  => array(
					'{{WRAPPER}} .captwiki-woo-wishlist__btn' => 'gap: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->start_controls_tabs( 'tabs_button_state' );

			$this->start_controls_tab(
				'tab_button_normal',
				array( 'label' => esc_html__( 'Normal', 'captain-widgets-kit' ) )
			);

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

			$this->add_control(
				'button_icon_color',
				array(
					'label'     => esc_html__( 'Icon Color', 'captain-widgets-kit' ),
					'type'      => Controls_Manager::COLOR,
					'selectors' => array(
						$icon_selector . ' svg' => 'fill: {{VALUE}};',
						$icon_selector          => 'color: {{VALUE}};',
					),
				)
			);

			$this->add_group_control(
				Group_Control_Background::get_type(),
				array(
					'name'     => 'button_background',
					'label'    => esc_html__( 'Background', 'captain-widgets-kit' ),
					'types'    => array( 'classic', 'gradient' ),
					'selector' => $btn_selector,
					'exclude'  => array( 'image' ),
				)
			);

			$this->end_controls_tab();

			$this->start_controls_tab(
				'tab_button_hover',
				array( 'label' => esc_html__( 'Hover', 'captain-widgets-kit' ) )
			);

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

			$this->add_control(
				'button_icon_color_hover',
				array(
					'label'     => esc_html__( 'Icon Color', 'captain-widgets-kit' ),
					'type'      => Controls_Manager::COLOR,
					'selectors' => array(
						$btn_selector . ':hover .captwiki-woo-wishlist__icon svg' => 'fill: {{VALUE}};',
						$btn_selector . ':hover .captwiki-woo-wishlist__icon'     => 'color: {{VALUE}};',
					),
				)
			);

			$this->add_group_control(
				Group_Control_Background::get_type(),
				array(
					'name'     => 'button_background_hover',
					'label'    => esc_html__( 'Background', 'captain-widgets-kit' ),
					'types'    => array( 'classic', 'gradient' ),
					'selector' => $btn_selector . ':hover',
					'exclude'  => array( 'image' ),
				)
			);

			$this->end_controls_tab();

			$this->start_controls_tab(
				'tab_button_active',
				array( 'label' => esc_html__( 'Active', 'captain-widgets-kit' ) )
			);

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

			$this->add_control(
				'button_icon_color_active',
				array(
					'label'     => esc_html__( 'Icon Color', 'captain-widgets-kit' ),
					'type'      => Controls_Manager::COLOR,
					'selectors' => array(
						$btn_selector . '.is-active .captwiki-woo-wishlist__icon svg' => 'fill: {{VALUE}};',
						$btn_selector . '.is-active .captwiki-woo-wishlist__icon'     => 'color: {{VALUE}};',
					),
				)
			);

			$this->add_group_control(
				Group_Control_Background::get_type(),
				array(
					'name'     => 'button_background_active',
					'label'    => esc_html__( 'Background', 'captain-widgets-kit' ),
					'types'    => array( 'classic', 'gradient' ),
					'selector' => $btn_selector . '.is-active',
					'exclude'  => array( 'image' ),
				)
			);

			$this->end_controls_tab();

		$this->end_controls_tabs();

		$this->add_control( 'divider_button_border', array( 'type' => Controls_Manager::DIVIDER ) );

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

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

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

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

		$this->end_controls_section();
	}

	/**
	 * Build a list of published products for the source selector.
	 *
	 * @since 1.2.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;
	}

	/**
	 * Resolve the product ID to attach to the wishlist button.
	 *
	 * @since 1.2.0
	 * @param array $settings Widget settings.
	 * @return int
	 */
	private function captwiki_resolve_product_id( array $settings ): int {

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

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

		$current = get_the_ID();

		if ( $current && 'product' === get_post_type( $current ) ) {
			return (int) $current;
		}

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

			if ( ! empty( $latest ) ) {
				return (int) $latest[0]->get_id();
			}
		}

		return $current ? (int) $current : 0;
	}

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

		if ( ! class_exists( 'WooCommerce' ) ) {
			if ( \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
				echo '<div class="captwiki-woo-wishlist captwiki-woo-wishlist--notice"><p>' . esc_html__( 'WooCommerce is required for the Wishlist Button widget.', 'captain-widgets-kit' ) . '</p></div>';
			}
			return;
		}

		$settings   = $this->get_settings_for_display();
		$product_id = $this->captwiki_resolve_product_id( $settings );

		$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-wishlist-' . $style,
			CAPTWIKI_URL . 'assets/css/widgets/woo-wishlist/captwiki-woo-wishlist-' . $style . '.css',
			array( 'captwiki-woo-wishlist' ),
			CAPTWIKI_VERSION
		);

		$show_icon  = ! empty( $settings['show_icon'] ) && 'yes' === $settings['show_icon'];
		$show_text  = ! empty( $settings['show_text'] ) && 'yes' === $settings['show_text'];
		$icon_pos   = ! empty( $settings['icon_position'] ) ? sanitize_key( $settings['icon_position'] ) : 'left';
		$add_text   = ! empty( $settings['add_text'] ) ? $settings['add_text'] : esc_html__( 'Add to Wishlist', 'captain-widgets-kit' );
		$added_text = ! empty( $settings['added_text'] ) ? $settings['added_text'] : esc_html__( 'In Wishlist', 'captain-widgets-kit' );

		// Pre-render icon HTML.
		$icon_html = '';
		if ( $show_icon && ! empty( $settings['wishlist_icon']['value'] ) ) {
			ob_start();
			Icons_Manager::render_icon( $settings['wishlist_icon'], array( 'aria-hidden' => 'true' ) );
			$icon_html = '<span class="captwiki-woo-wishlist__icon" aria-hidden="true">' . ob_get_clean() . '</span>';
		}

		$text_html = $show_text ? '<span class="captwiki-woo-wishlist__text">' . esc_html( $add_text ) . '</span>' : '';

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

		echo '<div class="' . esc_attr( implode( ' ', $wrapper_classes ) ) . '">';
			echo '<button type="button" class="captwiki-woo-wishlist__btn" '
				. 'data-product-id="' . esc_attr( (string) $product_id ) . '" '
				. 'data-add-text="' . esc_attr( $add_text ) . '" '
				. 'data-added-text="' . esc_attr( $added_text ) . '" '
				. 'aria-pressed="false" '
				. 'aria-label="' . esc_attr( $add_text ) . '">';

		// $text_html is pre-escaped; $icon_html is trusted Icons_Manager markup
		// (an <svg> that wp_kses_post would strip), so output directly.
		if ( 'right' === $icon_pos ) {
			echo $text_html . $icon_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		} else {
			echo $icon_html . $text_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		}

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