<?php
/**
 * Widget Name: Product Title
 * Description: Outputs the WooCommerce product title for the current product or a
 *              chosen product, with a selectable HTML tag, an optional link to the
 *              product, prefix/suffix text, a line clamp 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_Text_Stroke;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;

/**
 * Class Captwiki_Woo_Product_Title
 *
 * @since 1.4.0
 */
class Captwiki_Woo_Product_Title extends Widget_Base {

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

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

	/**
	 * Get widget icon.
	 *
	 * @since 1.4.0
	 * @return string
	 */
	public function get_icon(): string {
		return 'eicon-product-title 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', 'title', 'name', 'heading', '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 – Plain', 'captain-widgets-kit' ),
			'style-2' => esc_html__( 'Style 2 – Underline Accent', 'captain-widgets-kit' ),
			'style-3' => esc_html__( 'Style 3 – Left Bar', 'captain-widgets-kit' ),
			'style-4' => esc_html__( 'Style 4 – Highlight', 'captain-widgets-kit' ),
			'style-5' => esc_html__( 'Style 5 – Uppercase Tracking', 'captain-widgets-kit' ),
			'style-6' => esc_html__( 'Style 6 – Gradient Text', '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_title_style_controls();
		$this->register_box_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__( 'Title', '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(
			'html_tag',
			array(
				'label'   => esc_html__( 'HTML Tag', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'h1',
				'options' => array(
					'h1'   => 'H1',
					'h2'   => 'H2',
					'h3'   => 'H3',
					'h4'   => 'H4',
					'h5'   => 'H5',
					'h6'   => 'H6',
					'div'  => 'div',
					'span' => 'span',
					'p'    => 'p',
				),
			)
		);

		$this->add_control(
			'link_to_product',
			array(
				'label'        => esc_html__( 'Link To Product', '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(
			'open_new_tab',
			array(
				'label'        => esc_html__( 'Open In New Tab', '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',
				'condition'    => array( 'link_to_product' => 'yes' ),
			)
		);

		$this->add_control(
			'prefix_text',
			array(
				'label'     => esc_html__( 'Prefix', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::TEXT,
				'default'   => '',
				'separator' => 'before',
			)
		);

		$this->add_control(
			'suffix_text',
			array(
				'label'   => esc_html__( 'Suffix', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::TEXT,
				'default' => '',
			)
		);

		$this->add_control(
			'max_lines',
			array(
				'label'       => esc_html__( 'Limit Lines', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::NUMBER,
				'min'         => 0,
				'max'         => 10,
				'default'     => 0,
				'separator'   => 'before',
				'description' => esc_html__( 'Truncate the title after this many lines. 0 = no limit.', 'captain-widgets-kit' ),
			)
		);

		$this->add_responsive_control(
			'title_align',
			array(
				'label'     => esc_html__( 'Alignment', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::CHOOSE,
				'options'   => array(
					'left'   => 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',
					),
					'right'  => array(
						'title' => esc_html__( 'Right', 'captain-widgets-kit' ),
						'icon'  => 'eicon-text-align-right',
					),
				),
				'default'   => 'left',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-ptitle' => 'text-align: {{VALUE}};',
				),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Title style controls.
	 *
	 * @since 1.4.0
	 */
	private function register_title_style_controls(): void {

		$selector = '{{WRAPPER}} .captwiki-ptitle__text';
		$link     = '{{WRAPPER}} .captwiki-ptitle a';

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

		$this->start_controls_tabs( 'title_color_tabs' );

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

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

		$this->end_controls_tab();

		$this->start_controls_tab(
			'title_color_hover',
			array(
				'label'     => esc_html__( 'Hover', 'captain-widgets-kit' ),
				'condition' => array( 'link_to_product' => 'yes' ),
			)
		);

		$this->add_control(
			'title_color_hover_val',
			array(
				'label'     => esc_html__( 'Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array(
					'{{WRAPPER}} .captwiki-ptitle a:hover'                            => 'color: {{VALUE}};',
					'{{WRAPPER}} .captwiki-ptitle a:hover .captwiki-ptitle__text'     => 'color: {{VALUE}};',
				),
			)
		);

		$this->end_controls_tab();

		$this->end_controls_tabs();

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'      => 'title_typography',
				'selector'  => $selector,
				'separator' => 'before',
			)
		);

		$this->add_group_control(
			Group_Control_Text_Stroke::get_type(),
			array(
				'name'     => 'title_stroke',
				'selector' => $selector,
			)
		);

		$this->add_control(
			'affix_color',
			array(
				'label'     => esc_html__( 'Prefix / Suffix Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'separator' => 'before',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-ptitle__prefix, {{WRAPPER}} .captwiki-ptitle__suffix' => 'color: {{VALUE}};',
				),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Box style controls.
	 *
	 * @since 1.4.0
	 */
	private function register_box_style_controls(): void {

		$wrap_selector = '{{WRAPPER}} .captwiki-ptitle';

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

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

		$this->add_responsive_control(
			'box_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_group_control(
			Group_Control_Border::get_type(),
			array(
				'name'     => 'box_border',
				'selector' => $wrap_selector,
			)
		);

		$this->add_responsive_control(
			'box_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_group_control(
			Group_Control_Box_Shadow::get_type(),
			array(
				'name'     => 'box_shadow',
				'selector' => $wrap_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-ptitle captwiki-ptitle--notice"><p>' . esc_html( $message ) . '</p></div>';
	}

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

		$title = $product->get_name();

		if ( '' === trim( $title ) ) {
			$this->captwiki_render_editor_notice( esc_html__( 'This product has no title.', '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-title-' . $style,
			CAPTWIKI_URL . 'assets/css/widgets/woo-product-title/captwiki-woo-product-title-' . $style . '.css',
			array( 'captwiki-woo-product-title' ),
			CAPTWIKI_VERSION
		);

		$allowed_tags = array( 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div', 'span', 'p' );
		$tag          = ! empty( $settings['html_tag'] ) && in_array( $settings['html_tag'], $allowed_tags, true ) ? $settings['html_tag'] : 'h1';

		$max_lines = ! empty( $settings['max_lines'] ) ? absint( $settings['max_lines'] ) : 0;

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

		if ( $max_lines > 0 ) {
			$wrapper_classes[] = 'captwiki-ptitle--clamp';
		}

		$clamp_style = $max_lines > 0 ? ' style="--captwiki-ptitle-lines:' . esc_attr( (string) $max_lines ) . ';"' : '';

		// Inner content: prefix + title text + suffix.
		$inner = '';

		if ( ! empty( $settings['prefix_text'] ) ) {
			$inner .= '<span class="captwiki-ptitle__prefix">' . esc_html( $settings['prefix_text'] ) . '</span>';
		}

		$inner .= '<span class="captwiki-ptitle__text">' . esc_html( $title ) . '</span>';

		if ( ! empty( $settings['suffix_text'] ) ) {
			$inner .= '<span class="captwiki-ptitle__suffix">' . esc_html( $settings['suffix_text'] ) . '</span>';
		}

		// Optional link wrap.
		if ( ! empty( $settings['link_to_product'] ) && 'yes' === $settings['link_to_product'] ) {
			$url      = get_permalink( $product->get_id() );
			$new_tab  = ! empty( $settings['open_new_tab'] ) && 'yes' === $settings['open_new_tab'];
			$tab_attr = $new_tab ? ' target="_blank" rel="noopener noreferrer"' : '';
			$inner    = '<a href="' . esc_url( $url ) . '"' . $tab_attr . '>' . $inner . '</a>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		}

		echo '<' . esc_attr( $tag ) . ' class="' . esc_attr( implode( ' ', $wrapper_classes ) ) . '"' . $clamp_style . '>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		echo $inner; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		echo '</' . esc_attr( $tag ) . '>';
	}
}
