<?php

use Elementor\Core\DynamicTags\Tag;
use Elementor\Modules\DynamicTags\Module;

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly.
}

/**
 * Plus Addons Dynamic Tag - Product Title
 *
 * Provides a dynamic tag for Elementor to output the current product title.
 *
 * @since 6.4.5
 */
class ThePlus_Dynamic_Tag_Product_Rating extends Tag {

    /**
     * Unique dynamic tag name used internally by Elementor.
     *
     * @since 6.4.5
     * @return string
     */
	public function get_name(): string {
		return 'plus-tag-product-rating';
	}

    /**
     * Label shown in Elementor Dynamic Tags list.
     *
     * @since 6.4.5
     * @return string
     */
	public function get_title(): string {
		return esc_html__( 'Product Rating', 'theplus' );
	}

    /**
     * Registers the group under which this tag will appear.
     *
     * @since 6.4.5
     * @return array
     */
	public function get_group(): array {
		return [ 'plus-opt-woocommerce' ];
	}

    /**
     * Defines the category type (Text) for this dynamic tag.
     *
     * @since 6.4.5
     * @return array
     */
	public function get_categories(): array {
		return [
			Module::TEXT_CATEGORY,
		];
	}

    /**
     * Indicates that settings panel should be shown (even if empty).
     *
     * @since 6.4.5
     * @return bool
     */
    public function is_settings_required() {
		return true;
	}

	/**
	 * Register controls for this dynamic tag.
	 *
	 * @since 6.4.5
	 * @return void
	 */
	protected function register_controls(): void {
		$this->add_control(
			'rating_type',
			[
				'label'   => esc_html__( 'Rating Type', 'theplus' ),
				'type'    => \Elementor\Controls_Manager::SELECT,
				'default' => 'average',
				'options' => [
					'average'  => esc_html__( 'Average Rating (Number)', 'theplus' ),
					'count'    => esc_html__( 'Rating Count', 'theplus' ),
					'stars'    => esc_html__( 'Star Rating (HTML)', 'theplus' ),
					'fraction' => esc_html__( 'Fraction Rating (4.5/5)', 'theplus' ),
				],
			]
		);
	}

    /**
     * Render the dynamic product rating on frontend.
     *
     * Gets the current product ID and prints its rating.
     *
     * @since 6.4.5
     * @return void
     */
	public function render(): void {

		$product_id = get_the_ID();
		if ( ! $product_id ) {
			return;
		}

		$product = wc_get_product( $product_id );
		if ( ! $product ) {
			return;
		}

		$average = floatval( $product->get_average_rating() );
		$count   = intval( $product->get_rating_count() );
		$type    = $this->get_settings( 'rating_type' );

		switch ( $type ) {

			case 'average':
				if ( $average > 0 ) {
					echo esc_html( $average );
				}
				break;

			case 'count':
				echo esc_html( $count );
				break;

			case 'stars':
				echo wp_kses_post( wc_get_rating_html( $average, $count ) );
				break;

			case 'fraction':
				if ( $average > 0 ) {
					echo esc_html( $average . '/5' );
				}
				break;
		}
	}
}
