<?php
/**
 * Widget Name: Product Rating
 * Description: Outputs the WooCommerce product star rating (accurate fractional
 *              stars), an optional numeric average and a review count for the
 *              current product or a chosen product, with an optional link to the
 *              reviews, empty handling 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;
use Elementor\Group_Control_Box_Shadow;

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

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

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

	/**
	 * Get widget icon.
	 *
	 * @since 1.4.0
	 * @return string
	 */
	public function get_icon(): string {
		return 'eicon-rating 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', 'rating', 'stars', 'reviews', 'review', '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 – Classic', 'captain-widgets-kit' ),
			'style-2' => esc_html__( 'Style 2 – Score Badge', 'captain-widgets-kit' ),
			'style-3' => esc_html__( 'Style 3 – Pill', 'captain-widgets-kit' ),
			'style-4' => esc_html__( 'Style 4 – Stacked', 'captain-widgets-kit' ),
			'style-5' => esc_html__( 'Style 5 – Boxed', 'captain-widgets-kit' ),
			'style-6' => esc_html__( 'Style 6 – Minimal', '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_stars_style_controls();
		$this->register_text_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__( 'Rating', '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_score',
			array(
				'label'        => esc_html__( 'Show Numeric Score', '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(
			'score_out_of',
			array(
				'label'        => esc_html__( 'Show "/ 5"', '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( 'show_score' => 'yes' ),
			)
		);

		$this->add_control(
			'show_count',
			array(
				'label'        => esc_html__( 'Show Review Count', '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(
			'count_tpl',
			array(
				'label'       => esc_html__( 'Count Template', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => esc_html__( '({count} reviews)', 'captain-widgets-kit' ),
				'description' => esc_html__( 'Use {count} for the number of reviews.', 'captain-widgets-kit' ),
				'condition'   => array( 'show_count' => 'yes' ),
			)
		);

		$this->add_control(
			'link_reviews',
			array(
				'label'        => esc_html__( 'Link To Reviews', '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(
			'empty_behavior',
			array(
				'label'     => esc_html__( 'When No Reviews', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::SELECT,
				'default'   => 'empty_stars',
				'options'   => array(
					'empty_stars' => esc_html__( 'Show Empty Stars', 'captain-widgets-kit' ),
					'text'        => esc_html__( 'Show Text', 'captain-widgets-kit' ),
					'hide'        => esc_html__( 'Hide Widget', 'captain-widgets-kit' ),
				),
				'separator' => 'before',
			)
		);

		$this->add_control(
			'empty_text',
			array(
				'label'     => esc_html__( 'No-Reviews Text', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::TEXT,
				'default'   => esc_html__( 'No reviews yet', 'captain-widgets-kit' ),
				'condition' => array( 'empty_behavior' => 'text' ),
			)
		);

		$this->add_responsive_control(
			'rating_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',
				'separator' => 'before',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-prating' => 'justify-content: {{VALUE}};',
				),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Stars style controls.
	 *
	 * @since 1.4.0
	 */
	private function register_stars_style_controls(): void {

		$stars_selector = '{{WRAPPER}} .captwiki-prating__stars';

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

		$this->add_responsive_control(
			'star_size',
			array(
				'label'      => esc_html__( 'Size', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px' ),
				'range'      => array( 'px' => array( 'min' => 10, 'max' => 50 ) ),
				'default'    => array( 'unit' => 'px', 'size' => 18 ),
				'selectors'  => array(
					$stars_selector => 'font-size: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->add_responsive_control(
			'star_letter_spacing',
			array(
				'label'      => esc_html__( 'Star Spacing', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px' ),
				'range'      => array( 'px' => array( 'min' => 0, 'max' => 12 ) ),
				'selectors'  => array(
					$stars_selector . ' .captwiki-prating__stars-empty' => 'letter-spacing: {{SIZE}}{{UNIT}};',
					$stars_selector . ' .captwiki-prating__stars-filled' => 'letter-spacing: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->add_control(
			'star_filled_color',
			array(
				'label'     => esc_html__( 'Filled Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array(
					$stars_selector . ' .captwiki-prating__stars-filled' => 'color: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'star_empty_color',
			array(
				'label'     => esc_html__( 'Empty Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => array(
					$stars_selector . ' .captwiki-prating__stars-empty' => 'color: {{VALUE}};',
				),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Score & count text style controls.
	 *
	 * @since 1.4.0
	 */
	private function register_text_style_controls(): void {

		$score_selector = '{{WRAPPER}} .captwiki-prating__score';
		$count_selector = '{{WRAPPER}} .captwiki-prating__count';

		$this->start_controls_section(
			'section_text_style',
			array(
				'label' => esc_html__( 'Score & Count', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

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

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

		$this->add_control(
			'count_color',
			array(
				'label'     => esc_html__( 'Count Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'separator' => 'before',
				'selectors' => array(
					$count_selector       => 'color: {{VALUE}};',
					$count_selector . ' a' => 'color: {{VALUE}};',
				),
			)
		);

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

		$this->end_controls_section();
	}

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

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

		$this->start_controls_section(
			'section_box_style',
			array(
				'label' => esc_html__( 'Box & Spacing', '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 ) ),
				'selectors'  => array(
					$wrap_selector => 'gap: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->add_control(
			'box_bg',
			array(
				'label'     => esc_html__( 'Background', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'separator' => 'before',
				'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;
	}

	/**
	 * Build the two-layer star markup for a given rating.
	 *
	 * @since 1.4.0
	 * @param float $rating Average rating (0–5).
	 * @return string
	 */
	private function captwiki_stars_html( float $rating ): string {

		$percent = max( 0, min( 100, ( $rating / 5 ) * 100 ) );
		$stars   = '★★★★★';

		$out  = '<span class="captwiki-prating__stars" role="img" aria-label="' . esc_attr( sprintf( /* translators: %s: rating value. */ __( 'Rated %s out of 5', 'captain-widgets-kit' ), wc_format_localized_decimal( $rating ) ) ) . '">';
		$out .= '<span class="captwiki-prating__stars-empty" aria-hidden="true">' . $stars . '</span>';
		$out .= '<span class="captwiki-prating__stars-filled" aria-hidden="true" style="width:' . esc_attr( (string) round( $percent, 2 ) ) . '%">' . $stars . '</span>';
		$out .= '</span>';

		return $out;
	}

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

		$rating       = (float) $product->get_average_rating();
		$review_count = (int) $product->get_review_count();
		$has_reviews  = $review_count > 0;
		$empty_mode   = ! empty( $settings['empty_behavior'] ) ? $settings['empty_behavior'] : 'empty_stars';

		if ( ! $has_reviews && 'hide' === $empty_mode ) {
			$this->captwiki_render_editor_notice( esc_html__( 'This product has no reviews yet (hidden on the live site).', '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-rating-' . $style,
			CAPTWIKI_URL . 'assets/css/widgets/woo-product-rating/captwiki-woo-product-rating-' . $style . '.css',
			array( 'captwiki-woo-product-rating' ),
			CAPTWIKI_VERSION
		);

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

		if ( ! $has_reviews ) {
			$wrapper_classes[] = 'captwiki-prating--empty';
		}

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

		// No reviews + text mode.
		if ( ! $has_reviews && 'text' === $empty_mode ) {
			$text = ! empty( $settings['empty_text'] ) ? $settings['empty_text'] : esc_html__( 'No reviews yet', 'captain-widgets-kit' );
			echo '<span class="captwiki-prating__empty-text">' . esc_html( $text ) . '</span>';
			echo '</div>';
			return;
		}

		// Stars.
		echo $this->captwiki_stars_html( $has_reviews ? $rating : 0.0 ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped

		// Numeric score.
		if ( $has_reviews && ! empty( $settings['show_score'] ) && 'yes' === $settings['show_score'] ) {
			$score_text = wc_format_localized_decimal( $rating );

			if ( ! empty( $settings['score_out_of'] ) && 'yes' === $settings['score_out_of'] ) {
				$score_text .= ' / 5';
			}

			echo '<span class="captwiki-prating__score">' . esc_html( $score_text ) . '</span>';
		}

		// Review count.
		if ( ! empty( $settings['show_count'] ) && 'yes' === $settings['show_count'] ) {
			$tpl   = ! empty( $settings['count_tpl'] ) ? $settings['count_tpl'] : '({count} reviews)';
			$label = str_replace( '{count}', number_format_i18n( $review_count ), $tpl );

			$link = ! empty( $settings['link_reviews'] ) && 'yes' === $settings['link_reviews'] && $has_reviews;

			if ( $link ) {
				$url = get_permalink( $product->get_id() ) . '#reviews';
				echo '<span class="captwiki-prating__count"><a href="' . esc_url( $url ) . '">' . esc_html( $label ) . '</a></span>';
			} else {
				echo '<span class="captwiki-prating__count">' . esc_html( $label ) . '</span>';
			}
		}

		echo '</div>';
	}
}
