<?php
/**
 * Widget Name: Product Tabs
 * Description: Outputs the WooCommerce product data tabs (Description, Additional
 *              Information, Reviews and any third-party tabs) for the current or a
 *              chosen product, as horizontal tabs, vertical tabs or an accordion,
 *              with per-tab toggles, custom titles and multiple attractive styles.
 *
 * @package    captain-widgets-kit
 * @subpackage captain-widgets-kit/includes
 * @since      1.4.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_Tab
 *
 * @since 1.4.0
 */
class Captwiki_Woo_Product_Tab extends Widget_Base {

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

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

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

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

	/**
	 * Get widget keywords.
	 *
	 * @since 1.4.0
	 * @return array
	 */
	public function get_keywords(): array {
		return array( 'woocommerce', 'woo', 'product', 'tabs', 'description', 'reviews', 'accordion', 'captain-widgets-kit' );
	}

	/**
	 * Disable Elementor's default inner wrapper.
	 *
	 * @since 1.4.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.4.0
	 * @return array
	 */
	private function captwiki_style_options(): array {
		return array(
			'style-1' => esc_html__( 'Style 1 – Underline', 'captain-widgets-kit' ),
			'style-2' => esc_html__( 'Style 2 – Pills', 'captain-widgets-kit' ),
			'style-3' => esc_html__( 'Style 3 – Boxed', 'captain-widgets-kit' ),
			'style-4' => esc_html__( 'Style 4 – Bordered', 'captain-widgets-kit' ),
			'style-5' => esc_html__( 'Style 5 – Minimal', 'captain-widgets-kit' ),
			'style-6' => esc_html__( 'Style 6 – Segmented', 'captain-widgets-kit' ),
		);
	}

	/**
	 * Build a list of published products for the source selector.
	 *
	 * @since 1.4.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.4.0
	 */
	protected function register_controls(): void {
		$this->register_content_controls();
		$this->register_nav_style_controls();
		$this->register_panel_style_controls();
	}

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

		$this->start_controls_section(
			'section_content',
			array(
				'label' => esc_html__( 'Tabs', '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(
			'layout',
			array(
				'label'   => esc_html__( 'Layout', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'horizontal',
				'options' => array(
					'horizontal' => esc_html__( 'Horizontal Tabs', 'captain-widgets-kit' ),
					'vertical'   => esc_html__( 'Vertical Tabs', 'captain-widgets-kit' ),
					'accordion'  => esc_html__( 'Accordion', 'captain-widgets-kit' ),
				),
			)
		);

		$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(
			'active_tab',
			array(
				'label'       => esc_html__( 'Default Open Tab', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::NUMBER,
				'min'         => 1,
				'max'         => 20,
				'default'     => 1,
				'description' => esc_html__( 'Which tab is open on load (1 = first).', 'captain-widgets-kit' ),
			)
		);

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

		$this->add_control(
			'show_description',
			array(
				'label'        => esc_html__( 'Description', '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(
			'description_title',
			array(
				'label'       => esc_html__( 'Description Title', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::TEXT,
				'placeholder' => esc_html__( 'Description', 'captain-widgets-kit' ),
				'condition'   => array( 'show_description' => 'yes' ),
			)
		);

		$this->add_control(
			'show_additional',
			array(
				'label'        => esc_html__( 'Additional Information', '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(
			'additional_title',
			array(
				'label'       => esc_html__( 'Additional Info Title', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::TEXT,
				'placeholder' => esc_html__( 'Additional information', 'captain-widgets-kit' ),
				'condition'   => array( 'show_additional' => 'yes' ),
			)
		);

		$this->add_control(
			'show_reviews',
			array(
				'label'        => esc_html__( 'Reviews', '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(
			'reviews_title',
			array(
				'label'       => esc_html__( 'Reviews Title', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::TEXT,
				'placeholder' => esc_html__( 'Reviews', 'captain-widgets-kit' ),
				'condition'   => array( 'show_reviews' => 'yes' ),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Tab navigation style controls.
	 *
	 * @since 1.4.0
	 */
	private function register_nav_style_controls(): void {

		$tab_selector    = '{{WRAPPER}} .captwiki-ptabs__tab, {{WRAPPER}} .captwiki-ptabs__acc-header';
		$active_selector = '{{WRAPPER}} .captwiki-ptabs__tab.is-active, {{WRAPPER}} .captwiki-ptabs__acc-header.is-active';

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

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

		$this->start_controls_tabs( 'tab_state_tabs' );

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

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

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

		$this->end_controls_tab();

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

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

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

		$this->add_control(
			'tab_accent_active',
			array(
				'label'       => esc_html__( 'Accent Color', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::COLOR,
				'description' => esc_html__( 'Underline / border accent on the active tab.', 'captain-widgets-kit' ),
				'selectors'   => array(
					$active_selector => 'border-color: {{VALUE}};',
				),
			)
		);

		$this->end_controls_tab();

		$this->end_controls_tabs();

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

		$this->add_responsive_control(
			'tab_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 ) ),
				'selectors'  => array(
					'{{WRAPPER}} .captwiki-ptabs__nav' => 'gap: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Panel style controls.
	 *
	 * @since 1.4.0
	 */
	private function register_panel_style_controls(): void {

		$panel_selector = '{{WRAPPER}} .captwiki-ptabs__panel, {{WRAPPER}} .captwiki-ptabs__acc-panel-inner';

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

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

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

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

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

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

		$this->end_controls_section();
	}

	/**
	 * Resolve the product.
	 *
	 * @since 1.4.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.4.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-ptabs captwiki-ptabs--notice"><p>' . esc_html( $message ) . '</p></div>';
	}

	/**
	 * Collect the product tabs (titles + rendered content).
	 *
	 * @since 1.4.0
	 * @param \WC_Product $product  Product.
	 * @param array       $settings Widget settings.
	 * @return array List of array( 'key', 'title', 'content' ).
	 */
	private function captwiki_collect_tabs( $product, array $settings ): array {

		global $post;

		$saved_post           = $post;
		$GLOBALS['product']   = $product;
		$post                 = get_post( $product->get_id() );

		if ( $post ) {
			setup_postdata( $post );
		}

		$wc_tabs = apply_filters( 'woocommerce_product_tabs', array() );

		// Per-tab visibility toggles for the core tabs.
		$toggle_map = array(
			'description'            => 'show_description',
			'additional_information' => 'show_additional',
			'reviews'                => 'show_reviews',
		);

		$title_map = array(
			'description'            => 'description_title',
			'additional_information' => 'additional_title',
			'reviews'                => 'reviews_title',
		);

		$collected = array();

		foreach ( $wc_tabs as $key => $tab ) {

			if ( isset( $toggle_map[ $key ] ) ) {
				$enabled = ! empty( $settings[ $toggle_map[ $key ] ] ) && 'yes' === $settings[ $toggle_map[ $key ] ];
				if ( ! $enabled ) {
					continue;
				}
			}

			$title = isset( $tab['title'] ) ? $tab['title'] : ucfirst( $key );

			if ( isset( $title_map[ $key ] ) && ! empty( $settings[ $title_map[ $key ] ] ) ) {
				$title = $settings[ $title_map[ $key ] ];
			}

			$content = '';

			if ( isset( $tab['callback'] ) && is_callable( $tab['callback'] ) ) {
				ob_start();
				call_user_func( $tab['callback'], $key, $tab );
				$content = ob_get_clean();
			}

			$collected[] = array(
				'key'     => $key,
				'title'   => $title,
				'content' => $content,
			);
		}

		// Restore globals.
		$post = $saved_post;
		wp_reset_postdata();

		return $collected;
	}

	/**
	 * Render widget output on the frontend.
	 *
	 * @since 1.4.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 Tabs 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;
		}

		$tabs = $this->captwiki_collect_tabs( $product, $settings );

		if ( empty( $tabs ) ) {
			$this->captwiki_render_editor_notice( esc_html__( 'No tabs to display for this product with the current options.', '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';

		$allowed_layout = array( 'horizontal', 'vertical', 'accordion' );
		$layout         = ! empty( $settings['layout'] ) && in_array( $settings['layout'], $allowed_layout, true ) ? $settings['layout'] : 'horizontal';

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

		wp_enqueue_script( 'captwiki-woo-product-tab' );

		$active = ! empty( $settings['active_tab'] ) ? absint( $settings['active_tab'] ) - 1 : 0;
		$active = max( 0, min( $active, count( $tabs ) - 1 ) );

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

		$uid = 'captwiki-ptabs-' . $this->get_id();

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

		if ( 'accordion' === $layout ) {

			// Accordion: header + panel pairs.
			foreach ( $tabs as $i => $tab ) {
				$is_active   = ( $i === $active );
				$header_id   = $uid . '-h-' . $i;
				$panel_id    = $uid . '-p-' . $i;
				$active_attr = $is_active ? ' is-active' : '';

				echo '<div class="captwiki-ptabs__item' . esc_attr( $active_attr ) . '">';
				echo '<button type="button" id="' . esc_attr( $header_id ) . '" class="captwiki-ptabs__acc-header' . esc_attr( $active_attr ) . '" aria-expanded="' . ( $is_active ? 'true' : 'false' ) . '" aria-controls="' . esc_attr( $panel_id ) . '">';
				echo '<span class="captwiki-ptabs__acc-title">' . esc_html( $tab['title'] ) . '</span>';
				echo '<span class="captwiki-ptabs__acc-icon" aria-hidden="true"></span>';
				echo '</button>';
				echo '<div id="' . esc_attr( $panel_id ) . '" class="captwiki-ptabs__acc-panel' . esc_attr( $active_attr ) . '" role="region" aria-labelledby="' . esc_attr( $header_id ) . '">';
				echo '<div class="captwiki-ptabs__acc-panel-inner">' . wp_kses_post( $tab['content'] ) . '</div>';
				echo '</div>';
				echo '</div>';
			}
		} else {

			// Horizontal / vertical tabs.
			echo '<ul class="captwiki-ptabs__nav" role="tablist">';
			foreach ( $tabs as $i => $tab ) {
				$is_active = ( $i === $active );
				$tab_id    = $uid . '-t-' . $i;
				$panel_id  = $uid . '-p-' . $i;

				echo '<li class="captwiki-ptabs__nav-item" role="presentation">';
				echo '<button type="button" id="' . esc_attr( $tab_id ) . '" class="captwiki-ptabs__tab' . ( $is_active ? ' is-active' : '' ) . '" role="tab" aria-selected="' . ( $is_active ? 'true' : 'false' ) . '" aria-controls="' . esc_attr( $panel_id ) . '" data-index="' . esc_attr( (string) $i ) . '">';
				echo esc_html( $tab['title'] );
				echo '</button>';
				echo '</li>';
			}
			echo '</ul>';

			echo '<div class="captwiki-ptabs__panels">';
			foreach ( $tabs as $i => $tab ) {
				$is_active = ( $i === $active );
				$tab_id    = $uid . '-t-' . $i;
				$panel_id  = $uid . '-p-' . $i;

				echo '<div id="' . esc_attr( $panel_id ) . '" class="captwiki-ptabs__panel' . ( $is_active ? ' is-active' : '' ) . '" role="tabpanel" aria-labelledby="' . esc_attr( $tab_id ) . '"' . ( $is_active ? '' : ' hidden' ) . '>';
				echo wp_kses_post( $tab['content'] );
				echo '</div>';
			}
			echo '</div>';
		}

		echo '</div>';
	}
}
