<?php
/**
 * Widget Name: Product SKU
 * Description: Outputs the WooCommerce product SKU for the current product or a
 *              chosen product, with an optional label, empty-state handling, a
 *              fallback value 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_Typography;
use Elementor\Group_Control_Border;

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

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

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

	/**
	 * Get widget icon.
	 *
	 * @since 1.3.0
	 * @return string
	 */
	public function get_icon(): string {
		return 'eicon-product-meta 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', 'sku', 'code', 'reference', 'meta', '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 – Inline', 'captain-widgets-kit' ),
			'style-2' => esc_html__( 'Style 2 – Boxed', 'captain-widgets-kit' ),
			'style-3' => esc_html__( 'Style 3 – Pill', '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_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__( 'SKU', '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_label',
			array(
				'label'        => esc_html__( 'Show Label', '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(
			'label_text',
			array(
				'label'       => esc_html__( 'Label', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => esc_html__( 'SKU:', 'captain-widgets-kit' ),
				'label_block' => true,
				'condition'   => array( 'show_label' => 'yes' ),
			)
		);

		$this->add_control(
			'hide_if_empty',
			array(
				'label'        => esc_html__( 'Hide If Empty', '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'      => 'no',
			)
		);

		$this->add_control(
			'fallback_text',
			array(
				'label'       => esc_html__( 'Fallback', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => esc_html__( 'N/A', 'captain-widgets-kit' ),
				'label_block' => true,
				'description' => esc_html__( 'Shown when the product has no SKU (and "Hide If Empty" is off).', 'captain-widgets-kit' ),
				'condition'   => array( 'hide_if_empty' => '' ),
			)
		);

		$this->add_responsive_control(
			'sku_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-sku' => 'justify-content: {{VALUE}};',
				),
			)
		);

		$this->end_controls_section();
	}

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

		$wrap_selector  = '{{WRAPPER}} .captwiki-sku__inner';
		$label_selector = '{{WRAPPER}} .captwiki-sku__label';
		$value_selector = '{{WRAPPER}} .captwiki-sku__value';

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

		$this->add_responsive_control(
			'item_gap',
			array(
				'label'      => esc_html__( 'Gap', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px' ),
				'range'      => array( 'px' => array( 'min' => 0, 'max' => 30, 'step' => 1 ) ),
				'selectors'  => array(
					$wrap_selector => 'gap: {{SIZE}}{{UNIT}};',
				),
			)
		);

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

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

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

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

		$this->add_control(
			'label_heading',
			array(
				'label'     => esc_html__( 'Label', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::HEADING,
				'separator' => 'before',
			)
		);

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

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

		$this->add_control(
			'value_heading',
			array(
				'label'     => esc_html__( 'Value', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::HEADING,
				'separator' => 'before',
			)
		);

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

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

		$this->end_controls_section();
	}

	/**
	 * Resolve the product.
	 *
	 * @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;
		}

		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-sku captwiki-sku--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 SKU 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;
		}

		$sku       = $product->get_sku();
		$hide_empty = ! empty( $settings['hide_if_empty'] ) && 'yes' === $settings['hide_if_empty'];

		if ( '' === $sku ) {
			if ( $hide_empty ) {
				$this->captwiki_render_editor_notice( esc_html__( 'This product has no SKU (hidden on the live site).', 'captain-widgets-kit' ) );
				return;
			}
			$sku = ! empty( $settings['fallback_text'] ) ? $settings['fallback_text'] : esc_html__( 'N/A', 'captain-widgets-kit' );
		}

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

		$show_label = ! empty( $settings['show_label'] ) && 'yes' === $settings['show_label'];
		$label_text = ! empty( $settings['label_text'] ) ? $settings['label_text'] : esc_html__( 'SKU:', 'captain-widgets-kit' );

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

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

		if ( $show_label ) {
			echo '<span class="captwiki-sku__label">' . esc_html( $label_text ) . '</span>';
		}

		echo '<span class="captwiki-sku__value">' . esc_html( $sku ) . '</span>';

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