<?php
namespace BricksUltimate\Elements;

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

use BricksUltimate\Helpers;

class WooProductRatings extends \Bricks\Element {
	public $category 	= 'ultimate';
	public $name 		= 'bu-product-ratings';
	public $icon 		= 'ti-star';
	public $tag 		= 'div';

	// Return localized element label
	public function get_label() {
		return esc_html__( '(BU)Product Ratings', 'bricksultimate' );
	}

	// Set builder controls
	public function set_controls() {
		$this->controls['product_id'] = [
			'tab' 	=> 'content',
			'type' 	=> 'text',
			'label' => esc_html__( 'Product ID', 'bricksultimate' ),
			'info' 	=> esc_html__('Leave it blank if you are using on single product page or repeater.', 'bricksultimate'),
		];

		$this->controls['hideRatings'] = [
			'tab' 	=> 'content',
			'type' 	=> 'number',
			'label' => esc_html__( 'Do not show', 'bricksultimate' ),
			'description' => esc_html__( 'If number of reviews are less than', 'bricksultimate' ),
			'unit' 	=> false,
			'min' 	=> 0,
			'placeholder' => 0,
		];

		$this->controls['starsSeparator'] = [
			'tab' 	=> 'content',
			'type' 	=> 'separator',
			'label' => esc_html__( 'Stars', 'bricksultimate' ),
		];

		$this->controls['hideStars'] = [
			'tab' 	=> 'content',
			'type' 	=> 'checkbox',
			'label' => esc_html__( 'Disable stars', 'bricksultimate' ),
			'reset' => true,
		];

		$this->controls['starsColor'] = [
			'tab' 	=> 'content',
			'type' 	=> 'color',
			'label' => esc_html__( 'Star color', 'bricksultimate' ),
			'css' 	=> [
				[
					'selector' 	=> '.star-rating span:before, .woo-star-rating .star-fill',
					'property' 	=> 'color'
				]
			],
			'required' => ['hideStars', '!=', true ],
		];

		$this->controls['emptyStarsColor'] = [
			'tab' 	=> 'content',
			'type' 	=> 'color',
			'label' => esc_html__( 'Empty stars color', 'bricksultimate' ),
			'css' 	=> [
				[
					'selector' 	=> '.star-rating:before, .woo-star-rating .star-bg',
					'property' 	=> 'color'
				]
			],
			'required' => ['hideStars', '!=', true ],
		];

		$this->controls['fillEmptyStars'] = [
			'tab' 	=> 'content',
			'type' 	=> 'checkbox',
			'label' => esc_html__( 'Fill empty stars', 'bricksultimate' ),
			'reset' => true,
			'css' 	=> [
				[
					'selector' 	=> '.woo-star-rating .star svg',
					'property' 	=> 'fill',
					'value' 	=> 'currentColor'
				]
			],
		];

		$this->controls['starsSize'] = [
			'tab' 		=> 'content',
			'type' 		=> 'number',
			'label' 	=> esc_html__( 'Size in px', 'bricksultimate' ),
			'unit' 		=> 'px',
			'default' 	=> 15,
			'min' 		=> 10,
			'max' 		=> 100,
			'step' 		=> 1,
			'css' 		=> [
				/*[
					'selector' 	=> '.star-rating, .woo-star-rating .star',
					'property'  => 'font-size',
				],*/
				[
					'selector' 	=> '.star-rating, .woo-star-rating .star',
					'property'  => 'height',
				],
				[
					'selector' 	=> '.woo-star-rating .star svg, .woo-star-rating .star',
					'property'  => 'width',
					//'value' 	=> 'calc(%s * 5)',
				]
			],
			'required' => ['hideStars', '!=', true ],
		];

		$this->controls['strokeWd'] = [
			'tab' 		=> 'content',
			'type'      => 'number',
			'label'     => esc_html__('Stroke width', 'bricks'),
			'unit' 		=> 'px',
			'default' 	=> 2,
			'min' 		=> 0,
			'max' 		=> 100,
			'step' 		=> 1,
			'css' 		=> [
				[
					'selector' 	=> '.woo-star-rating .star svg',
					'property'  => 'stroke-width',
				]
			],
			'required' => ['hideStars', '!=', true ],
		];

		$this->controls['strokeColor'] = [
			'tab' 	=> 'content',
			'type' 	=> 'color',
			'label' => esc_html__( 'Stroke Color', 'bricksultimate' ),
			'css' 	=> [
				[
					'selector' 	=> '.woo-star-rating .star svg',
					'property' 	=> 'stroke'
				]
			],
			'required' => ['hideStars', '!=', true ],
		];

		$this->controls['gap'] = [
			'tab' 		=> 'content',
			'type'      => 'number',
			'label'     => esc_html__('Gap', 'bricks'),
			'unit' 		=> 'px',
			'default' 	=> 4,
			'min' 		=> 0,
			'max' 		=> 100,
			'step' 		=> 1,
			'css' 		=> [
				[
					'selector' 	=> '.woo-star-rating',
					'property'  => 'gap',
				]
			],
			'required' => ['hideStars', '!=', true ],
		];

		$this->controls['avrgPointsSeparator'] = [
			'tab' 	=> 'content',
			'type' 	=> 'separator',
			'label' => esc_html__( 'Average Rating Points', 'bricksultimate' ),
		];

		$this->controls['showRatingPoints'] = [
			'tab' 	=> 'content',
			'type' 	=> 'checkbox',
			'label' => esc_html__( 'Display rating points', 'bricksultimate' ),
			'reset' => true,
		];

		$this->controls['rating_text'] = [
			'tab' 	=> 'content',
			'type' 	=> 'text',
			'label' => esc_html__( 'Text', 'bricksultimate' ),
			'default' => '{product_average_ratings} out of 5',
			'placeholder' => '{product_average_ratings} out of 5',
			'required' => ['showRatingPoints', '=', true ],
		];

		$this->controls['sizingSeparator'] = [
			'tab'   => 'content',
			'type'  => 'separator',
			'label' => esc_html__( 'Size and Spacing', 'bricksultimate' ),
			'required' => ['showRatingPoints', '=', true ],
		];

		$this->controls['width'] = [
			'tab'   => 'content',
			'label' => esc_html__( 'Width', 'bricks' ),
			'type'  => 'number',
			'units' => true,
			'css'   => [
				[
					'property' => 'width',
					'selector' => '.average-rating',
				],
			],
			'required' => ['showRatingPoints', '=', true ],
		];

		$this->controls['height'] = [
			'tab'   => 'content',
			'label' => esc_html__( 'Height', 'bricks' ),
			'type'  => 'number',
			'units' => true,
			'css'   => [
				[
					'selector' 	=> '.average-rating',
					'property' => 'height',
				],
			],
			'required' => ['showRatingPoints', '=', true ],
		];

		$this->controls['padding'] = [
			'tab' 		=> 'content',
			'type'      => version_compare( BRICKS_VERSION, '1.5', '>') ? 'spacing' : 'dimensions',
			'label'     => esc_html__('Padding', 'bricks'),
			'css' 		=> [
				[
					'selector' 	=> '.average-rating',
					'property'  => 'padding',
				]
			],
			'required' => ['showRatingPoints', '=', true ],
		];

		$this->controls['styleSeparator'] = [
			'tab'   => 'content',
			'type'  => 'separator',
			'required' => ['showRatingPoints', '=', true ],
		];

		$this->controls['avrgTextBg'] = [
			'tab' 		=> 'content',
			'type'      => 'color',
			'label'     => esc_html__('Background', 'bricks'),
			'css' 		=> [
				[
					'selector' 	=> '.average-rating',
					'property'  => 'background-color',
				]
			],
			'required' => ['showRatingPoints', '=', true ],
		];

		$this->controls['avrgTextTg'] = [
			'tab' 		=> 'content',
			'type'      => 'typography',
			'label'     => esc_html__('Typography', 'bricks'),
			'css' 		=> [
				[
					'selector' 	=> '.average-rating',
					'property'  => 'font',
				]
			],
			'required' => ['showRatingPoints', '=', true ],
		];

		$this->controls['avrgTextBrd'] = [
			'tab' 		=> 'content',
			'type'      => 'border',
			'label'     => esc_html__('Border', 'bricks'),
			'css' 		=> [
				[
					'selector' 	=> '.average-rating',
					'property'  => 'border',
				]
			],
			'required' => ['showRatingPoints', '=', true ],
		];

		$this->controls['totalReveiwsSeparator'] = [
			'tab' 	=> 'content',
			'type' 	=> 'separator',
			'label' => esc_html__( 'Total reviews', 'bricksultimate' ),
		];

		$this->controls['showTotalReviews'] = [
			'tab' 	=> 'content',
			'type' 	=> 'checkbox',
			'label' => esc_html__( 'Display total reviews', 'bricksultimate' ),
			'reset' => true,
		];

		$this->controls['totalReviewsText'] = [
			'tab' 			=> 'content',
			'type' 			=> 'text',
			'label' 		=> esc_html__( 'Text', 'bricksultimate' ),
			'default' 		=> '{product_total_reviews} reviews',
			'placeholder' 	=> '{product_total_reviews} reviews',
			'required' 		=> ['showTotalReviews', '=', true],
		];

		$this->controls['sizingSeparator'] = [
			'tab'   => 'content',
			'type'  => 'separator',
			'label' => esc_html__( 'Size and Spacing', 'bricksultimate' ),
			'required' => ['showTotalReviews', '=', true ],
		];

		$this->controls['totalReviewsWidth'] = [
			'tab'   => 'content',
			'label' => esc_html__( 'Width', 'bricks' ),
			'type'  => 'number',
			'units' => true,
			'css'   => [
				[
					'property' => 'width',
					'selector' => '.total-reviews',
				],
			],
			'required' => ['showTotalReviews', '=', true ],
		];

		$this->controls['totalReviewsHeight'] = [
			'tab'   => 'content',
			'label' => esc_html__( 'Height', 'bricks' ),
			'type'  => 'number',
			'units' => true,
			'css'   => [
				[
					'selector' 	=> '.total-reviews',
					'property' => 'height',
				],
			],
			'required' => ['showTotalReviews', '=', true ],
		];

		$this->controls['totalReviewsPadding'] = [
			'tab' 		=> 'content',
			'type'      => version_compare( BRICKS_VERSION, '1.5', '>') ? 'spacing' : 'dimensions',
			'label'     => esc_html__('Padding', 'bricks'),
			'css' 		=> [
				[
					'selector' 	=> '.total-reviews',
					'property'  => 'padding',
				]
			],
			'required' => ['showTotalReviews', '=', true ],
		];

		$this->controls['totalReviewsStyleSeparator'] = [
			'tab'   => 'content',
			'type'  => 'separator',
			'required' => ['showTotalReviews', '=', true ],
		];

		$this->controls['totalReviewsBg'] = [
			'tab' 		=> 'content',
			'type'      => 'color',
			'label'     => esc_html__('Background', 'bricks'),
			'css' 		=> [
				[
					'selector' 	=> '.total-reviews',
					'property'  => 'background-color',
				]
			],
			'required' => ['showTotalReviews', '=', true ],
		];

		$this->controls['totalReviewsTg'] = [
			'tab' 		=> 'content',
			'type'      => 'typography',
			'label'     => esc_html__('Typography', 'bricks'),
			'css' 		=> [
				[
					'selector' 	=> '.total-reviews',
					'property'  => 'font',
				]
			],
			'required' => ['showTotalReviews', '=', true ],
		];

		$this->controls['totalReviewsBrd'] = [
			'tab' 		=> 'content',
			'type'      => 'border',
			'label'     => esc_html__('Border', 'bricks'),
			'css' 		=> [
				[
					'selector' 	=> '.total-reviews',
					'property'  => 'border',
				]
			],
			'required' => ['showTotalReviews', '=', true ],
		];
	}

	// Enqueue element styles and scripts
	/*public function enqueue_scripts() {
		if( bricks_is_builder() || bricks_is_builder_iframe() || bricks_is_builder_call() ){
			wp_enqueue_style( 'bu-product-ratings', Helpers::get_asset_url('css') . 'star-rating.min.css', [], filemtime(Helpers::get_asset_path('css') . 'star-rating.min.css' )
			);
		}
	}*/

	// Set builder controls
	public function render() {
		global $product;

		$settings = $this->settings;

		$product_id = bricks_render_dynamic_data( Helpers::get_value($settings, 'product_id', false) );

		if( empty( $product_id ) || $product_id === false )
			$product_id = $this->post_id;

		$product = wc_get_product( $product_id );

		if( $product === false )
			return;

		$total_reviews 	= $product->get_review_count();
		$average_rating = wc_format_decimal( $product->get_average_rating(), 2 );
		$show_stars 	= ! empty( $settings[ 'hideStars' ] ) ? false : true;
		$hideRatings 	= intval( Helpers::get_value($settings, 'hideRatings') );

		if( $total_reviews >= $hideRatings ) {
			echo "<{$this->tag} {$this->render_attributes('_root')}>";

			$average_rating_text = wp_kses_post( Helpers::get_value( $settings, 'rating_text') );
			if( !empty( $average_rating_text ) && !empty( $settings['showRatingPoints'] ) ):
				$this->set_attribute('average_rating_points', 'class', 'average-rating-points');
				echo "<div {$this->render_attributes('average_rating_points')}>{$average_rating_text}</div>";
			endif;

			if( $show_stars ):
				add_filter( 'woocommerce_product_get_rating_html', [ $this, 'bu_wc_get_rating_html' ], 10, 2 );
				echo wc_get_rating_html( $average_rating + 0.01 );
				remove_filter( 'woocommerce_product_get_rating_html', [ $this, 'bu_wc_get_rating_html' ], 10, 2 );
			endif;

			$totalReviewsText = wp_kses_post( Helpers::get_value( $settings, 'totalReviewsText') );
			if( !empty( $totalReviewsText ) && !empty( $settings['showTotalReviews'] ) ):
				$this->set_attribute('total_reviews', 'class', 'total-reviews');
				echo "<div {$this->render_attributes('total_reviews')}>{$totalReviewsText}</div>";
			endif;

			echo "</{$this->tag}>";
		}
	}

	public function bu_wc_get_rating_html( $html, $rating ) {
		if ( $rating <= 0 ) return $html;

	    $html = '<div class="woo-star-rating" role="img" aria-label="Rated ' . esc_attr( $rating ) . ' out of 5">';

	    for ( $i = 1; $i <= 5; $i++ ) {
	        $fill = 0;
	        if ( $rating >= $i ) {
	            $fill = 100;
	        } elseif ( $rating + 1 > $i ) {
	            $fill = ($rating - $i + 1) * 100;
	        }

	        $html .= '<div class="star">
	            <div class="star-bg">' . $this->get_star_svg('empty') . '</div>
	            <div class="star-fill" style="width:' . $fill . '%">' . $this->get_star_svg('filled') . '</div>
	        </div>';
	    }

	    $html .= '</div>';

	    return $html;
	}

	function get_star_svg($type = 'filled') {
	    if ( $type === 'filled' ) {
	        return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M12 .587l3.668 7.568L24 9.423l-6 5.847L19.335 24 12 19.771 4.665 24 6 15.27 0 9.423l8.332-1.268z"/></svg>';
	    } else {
	        return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 .587l3.668 7.568L24 9.423l-6 5.847L19.335 24 12 19.771 4.665 24 6 15.27 0 9.423l8.332-1.268z"/></svg>';
	    }
	}
}