<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}
use \Elementor\Widget_Base;
use \Elementor\Controls_Manager;
use \Elementor\Group_Control_Typography;
use \Elementor\Plugin as ElementorPlugin;
use \Sifency\Traits\Sifency_Animation_Controls;
use Sifency\Traits\Sifency_Animation_Manager;
use Sifency\Traits\Sifency_Product_Rating_Controls;

class Sifency_Widget_Product_Rating extends Widget_Base {
    use Sifency_Animation_Controls;
    use Sifency_Product_Rating_Controls;

    public function get_name() {
        return 'sifency-product-rating'; 
    }

    public function get_title() {
        return __('Sifency Product Rating', 'sifency-addons');
    }

    public function get_icon() {
        return 'eicon-product-rating';
    }

    public function get_categories() {
        return ['sifency-addons-woo-widgets'];
    }

    public function get_keywords() {
        return ['product', 'rating', 'stars', 'review', 'woocommerce', 'sifency'];
    }

    public function get_style_depends() {
	    return [ 'sifency-frontend-style' ];
    }

    protected function register_controls() {
        if ( ! class_exists('woocommerce') ) {
            $this->start_controls_section('woo_notice', [ 'label' => 'Notice' ]);
            $this->add_control('woo_notice_control', [ 'type' => Controls_Manager::RAW_HTML, 'raw' => '<div class="elementor-panel-alert elementor-panel-alert-warning">' . esc_html__('WooCommerce is not installed or active.', 'sifency-addons') . '</div>' ]);
            $this->end_controls_section();
            return;
        }
        $this->add_sifency_product_rating_controls();
        $this->add_sifency_animation_controls();
        $this->update_control(
            'sifency_animation_target',
            [
                'type' => Controls_Manager::HIDDEN,
                'default' => 'wrapper',
            ]
        );
    }

    protected function render() {
        if ( \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
            $this->render_editor_preview();
            return;
        }

        $this->render_live_rating();
    }

    /**
     * Renders the rating based on a real product for the live site.
     */
    private function render_live_rating() {
        $product = wc_get_product();
        if ( empty($product) ) { return; }
        
        if ( 'no' === get_option( 'woocommerce_enable_reviews' ) ) { return; }
        
        $settings = $this->get_settings_for_display();
        
        if ('yes' !== $settings['show_review_link']) {
            add_filter( 'woocommerce_product_get_rating_html', [ $this, 'remove_review_link' ], 10, 2 );
        }
        
        $this->render_html( 'woocommerce_template_single_rating' );

        if ('yes' !== $settings['show_review_link']) {
            remove_filter( 'woocommerce_product_get_rating_html', [ $this, 'remove_review_link' ], 10, 2 );
        }
    }
    
    /**
     * Renders a fake rating for live preview in the Elementor editor.
     *
     * @since 1.0.4
     * @access private
     */
    private function render_editor_preview() {
        $settings = $this->get_settings_for_display();
        $rating = $settings['editor_preview_rating']['size'] ?? 4;
        $count  = $settings['editor_preview_count'] ?? 3;

        $rating_percentage = ( $rating / 5 ) * 100;

        $rating_html  = '<div class="woocommerce-product-rating">';

        /* translators: %s: Product rating value. */
        $rating_html .= '<div class="star-rating" role="img" aria-label="' . sprintf( esc_attr__( 'Rated %s out of 5', 'sifency-addons' ), $rating ) . '">';

        /* translators: %s: Product rating value wrapped in strong tag. */
        $rating_html .= '<span style="width:' . esc_attr( $rating_percentage ) . '%">' . sprintf( esc_html__( 'Rated %s out of 5', 'sifency-addons' ), '<strong>' . esc_html( $rating ) . '</strong>' ) . '</span>';
        $rating_html .= '</div>';

        if ( 'yes' === ( $settings['show_review_link'] ?? '' ) && $count > 0 ) {
            $rating_html .= '<a href="#reviews" class="woocommerce-review-link" rel="nofollow">';
            
            $rating_html .= sprintf(
                /* translators: %s: Number of customer reviews. */
                _n( '(%s customer review)', '(%s customer reviews)', $count, 'sifency-addons' ),
                '<span class="count">' . esc_html( $count ) . '</span>'
            );
            $rating_html .= '</a>';
        }

        $rating_html .= '</div>';

        $this->render_html( $rating_html, false );
    }

    
    /**
     * Renders the final HTML output.
     * @param string|callable $content The content to render. Can be a string or a callable function.
     * @param bool $is_callable True if $content is a function to be called.
     */
    private function render_html( $content, $is_callable = true ) {
        $settings = $this->get_settings_for_display();
        $animation_manager = new Sifency_Animation_Manager($settings);
        $wrapper_classes = ['sifency-product-rating'];
        $wrapper_attrs = $animation_manager->get_wrapper_attributes($wrapper_classes);
        ?>
        <div <?php 
            
            echo wp_kses_post( $wrapper_attrs ); ?>>
            <?php
                if ( $is_callable && is_callable($content) ) {
                    call_user_func($content);
                } else {
                    echo wp_kses_post ($content);
                }
            ?>
        </div>
        <?php
    }
    
    /**
     * Callback function to remove the review link from the rating HTML.
     */
    public function remove_review_link( $html, $rating ) {
        if ($rating > 0) {
            $html = wc_get_rating_html($rating);
        } else {
            $html = '';
        }
        return $html;
    }

    public function render_plain_content() {
        if ( \Elementor\Plugin::$instance->editor->is_edit_mode() ) {
             $this->render_editor_preview();
        }
    }
}