<?php

namespace Unlockafe_Addons\Widgets;

use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Group_Control_Background;
use Elementor\Repeater;
use Elementor\Utils;

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

/**
 * Elementor Customer Review Widget.
 *
 * @since 1.1.2
 */

class Customer_Review extends Widget_Base
{
    public function get_name()
    {
        return 'unlockafe-customer-review';
    }

    public function get_title()
    {
        return esc_html__('Customer Review', 'unlock-addons-for-elementor');
    }

    public function get_icon()
    {
        return 'eicon-testimonial-carousel ulicon';
    }

    public function get_categories()
    {
        return ['unlockafe-addons'];
    }

    public function get_keywords()
    {
        return ['customer review', 'testimonial', 'rating', 'woocommerce', 'product', 'unlockafe'];
    }

    public function get_style_depends()
    {
        return ['unlockafe-customer-review-style', 'swiper'];
    }

    public function get_script_depends()
    {
        return ['unlockafe-customer-review-scripts'];
    }
    private function generate_stars_html($rating)
    {
        $stars_html = '';
        $full_stars = floor($rating);
        $half_star = ($rating - $full_stars) >= 0.5;
        $empty_stars = 5 - $full_stars - ($half_star ? 1 : 0);

        for ($i = 0; $i < $full_stars; $i++) {
            $stars_html .= '<i class="fa fa-star"></i>';
        }
        if ($half_star) {
            $stars_html .= '<i class="fa fa-star-half-o"></i>';
        }
        for ($i = 0; $i < $empty_stars; $i++) {
            $stars_html .= '<i class="fa fa-star-o"></i>';
        }
        return $stars_html;
    }

    protected function register_controls()
    {
        //======================================================================
        // Design Layout & Data Source Panel
        //======================================================================
        $this->start_controls_section(
            'uafe_review_layout_section',
            [
                'label' => esc_html__('Layout & Data Source', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'uafe_review_layout',
            [
                'label' => esc_html__('Select Layout', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'options' => [
                    'layout-1' => esc_html__('Layout 1 (Detailed Summary)', 'unlock-addons-for-elementor'),
                    'layout-2' => esc_html__('Layout 2 (Modern Grid)', 'unlock-addons-for-elementor'),
                    'layout-3' => esc_html__('Layout 3 (3D Grid)', 'unlock-addons-for-elementor'),
                    'layout-4' => esc_html__('Layout 4 (Clean Carousel)', 'unlock-addons-for-elementor'),
                    'layout-5' => esc_html__('Layout 5 (Coverflow Carousel)', 'unlock-addons-for-elementor'),
                ],
                'default' => 'layout-1',
            ]
        );

        $this->add_control(
            'uafe_data_source',
            [
                'label' => esc_html__('Data Source', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'default' => 'manual',
                'options' => [
                    'manual' => esc_html__('Manual Entry', 'unlock-addons-for-elementor'),
                    'woocommerce' => esc_html__('WooCommerce Product', 'unlock-addons-for-elementor'),
                ],
                'separator' => 'before',
            ]
        );

        $this->add_control(
            'uafe_wc_product_id',
            [
                'label' => esc_html__('Select Product', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT2,
                'label_block' => true,
                'options' => $this->get_woocommerce_products(),
                'condition' => [
                    'uafe_data_source' => 'woocommerce',
                ],
            ]
        );


        $this->end_controls_section();
        
        //======================================================================
        // Overall Summary Panel (For Layout 1 - Manual)
        //======================================================================
        $this->start_controls_section(
            'uafe_overall_summary_section',
            [
                'label' => __('Overall Summary (Manual)', 'unlock-addons-for-elementor'),
                'condition' => [
                    'uafe_review_layout' => 'layout-1',
                    'uafe_data_source' => 'manual',
                ]
            ]
        );

        $this->add_control(
            'uafe_overall_rating_value',
            [
                'label' => esc_html__('Overall Rating Value', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::NUMBER,
                'min' => 0, 'max' => 5, 'step' => 0.1, 'default' => 4.8,
            ]
        );
        $this->add_control(
            'uafe_total_review_count',
            [
                'label' => esc_html__('Total Review Count Text', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'default' => esc_html__('Based on 128 reviews', 'unlock-addons-for-elementor'),
            ]
        );
        $repeater_bars = new Repeater();
        $repeater_bars->add_control( 'bar_label', [ 'label' => esc_html__('Label', 'unlock-addons-for-elementor'), 'type' => Controls_Manager::TEXT, 'default' => esc_html__('5 Stars' , 'unlock-addons-for-elementor'),]);
        $repeater_bars->add_control( 'bar_percentage', [ 'label' => esc_html__('Percentage', 'unlock-addons-for-elementor'), 'type' => Controls_Manager::SLIDER, 'default' => [ 'unit' => '%', 'size' => 85 ], 'size_units' => [ '%' ], 'range' => [ '%' => [ 'min' => 0, 'max' => 100 ] ],]);
        $repeater_bars->add_control( 'bar_count', [ 'label' => esc_html__('Count', 'unlock-addons-for-elementor'), 'type' => Controls_Manager::NUMBER, 'default' => 95,]);
        $this->add_control(
            'uafe_rating_bars',
            [
                'label' => esc_html__('Rating Breakdown Bars', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::REPEATER,
                'fields' => $repeater_bars->get_controls(),
                'default' => [
                    [ 'bar_label' => '5 <i class="fa fa-star"></i>', 'bar_percentage' => ['size' => 85, 'unit' => '%'], 'bar_count' => 95 ],
                    [ 'bar_label' => '4 <i class="fa fa-star"></i>', 'bar_percentage' => ['size' => 12, 'unit' => '%'], 'bar_count' => 25 ],
                    [ 'bar_label' => '3 <i class="fa fa-star"></i>', 'bar_percentage' => ['size' => 2, 'unit' => '%'], 'bar_count' => 5 ],
                    [ 'bar_label' => '2 <i class="fa fa-star"></i>', 'bar_percentage' => ['size' => 0, 'unit' => '%'], 'bar_count' => 0 ],
                    [ 'bar_label' => '1 <i class="fa fa-star"></i>', 'bar_percentage' => ['size' => 1, 'unit' => '%'], 'bar_count' => 3 ],
                ],
                'title_field' => '{{{ bar_label }}}',
            ]
        );
        
        $this->end_controls_section();

        //======================================================================
        // Review Items Panel (Manual)
        //======================================================================
        $this->start_controls_section(
            'uafe_review_items_section',
            [
                'label' => __('Review Items (Manual)', 'unlock-addons-for-elementor'),
                'condition' => [
                    'uafe_data_source' => 'manual',
                ]
            ]
        );
        
        $repeater = new Repeater();
        $repeater->add_control( 'uafe_reviewer_avatar', [ 'label' => esc_html__('Avatar', 'unlock-addons-for-elementor'), 'type' => Controls_Manager::MEDIA, 'default' => [ 'url' => Utils::get_placeholder_image_src() ], ]);
        $repeater->add_control( 'uafe_reviewer_name', [ 'label' => esc_html__('Name', 'unlock-addons-for-elementor'), 'type' => Controls_Manager::TEXT, 'default' => esc_html__('Jane D.', 'unlock-addons-for-elementor'),]);
        $repeater->add_control( 'uafe_review_rating', [ 'label' => esc_html__('Rating (1-5)', 'unlock-addons-for-elementor'), 'type' => Controls_Manager::NUMBER, 'min' => 1, 'max' => 5, 'step' => 0.5, 'default' => 5,]);
        $repeater->add_control( 'uafe_review_title', [ 'label' => esc_html__('Review Title', 'unlock-addons-for-elementor'), 'type' => Controls_Manager::TEXT, 'default' => esc_html__('Absolutely exceeded my expectations!', 'unlock-addons-for-elementor'),]);
        $repeater->add_control( 'uafe_review_content', [ 'label' => esc_html__('Review Content', 'unlock-addons-for-elementor'), 'type' => Controls_Manager::TEXTAREA, 'default' => esc_html__('The quality is fantastic.', 'unlock-addons-for-elementor'),]);
        $repeater->add_control( 'uafe_review_date', [ 'label' => esc_html__('Review Date', 'unlock-addons-for-elementor'), 'type' => Controls_Manager::TEXT, 'default' => esc_html__('Aug 14, 2025', 'unlock-addons-for-elementor'), 'condition' => [ 'uafe_review_layout' => 'layout-1' ],]);
        $repeater->add_control( 'uafe_is_verified', [ 'label' => esc_html__('Verified Purchase?', 'unlock-addons-for-elementor'), 'type' => Controls_Manager::SWITCHER, 'default' => 'yes', 'condition' => [ 'uafe_review_layout' => ['layout-1', 'layout-2'] ],]);
        $repeater->add_control( 'uafe_reviewer_location', [ 'label' => esc_html__('Location', 'unlock-addons-for-elementor'), 'type' => Controls_Manager::TEXT, 'default' => esc_html__('Canada', 'unlock-addons-for-elementor'), 'condition' => [ 'uafe_review_layout' => 'layout-3' ],]);
        $repeater->add_control( 'uafe_is_highlighted', [ 'label' => esc_html__('Highlight this card?', 'unlock-addons-for-elementor'), 'type' => Controls_Manager::SWITCHER, 'condition' => [ 'uafe_review_layout' => 'layout-3' ],]);
        $this->add_control( 'uafe_review_items', [ 'label' => esc_html__('Review List', 'unlock-addons-for-elementor'), 'type' => Controls_Manager::REPEATER, 'fields' => $repeater->get_controls(), 'default' => [ [ 'uafe_reviewer_name' => 'Jane D.', 'uafe_review_rating' => 5 ], [ 'uafe_reviewer_name' => 'Mark S.', 'uafe_review_rating' => 4 ], ], 'title_field' => '{{{ uafe_reviewer_name }}} - ★{{{ uafe_review_rating }}}',]);
        $this->end_controls_section();
        
        //======================================================================
        // Slider Settings Panel (For Layouts 4 & 5)
        //======================================================================
        $this->start_controls_section( 'uafe_slider_settings_section', [ 'label' => __('Slider Settings', 'unlock-addons-for-elementor'), 'condition' => [ 'uafe_review_layout' => ['layout-4', 'layout-5']]]);
        $this->add_control( 'uafe_slider_loop', [ 'label' => esc_html__('Loop', 'unlock-addons-for-elementor'), 'type' => Controls_Manager::SWITCHER, 'default' => 'yes',]);
        $this->add_control( 'uafe_slider_autoplay', [ 'label' => esc_html__('Autoplay', 'unlock-addons-for-elementor'), 'type' => Controls_Manager::SWITCHER, 'default' => 'yes',]);
        $this->add_control( 'uafe_slider_delay', [ 'label' => esc_html__('Autoplay Delay (ms)', 'unlock-addons-for-elementor'), 'type' => Controls_Manager::NUMBER, 'default' => 4000, 'condition' => [ 'uafe_slider_autoplay' => 'yes' ],]);
        $this->end_controls_section();
    }
    
    private function get_woocommerce_products() {
        if (!class_exists('WooCommerce')) { return []; }
        $products = wc_get_products(['limit' => -1]);
        $options = [];
        foreach ($products as $product) { $options[$product->get_id()] = $product->get_name(); }
        return $options;
    }

    // Main Render Function
    protected function render()
    {
        $settings = $this->get_settings_for_display();
        $layout = $settings['uafe_review_layout'];

        $reviews_data = [];
        $summary_data = [];

        if ($settings['uafe_data_source'] === 'woocommerce') {
            // --- WOOCOMMERCE DATA LOGIC ---
            if (!class_exists('WooCommerce')) {
                echo '<div class="elementor-alert elementor-alert-warning">' . esc_html__('WooCommerce is not installed or active.', 'unlock-addons-for-elementor') . '</div>';
                return;
            }

            $product_id = $settings['uafe_wc_product_id'];
            if (empty($product_id)) {
                echo '<div class="elementor-alert elementor-alert-info">' . esc_html__('Please select a product from the widget settings.', 'unlock-addons-for-elementor') . '</div>';
                return;
            }

            $product = wc_get_product($product_id);
            if (!$product) {
                echo '<div class="elementor-alert elementor-alert-danger">' . esc_html__('Product not found.', 'unlock-addons-for-elementor') . '</div>';
                return;
            }

            $comments = get_comments(['post_id' => $product_id, 'status'  => 'approve', 'type'    => 'review']);

            foreach ($comments as $comment) {
                $rating = get_comment_meta($comment->comment_ID, 'rating', true);
                $reviews_data[] = [
                    'uafe_reviewer_avatar' => ['url' => get_avatar_url($comment->comment_author_email)],
                    'uafe_reviewer_name' => $comment->comment_author,
                    'uafe_review_rating' => $rating,
                    'uafe_review_title' => '',
                    'uafe_review_content' => $comment->comment_content,
                    'uafe_review_date' => get_comment_date('M j, Y', $comment),
                    'uafe_is_verified' => wc_review_is_from_verified_owner($comment->comment_ID) ? 'yes' : 'no',
                    'uafe_reviewer_location' => '',
                    'uafe_is_highlighted' => 'no',
                ];
            }

            $summary_data['overall_rating'] = $product->get_average_rating();
            $summary_data['total_reviews_text'] = sprintf(_n('Based on %s review', 'Based on %s reviews', $product->get_review_count(), 'unlock-addons-for-elementor'), $product->get_review_count());
            $rating_counts = $product->get_rating_counts();
            for ($i = 5; $i >= 1; $i--) {
                $count = isset($rating_counts[$i]) ? $rating_counts[$i] : 0;
                $percentage = ($product->get_review_count() > 0) ? ($count / $product->get_review_count()) * 100 : 0;
                $summary_data['bars'][] = [
                    'bar_label' => $i . ' <i class="fa fa-star"></i>',
                    'bar_percentage' => ['size' => $percentage],
                    'bar_count' => $count,
                ];
            }
        } else {
            // --- MANUAL DATA LOGIC ---
            $reviews_data = $settings['uafe_review_items'];
            $summary_data['overall_rating'] = $settings['uafe_overall_rating_value'];
            $summary_data['total_reviews_text'] = $settings['uafe_total_review_count'];
            $summary_data['bars'] = $settings['uafe_rating_bars'];
        }

        ?>
        <div class="uafe-review-widget-wrapper">
            <?php if (empty($reviews_data) && $settings['uafe_data_source'] === 'woocommerce'): ?>
                 <div class="elementor-alert elementor-alert-info"><?php esc_html_e('This product has no reviews yet.', 'unlock-addons-for-elementor'); ?></div>
            <?php return; endif; ?>
        
            <?php // ----- LAYOUT 1 ----- ?>
            <?php if ($layout === 'layout-1') : ?>
                <section id="layout1" class="section-container">
                    <div class="container">
                        <div class="review-summary-card">
                            <div class="overall-rating-box">
                                <p class="rating-value"><?php echo esc_html(number_format($summary_data['overall_rating'], 1)); ?></p>
                                <div class="stars"><?php echo $this->generate_stars_html($summary_data['overall_rating']); ?></div>
                                <p class="review-count"><?php echo esc_html($summary_data['total_reviews_text']); ?></p>
                            </div>
                            <div class="rating-histogram">
                                <?php foreach ($summary_data['bars'] as $bar) : ?>
                                    <div class="rating-bar-row">
                                        <span class="rating-bar-label"><?php echo $bar['bar_label']; ?></span>
                                        <div class="rating-bar-track">
                                            <div class="rating-bar-fill" style="width: <?php echo esc_attr($bar['bar_percentage']['size']); ?>%;"></div>
                                        </div>
                                        <span class="rating-bar-count"><?php echo esc_html($bar['bar_count']); ?></span>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <div class="reviews-list">
                            <?php foreach ($reviews_data as $item) : ?>
                                <div class="individual-review-card">
                                    <div class="review-header">
                                        <img src="<?php echo esc_url($item['uafe_reviewer_avatar']['url']); ?>" alt="Reviewer Avatar">
                                        <div class="review-meta">
                                            <div class="meta-top">
                                                <div>
                                                    <div class="reviewer-name"><?php echo esc_html($item['uafe_reviewer_name']); ?></div>
                                                    <?php if (!empty($item['uafe_is_verified']) && $item['uafe_is_verified'] === 'yes') : ?>
                                                        <span class="verified-badge"><i class="fa fa-check-circle"></i> <?php esc_html_e('Verified Purchase', 'unlock-addons-for-elementor'); ?></span>
                                                    <?php endif; ?>
                                                </div>
                                                <span class="review-date"><?php echo esc_html($item['uafe_review_date']); ?></span>
                                            </div>
                                            <div class="review-content">
                                                <div class="stars"><?php echo $this->generate_stars_html($item['uafe_review_rating']); ?></div>
                                                <?php if (!empty($item['uafe_review_title'])): ?>
                                                    <h5><?php echo esc_html($item['uafe_review_title']); ?></h5>
                                                <?php endif; ?>
                                                <p><?php echo wp_kses_post($item['uafe_review_content']); ?></p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </section>
            
            <?php // ----- LAYOUT 2 ----- ?>
            <?php elseif ($layout === 'layout-2') : ?>
                <section id="layout2" class="section-container">
                    <div class="container">
                        <div class="reviews-grid">
                            <?php foreach ($reviews_data as $item) : ?>
                                <div class="review-card">
                                    <div class="review-header">
                                        <img src="<?php echo esc_url($item['uafe_reviewer_avatar']['url']); ?>" alt="Reviewer">
                                        <div class="reviewer-info">
                                            <div class="name"><?php echo esc_html($item['uafe_reviewer_name']); ?></div>
                                            <?php if (!empty($item['uafe_is_verified']) && $item['uafe_is_verified'] === 'yes') : ?>
                                                <div class="verified"><i class="fa fa-check-circle"></i> <?php esc_html_e('Verified Purchase', 'unlock-addons-for-elementor'); ?></div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    <div class="stars"><?php echo $this->generate_stars_html($item['uafe_review_rating']); ?></div>
                                    <?php if (!empty($item['uafe_review_title'])): ?>
                                        <h3 class="review-title"><?php echo esc_html($item['uafe_review_title']); ?></h3>
                                    <?php endif; ?>
                                    <p class="review-body"><?php echo wp_kses_post($item['uafe_review_content']); ?></p>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </section>

            <?php // ----- LAYOUT 3 ----- ?>
            <?php elseif ($layout === 'layout-3') : ?>
                <section id="layout3" class="section-container">
                    <div class="container">
                        <div class="reviews-grid">
                            <?php foreach ($reviews_data as $item) : 
                                $card_class = 'review-card';
                                if (!empty($item['uafe_is_highlighted']) && $item['uafe_is_highlighted'] === 'yes') {
                                    $card_class .= ' highlight-card';
                                }
                            ?>
                                <div class="review-card-container">
                                    <div class="<?php echo esc_attr($card_class); ?>">
                                        <div class="review-card-avatar"><img src="<?php echo esc_url($item['uafe_reviewer_avatar']['url']); ?>" alt="Reviewer"></div>
                                        <h3 class="name"><?php echo esc_html($item['uafe_reviewer_name']); ?></h3>
                                        <?php if (!empty($item['uafe_reviewer_location'])): ?>
                                            <p class="location"><?php echo esc_html($item['uafe_reviewer_location']); ?></p>
                                        <?php endif; ?>
                                        <div class="stars"><?php echo $this->generate_stars_html($item['uafe_review_rating']); ?></div>
                                        <p class="review-content"><?php echo wp_kses_post($item['uafe_review_content']); ?></p>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </section>
                
            <?php // ----- LAYOUT 4 ----- ?>
            <?php elseif ($layout === 'layout-4') : 
                $swiper_options = [
                    'loop' => ($settings['uafe_slider_loop'] === 'yes'),
                    'autoplay' => ($settings['uafe_slider_autoplay'] === 'yes') ? ['delay' => (int)$settings['uafe_slider_delay']] : false,
                ];
            ?>
                <section id="layout4" class="section-container">
                    <div class="container">
                        <div class="swiper-container" data-swiper-options='<?php echo json_encode($swiper_options); ?>'>
                            <div class="swiper-wrapper">
                                <?php foreach ($reviews_data as $item) : ?>
                                    <div class="swiper-slide">
                                        <div class="testimonial-card">
                                            <i class="fa fa-quote-right testimonial-quote"></i>
                                            <img src="<?php echo esc_url($item['uafe_reviewer_avatar']['url']); ?>" alt="Avatar" class="testimonial-avatar">
                                            <h3 class="testimonial-name"><?php echo esc_html($item['uafe_reviewer_name']); ?></h3>
                                            <div class="testimonial-stars"><?php echo $this->generate_stars_html($item['uafe_review_rating']); ?></div>
                                            <p class="testimonial-review">"<?php echo wp_kses_post($item['uafe_review_content']); ?>"</p>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            <div class="swiper-pagination"></div>
                        </div>
                    </div>
                </section>

            <?php // ----- LAYOUT 5 ----- ?>
            <?php elseif ($layout === 'layout-5') : 
                $swiper_options = [
                    'loop' => ($settings['uafe_slider_loop'] === 'yes'),
                    'autoplay' => ($settings['uafe_slider_autoplay'] === 'yes') ? ['delay' => (int)$settings['uafe_slider_delay']] : false,
                ];
            ?>
                <section id="layout5" class="section-container">
                    <div class="container">
                         <div class="swiper-container" data-swiper-options='<?php echo json_encode($swiper_options); ?>'>
                            <div class="swiper-wrapper">
                                <?php foreach ($reviews_data as $item) : ?>
                                <div class="swiper-slide">
                                    <div class="ImgHolder">
                                        <img src="<?php echo esc_url($item['uafe_reviewer_avatar']['url']); ?>" alt="Avatar">
                                    </div>
                                    <div class="ContentHolder">
                                        <h3><?php echo esc_html($item['uafe_reviewer_name']); ?></h3>
                                        <div class="stars"><?php echo $this->generate_stars_html($item['uafe_review_rating']); ?></div>
                                        <p class="review-body"><?php echo wp_kses_post($item['uafe_review_content']); ?></p>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            <div class="swiper-pagination"></div>
                        </div>
                    </div>
                </section>
            <?php endif; ?>
        </div>
    <?php
    }
}