<?php
/**
 * Widget Name: Product Add to Cart
 * Description: WooCommerce add-to-cart form for the current product or a chosen
 *              product, with full button + quantity styling. Supports simple and
 *              variable products via the WooCommerce single add-to-cart template.
 *
 * @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;

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

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

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

	/**
	 * Get widget icon.
	 *
	 * @since 1.2.0
	 * @return string
	 */
	public function get_icon(): string {
		return 'eicon-product-add-to-cart 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', 'add to cart', 'cart', 'product', 'buy', '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 – Classic', 'captain-widgets-kit' ),
			'style-2' => esc_html__( 'Style 2 – Outline', 'captain-widgets-kit' ),
			'style-3' => esc_html__( 'Style 3 – Pill Gradient', 'captain-widgets-kit' ),
		);
	}

	/**
	 * 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;
	}

	/**
	 * Register controls.
	 *
	 * @since 1.2.0
	 */
	protected function register_controls(): void {
		$this->register_content_controls();
		$this->register_button_style_controls();
		$this->register_quantity_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__( 'Add to Cart', '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(
			'custom_button_text',
			array(
				'label'       => esc_html__( 'Custom Button Text', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::TEXT,
				'placeholder' => esc_html__( 'Add to cart', 'captain-widgets-kit' ),
				'label_block' => true,
				'description' => esc_html__( 'Leave empty to use the WooCommerce default text.', 'captain-widgets-kit' ),
				'dynamic'     => array( 'active' => true ),
			)
		);

		$this->add_control(
			'show_quantity',
			array(
				'label'        => esc_html__( 'Show Quantity', '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_responsive_control(
			'cart_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-add-to-cart form.cart' => 'justify-content: {{VALUE}};',
				),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Button style controls.
	 *
	 * @since 1.2.0
	 */
	private function register_button_style_controls(): void {

		$button_selector = '{{WRAPPER}} .captwiki-woo-add-to-cart .single_add_to_cart_button';

		$this->start_controls_section(
			'section_style_button',
			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' => $button_selector,
			)
		);

		$this->start_controls_tabs( 'tabs_button_colors' );

			$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(
						$button_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' => $button_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(
						$button_selector . ':hover, ' . $button_selector . ':focus' => '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' => $button_selector . ':hover, ' . $button_selector . ':focus',
					'exclude'  => array( 'image' ),
				)
			);

			$this->add_control(
				'button_transition',
				array(
					'label'     => esc_html__( 'Transition (s)', 'captain-widgets-kit' ),
					'type'      => Controls_Manager::SLIDER,
					'range'     => array( 'px' => array( 'min' => 0, 'max' => 3, 'step' => 0.1 ) ),
					'default'   => array( 'size' => 0.3 ),
					'selectors' => array(
						$button_selector => 'transition: all {{SIZE}}s ease;',
					),
				)
			);

			$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' => $button_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', '%', 'em' ),
				'selectors'  => array(
					$button_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' => $button_selector,
			)
		);

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

		$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(
					$button_selector => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->add_responsive_control(
			'button_width',
			array(
				'label'      => esc_html__( 'Button Width', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px', '%' ),
				'range'      => array(
					'px' => array( 'min' => 0, 'max' => 600, 'step' => 1 ),
					'%'  => array( 'min' => 0, 'max' => 100, 'step' => 1 ),
				),
				'selectors'  => array(
					$button_selector => 'width: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Quantity style controls.
	 *
	 * @since 1.2.0
	 */
	private function register_quantity_style_controls(): void {

		$qty_selector = '{{WRAPPER}} .captwiki-woo-add-to-cart .quantity .qty';

		$this->start_controls_section(
			'section_style_quantity',
			array(
				'label'     => esc_html__( 'Quantity', 'captain-widgets-kit' ),
				'tab'       => Controls_Manager::TAB_STYLE,
				'condition' => array( 'show_quantity' => 'yes' ),
			)
		);

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

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

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

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

		$this->add_responsive_control(
			'quantity_width',
			array(
				'label'      => esc_html__( 'Field Width', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px', 'em' ),
				'range'      => array( 'px' => array( 'min' => 40, 'max' => 200, 'step' => 1 ) ),
				'selectors'  => array(
					$qty_selector => 'width: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->add_responsive_control(
			'quantity_spacing',
			array(
				'label'      => esc_html__( 'Spacing', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px', 'em' ),
				'range'      => array( 'px' => array( 'min' => 0, 'max' => 60, 'step' => 1 ) ),
				'selectors'  => array(
					'{{WRAPPER}} .captwiki-woo-add-to-cart .quantity' => 'margin-inline-end: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Resolve the product to render the add-to-cart form for.
	 *
	 * Falls back to the most recent product inside the Elementor editor so the
	 * widget always previews something even outside a single-product template.
	 *
	 * @since 1.2.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.2.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-woo-add-to-cart captwiki-woo-add-to-cart--notice">';
			echo '<p>' . esc_html( $message ) . '</p>';
		echo '</div>';
	}

	/**
	 * Render widget output on the frontend.
	 *
	 * @since 1.2.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 Add to Cart 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';

		// Load only the active style stylesheet, depending on the common one.
		wp_enqueue_style(
			'captwiki-woo-add-to-cart-' . $style,
			CAPTWIKI_URL . 'assets/css/widgets/woo-add-to-cart/captwiki-woo-add-to-cart-' . $style . '.css',
			array( 'captwiki-woo-add-to-cart' ),
			CAPTWIKI_VERSION
		);

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

		if ( empty( $settings['show_quantity'] ) || 'yes' !== $settings['show_quantity'] ) {
			$wrapper_classes[] = 'captwiki-woo-add-to-cart--no-qty';
		}

		// Preserve and swap the global product so WooCommerce templates target ours.
		$previous_product   = isset( $GLOBALS['product'] ) ? $GLOBALS['product'] : null;
		$GLOBALS['product'] = $product;

		$custom_text = ! empty( $settings['custom_button_text'] ) ? $settings['custom_button_text'] : '';
		$text_filter = null;

		if ( '' !== $custom_text ) {
			$text_filter = static function () use ( $custom_text ) {
				return $custom_text;
			};
			add_filter( 'woocommerce_product_single_add_to_cart_text', $text_filter );
		}

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

		if ( $product->is_purchasable() || $product->is_type( 'variable' ) || $product->is_type( 'grouped' ) || $product->is_type( 'external' ) ) {
			// WooCommerce core template prints trusted markup (forms/inputs that
			// wp_kses_post would strip), so it is output directly.
			woocommerce_template_single_add_to_cart(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		} else {
			echo '<p class="captwiki-woo-add-to-cart__unavailable">' . esc_html__( 'This product is not available for purchase.', 'captain-widgets-kit' ) . '</p>';
		}

		echo '</div>';

		// Restore global state.
		if ( null !== $text_filter ) {
			remove_filter( 'woocommerce_product_single_add_to_cart_text', $text_filter );
		}

		$GLOBALS['product'] = $previous_product;
	}
}
