<?php
/**
 * Widget Name: Product Stock
 * Description: Shows the WooCommerce stock status (in stock / out of stock /
 *              on backorder) for the current product or a chosen product, with an
 *              optional quantity, a low-stock highlight, custom labels, a status
 *              dot 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_Stock
 *
 * @since 1.3.0
 */
class Captwiki_Woo_Product_Stock extends Widget_Base {

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

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

	/**
	 * Get widget icon.
	 *
	 * @since 1.3.0
	 * @return string
	 */
	public function get_icon(): string {
		return 'eicon-product-stock 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', 'stock', 'inventory', 'availability', 'quantity', '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 – Pill', 'captain-widgets-kit' ),
			'style-3' => esc_html__( 'Style 3 – Soft Badge', '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__( 'Stock', '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 Status Dot', '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(
			'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'      => 'no',
				'description'  => esc_html__( 'Only shown for products that manage stock.', 'captain-widgets-kit' ),
			)
		);

		$this->add_control(
			'quantity_text',
			array(
				'label'       => esc_html__( 'Quantity Text', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => esc_html__( '{qty} in stock', 'captain-widgets-kit' ),
				'label_block' => true,
				'description' => esc_html__( 'Use {qty} for the number.', 'captain-widgets-kit' ),
				'condition'   => array( 'show_quantity' => 'yes' ),
			)
		);

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

		$this->add_control(
			'in_stock_text',
			array(
				'label'       => esc_html__( 'In Stock', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => esc_html__( 'In Stock', 'captain-widgets-kit' ),
				'label_block' => true,
			)
		);

		$this->add_control(
			'out_of_stock_text',
			array(
				'label'       => esc_html__( 'Out of Stock', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => esc_html__( 'Out of Stock', 'captain-widgets-kit' ),
				'label_block' => true,
			)
		);

		$this->add_control(
			'on_backorder_text',
			array(
				'label'       => esc_html__( 'On Backorder', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => esc_html__( 'Available on Backorder', 'captain-widgets-kit' ),
				'label_block' => true,
			)
		);

		$this->add_control(
			'low_stock_text',
			array(
				'label'       => esc_html__( 'Low Stock', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => esc_html__( 'Only {qty} left!', 'captain-widgets-kit' ),
				'label_block' => true,
				'description' => esc_html__( 'Shown when stock is at or below the low-stock threshold. Use {qty}. Leave empty to keep the In Stock label.', 'captain-widgets-kit' ),
			)
		);

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

		$this->end_controls_section();
	}

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

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

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

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

		$this->add_responsive_control(
			'icon_size',
			array(
				'label'      => esc_html__( 'Dot Size', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px' ),
				'range'      => array( 'px' => array( 'min' => 4, 'max' => 24, 'step' => 1 ) ),
				'selectors'  => array(
					'{{WRAPPER}} .captwiki-stock__dot' => 'width: {{SIZE}}{{UNIT}}; height: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$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' => 24, 'step' => 1 ) ),
				'selectors'  => array(
					$badge_selector => 'gap: {{SIZE}}{{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_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_control(
			'colors_heading',
			array(
				'label'     => esc_html__( 'Status Colors', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::HEADING,
				'separator' => 'before',
			)
		);

		$this->add_control(
			'in_stock_color',
			array(
				'label'     => esc_html__( 'In Stock', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#16a34a',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-stock--instock' => '--captwiki-stock-color: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'low_stock_color',
			array(
				'label'     => esc_html__( 'Low Stock', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#d97706',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-stock--lowstock' => '--captwiki-stock-color: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'out_of_stock_color',
			array(
				'label'     => esc_html__( 'Out of Stock', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#dc2626',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-stock--outofstock' => '--captwiki-stock-color: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'backorder_color',
			array(
				'label'     => esc_html__( 'On Backorder', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#2563eb',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-stock--onbackorder' => '--captwiki-stock-color: {{VALUE}};',
				),
			)
		);

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

		$status = $product->get_stock_status();
		$qty    = $product->get_stock_quantity();

		// Detect low stock for managed-stock products.
		$is_low = false;
		if ( $product->managing_stock() && null !== $qty && 'instock' === $status ) {
			$low_amount = function_exists( 'wc_get_low_stock_amount' ) ? (int) wc_get_low_stock_amount( $product ) : 0;
			$is_low     = ( $qty > 0 && $qty <= $low_amount );
		}

		$in_stock_text  = ! empty( $settings['in_stock_text'] ) ? $settings['in_stock_text'] : esc_html__( 'In Stock', 'captain-widgets-kit' );
		$out_text       = ! empty( $settings['out_of_stock_text'] ) ? $settings['out_of_stock_text'] : esc_html__( 'Out of Stock', 'captain-widgets-kit' );
		$backorder_text = ! empty( $settings['on_backorder_text'] ) ? $settings['on_backorder_text'] : esc_html__( 'Available on Backorder', 'captain-widgets-kit' );
		$low_text       = isset( $settings['low_stock_text'] ) ? $settings['low_stock_text'] : '';

		// Resolve the status key + label.
		$state = 'instock';
		$label = $in_stock_text;

		if ( 'outofstock' === $status ) {
			$state = 'outofstock';
			$label = $out_text;
		} elseif ( 'onbackorder' === $status ) {
			$state = 'onbackorder';
			$label = $backorder_text;
		} elseif ( $is_low && '' !== $low_text ) {
			$state = 'lowstock';
			$label = str_replace( '{qty}', (string) $qty, $low_text );
		}

		// Optional quantity suffix (managed stock only).
		$qty_html = '';
		if ( ! empty( $settings['show_quantity'] ) && 'yes' === $settings['show_quantity'] && null !== $qty && $product->managing_stock() ) {
			$qty_tpl  = ! empty( $settings['quantity_text'] ) ? $settings['quantity_text'] : esc_html__( '{qty} in stock', 'captain-widgets-kit' );
			$qty_html = '<span class="captwiki-stock__qty">' . esc_html( str_replace( '{qty}', (string) $qty, $qty_tpl ) ) . '</span>';
		}

		$show_icon = ! empty( $settings['show_icon'] ) && 'yes' === $settings['show_icon'];

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

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

		if ( $show_icon ) {
			echo '<span class="captwiki-stock__dot" aria-hidden="true"></span>';
		}

		echo '<span class="captwiki-stock__label">' . esc_html( $label ) . '</span>';
		echo $qty_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped

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