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

class IO_Reviews_Widget extends \Elementor\Widget_Base
{

    public function get_name()
    {
        return 'io_reviews_widget';
    }

    public function get_title()
    {
        return __( "InflatableOffice \r\nReviews Widget", 'plugin-name' );
    }

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

    public function get_categories()
    {
        return [ 'general' ];
    }

    protected function _register_controls()
    {

    // Carousel Controls Section
        $this->start_controls_section(
            'carousel_controls_section',
            [
                'label' => __('Carousel Controls', 'plugin-name'),
                'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'slides_to_show',
            [
                'label' => __('Slides to Show', 'plugin-name'),
                'type' => \Elementor\Controls_Manager::NUMBER,
                'default' => 3,
                'min' => 1,
                'max' => 10,
            ]
        );

        $this->add_control(
            'autoplay',
            [
                'label' => __('Autoplay', 'plugin-name'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'plugin-name'),
                'label_off' => __('No', 'plugin-name'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'autoplay_speed',
            [
                'label' => __('Autoplay Speed (seconds)', 'plugin-name'),
                'type' => \Elementor\Controls_Manager::NUMBER,
                'default' => 2,
                'min' => 1,
                'max' => 20,
                'condition' => [
                    'autoplay' => 'yes',
                ],
            ]
        );

        $this->add_control(
            'infinite',
            [
                'label' => __('Infinite Loop', 'plugin-name'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'plugin-name'),
                'label_off' => __('No', 'plugin-name'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'slides_to_scroll',
            [
                'label' => __('Slides to Scroll', 'plugin-name'),
                'type' => \Elementor\Controls_Manager::NUMBER,
                'default' => 1,
                'min' => 1,
                'max' => 10,
            ]
        );

        $this->end_controls_section();

        // Review's Display Section
        $this->start_controls_section(
            'reviews_display_section',
            [
                'label' => __("Review's Display", 'plugin-name'),
                'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'show_all_reviews',
            [
                'label' => __('Show All Available Reviews', 'plugin-name'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'plugin-name'),
                'label_off' => __('No', 'plugin-name'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'number_of_reviews',
            [
                'label' => __('# of Reviews', 'plugin-name'),
                'type' => \Elementor\Controls_Manager::NUMBER,
                'default' => 5,
                'condition' => [
                    'show_all_reviews!' => 'yes',
                ],
            ]
        );

        $this->add_control(
            'show_average_rating',
            [
                'label' => __('Show Reviews Header with Average Rating', 'plugin-name'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'plugin-name'),
                'label_off' => __('No', 'plugin-name'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'show_stars',
            [
                'label' => __('Show Stars on Reviews', 'plugin-name'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'plugin-name'),
                'label_off' => __('No', 'plugin-name'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'show_review_date',
            [
                'label' => __('Show Review Date', 'plugin-name'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'plugin-name'),
                'label_off' => __('No', 'plugin-name'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'show_reviewer_name',
            [
                'label' => __('Show Reviewer Name', 'plugin-name'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'plugin-name'),
                'label_off' => __('No', 'plugin-name'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'show_reviewer_photo',
            [
                'label' => __('Show Reviewer Photo', 'plugin-name'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'plugin-name'),
                'label_off' => __('No', 'plugin-name'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'review_order',
            [
                'label' => __('Review Order', 'plugin-name'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'default' => 'random',
                'options' => [
                    'time' => __('Time', 'plugin-name'),
                    'rating' => __('Rating', 'plugin-name'),
                    'random' => __('Random', 'plugin-name'),
                ],
            ]
        );

        $this->end_controls_section();
    }

    public function get_settings_for_display($args = [])
    {
        // Fetch the settings, but if null, provide defaults
        $settings = parent::get_settings_for_display();
        if (empty($settings)) {
            $settings = array_merge($this->get_default_settings(), $args);
        }
        return $settings;
    }

    public function get_default_settings()
    {
        return [
            'slides_to_show' => 3,
            'autoplay' => 'yes',
            'autoplay_speed' => 2,
            'infinite' => 'yes',
            'slides_to_scroll' => 1,
            'show_all_reviews' => 'yes',
            'number_of_reviews' => 5,
            'show_average_rating' => 'yes',
            'show_stars' => 'yes',
            'show_review_date' => 'yes',
            'show_reviewer_name' => 'yes',
            'show_reviewer_photo' => 'yes',
            'review_order' => 'random',
        ];
    }

    public function render()
    {
        $settings = $this->get_settings_for_display();
        $review_display_type = get_option('io_reviews_widget_type');
        $myplaceID = get_option('io_reviews_myplaceID');

		$is_reviews_page = strpos($_SERVER['REQUEST_URI'], '/reviews') !== false;

    // Fetch and normalize data based on display type
        $iotestimonials = json_decode(get_option('io_reviews_iotestimonials', '[]'), true);
        $google_reviews = json_decode(get_option('io_reviews_google', '[]'), true);

    // Normalize reviews based on the selected widget type
        $normalized_reviews = [];
        if ($review_display_type == 'io_testimonials')
        {
            $normalized_reviews = $this->normalize_reviews($iotestimonials, [], $settings);
        }
        else if ($review_display_type == 'google_reviews')
        {
            $normalized_reviews = $this->normalize_reviews([], $google_reviews, $settings);
        }
        else if ($review_display_type == 'both_reviews')
        {
            $normalized_reviews = $this->normalize_reviews($iotestimonials, $google_reviews, $settings);
        }

    //use stored values, but have fallbacks in case of issues
        $total_google_rating = (float) get_option('io_reviews_google_avg_rating', 0);
        $total_google_reviews = (int) get_option('io_reviews_google_total_reviews', 0);

    //get actual stored review count
        $actual_google_reviews_count = is_array($google_reviews) ? count($google_reviews) : 0;

    //fallback
        if (($total_google_rating <= 0 || !is_numeric($total_google_rating)) && is_array($google_reviews) && !empty($google_reviews))
        {
            $total_google_rating = (float) $this->calculate_average_rating($google_reviews, 'rating');
        }

    //check for discrepancies and fall back to actual count if needed
        if (($total_google_reviews <= 0 || !is_numeric($total_google_reviews)) && is_array($google_reviews))
        {
        //if no stored count, use actual count
            $total_google_reviews = (int) $actual_google_reviews_count;
        }
        elseif ($actual_google_reviews_count > 0)
        {
        //check if stored count is exactly 5 (Places API limitation indicator)
            $is_places_api_limit = ($actual_google_reviews_count == 5);

        //check if there's a discrepancy between stored total and actual stored reviews
            $has_discrepancy = ($total_google_reviews != $actual_google_reviews_count);

        //if NOT the Places API limit (5 reviews) AND there IS a discrepancy, use actual count
            if (!$is_places_api_limit && $has_discrepancy)
            {
                $total_google_reviews = (int) $actual_google_reviews_count;

            //recalculate the average rating from actual stored reviews for consistency
                $total_google_rating = (float) $this->calculate_average_rating($google_reviews, 'rating');
            }
        }

        $total_io_rating = (float) get_option('io_reviews_iotestimonials_filtered_average_rating', 0);
        $total_io_reviews = (int) get_option('io_reviews_iotestimonials_filtered_total_review_count', 0);

    // Display header with Google branding and total star rating?>
        <div class="io-reviews-header">

        <?php if ($settings['show_average_rating'] === 'yes') { ?>

            <div style="display: flex; justify-content: space-around; align-items: flex-start; margin-top: 1.5em; padding-bottom: .75em;">

            <?php if ($review_display_type == 'io_testimonials' || $review_display_type == 'both_reviews')
            {
            // InflatableOffice branding and rating?>
                <div style="display: flex; flex-direction: column; align-items: center; margin-top:.35rem">

                    <div style="display: flex; align-items: center; justify-content: center;">
                        <img src="<?php echo plugins_url('assets/images/io_logo.png', __FILE__); ?>" alt="InflatableOffice Logo" style="aspect-ratio: auto 289/29; margin-right: 0.5em;">
                    </div>

                    <div style="display: flex; align-items: center; justify-content: center; margin-top: 0.5em;">
                        <span style="font-size: 1.25em;"><?php echo esc_html(number_format($total_io_rating, 1)); ?></span>
                        <span style="margin-left: 0.5em;"><?php echo $this->render_stars($total_io_rating); ?></span>
                        <span style="font-size: 1.0em; font-weight: normal; margin-left: 0.5em; color: #888;"><?php echo esc_html($total_io_reviews); ?> reviews</span>
                    </div>

                </div>

            <?php
            }
            if ($review_display_type == 'google_reviews' || $review_display_type == 'both_reviews')
            {
            // Google branding and rating?>
                <div style="display: flex; flex-direction: column; align-items: center; margin-left: 10ch; margin-top:.35rem ">

                    <div style="display: flex; align-items: center; justify-content: center;">
                        <img src="<?php echo plugins_url('assets/images/google_logo.png', __FILE__); ?>" alt="Google Logo" style="width: 8rem; height: 2rem; margin-right: 0.5em; margin-top:.2rem">
                    </div>

                    <div style="display: flex; align-items: center; justify-content: center; margin-top: 0.45em;">
                        <span style="font-size: 1.25em;"><?php echo esc_html(number_format($total_google_rating, 1)); ?></span>
                        <span style="margin-left: 0.5em;"><?php echo $this->render_stars($total_google_rating); ?></span>
                        <span style="font-size: 1.0em; font-weight: normal; margin-left: 0.5em; color: #888;"><?php echo esc_html($total_google_reviews); ?> reviews</span>
                    </div>

                </div>

            <?php }
            if ($myplaceID)
            { ?>
                <div style="display: flex; flex-direction: column; align-items: center; margin-left: 10ch; margin-top: 1.5em;">
                    <a href="https://search.google.com/local/writereview?placeid=<?php echo esc_attr($myplaceID); ?>" target="_blank" style="background-color: #4285F4; color: white; padding: 0.5em 1em; border-radius: 5px; text-decoration: none;">Write a Review</a>
                </div>
            <?php
            } ?>

            </div>

        <?php } ?>

        </div>
        <div style="clear: both;"></div>

        <?php
    	if ($is_reviews_page)
        	$this->render_grid($normalized_reviews, $settings);
    	else
        	$this->render_carousel($normalized_reviews, $settings);
        ?>

        <script>
            function adjustLayoutForOrientation()
            {
                var isPortrait = window.innerHeight > window.innerWidth;
                var header = document.querySelector('.io-reviews-header');

                if (isPortrait)
                {
                    header.style.flexDirection = 'column';
                    header.style.alignItems = 'center';
                }
				else
                {
                    header.style.flexDirection = 'row';
                    header.style.alignItems = 'flex-start';
                }

                adjustCarouselForOrientation();  // Call existing function to adjust carousel
            }

            function adjustCarouselForOrientation()
            {
                var isPortrait = window.innerHeight > window.innerWidth;
                var carouselSettings = {
                    infinite: <?php echo $settings['infinite'] === 'yes' ? 'true' : 'false'; ?>,
                    autoplay: <?php echo $settings['autoplay'] === 'yes' ? 'true' : 'false'; ?>,
                    autoplaySpeed: <?php echo $settings['autoplay_speed'] * 1000; ?>,
                    slidesToScroll: <?php echo $settings['slides_to_scroll']; ?>,
                    slidesToShow: isPortrait ? 1 : <?php echo $settings['slides_to_show']; ?>,
                };

                jQuery('.io-reviews-carousel').slick('unslick'); // Destroy previous instance
                jQuery('.io-reviews-carousel').slick(carouselSettings); // Re-initialize with new settings
            }

            jQuery(document).ready(function()
            {
                adjustLayoutForOrientation();
                jQuery(window).on('resize orientationchange', function()
                {
                    adjustLayoutForOrientation();
                });
            });
        </script>
    <?php
    }

    private function render_carousel($reviews, $settings)
    {
        if (empty($reviews))
        {
            ?>
            <p>No reviews available.</p>
            <?php
            return;
        }

        $autoplay_speed_ms = $settings['autoplay_speed'] * 1000;
        ?>

        <div class="io-reviews-carousel">
            <?php foreach ($reviews as $review) { ?>
                <div class="review">
                    <div class="card io-review-card" style="padding: 1em; margin: 1em; min-height: 16rem; overflow: hidden;">

                        <div class="card-header d-flex align-items-center" style="display: flex; align-items: center; padding: 0.5em 1em;">
                            <?php if ($settings['show_reviewer_photo'] === 'yes') { ?>
                                <?php
                                $profile_photo_html = !empty($review['profile_photo_url'])
                                    ? '<img src="' . esc_url($review['profile_photo_url']) . '" alt="User Photo" style="width: 50px; height: 50px; border-radius: 50%; margin-right: 2em;">'
                                    : $this->generate_placeholder_image($review['author']);
                                echo $profile_photo_html;
                                ?>
                            <?php } ?>
                            <div style="flex-grow: 1;">
                                <?php if ($settings['show_reviewer_name'] === 'yes') { ?>
                                    <h5 class="card-title mb-1" style="font-size: 1.25em; margin: 0;"><?php echo esc_html($review['author']); ?></h5>
                                <?php } ?>
                                <?php if ($settings['show_review_date'] === 'yes') { ?>
                                    <p class="mb-1" style="margin: 0; font-size: 0.9em; color: #666;"><?php echo esc_html($review['date']); ?></p>
                                <?php } ?>
                            </div>
                        </div>

                        <div class="card-body" style="display: flex; flex-direction: column; justify-content: space-between; height: calc(100% - 4rem);">
                            <?php if ($settings['show_stars'] === 'yes') { ?>
                                <p class="mb-1" style="margin: 0; margin-bottom: 1em;"><?php echo $this->render_stars($review['rating']); ?></p>
                            <?php } ?>
                            <p class="card-text" style="height: 8rem; overflow-y: auto; font-size: 1em;"><?php echo esc_html($review['text']); ?></p>

                            <div class="review-branding" style="display: flex; align-items: center; margin-top: .25em;">
                                <?php if ($review['source'] === 'google') { ?>
                                    <img src="<?php echo plugins_url('assets/images/google_g_icon.png', __FILE__); ?>" alt="Google Logo" style="width: 20px; height: 20px; margin-right: 0.5em;">
                                    <span style="font-size: .75em; color: #555; margin-top: .55em;">Posted on Google</span>
                                <?php } else if ($review['source'] === 'iotestimonials') { ?>
                                    <img src="<?php echo plugins_url('assets/images/io_icon.png', __FILE__); ?>" alt="InflatableOffice Logo" style="width: 20px; height: 20px; margin-right: 0.5em;">
                                    <span style="font-size: .75em; color: #555; margin-top: .6em;">Posted on InflatableOffice</span>
                                <?php } ?>
                            </div>

                        </div>

                    </div>
                </div>
            <?php } ?>
        </div>

        <script>
            jQuery(document).ready(function($)
            {
                console.log('Initializing carousel');
                $('.io-reviews-carousel').slick(
                {
                    infinite: <?php echo $settings['infinite'] === 'yes' ? 'true' : 'false'; ?>,
                    slidesToShow: <?php echo $settings['slides_to_show']; ?>,
                    slidesToScroll: <?php echo $settings['slides_to_scroll']; ?>,
                    autoplay: <?php echo $settings['autoplay'] === 'yes' ? 'true' : 'false'; ?>,
                    autoplaySpeed: <?php echo $autoplay_speed_ms; ?>,
                });
            });
        </script>
    <?php
    }

	private function render_grid($reviews, $settings)
    {
    if (empty($reviews)) {
        ?>
        <p>No reviews available.</p>
        <?php
        return;
    }
    ?>

    <div class="io-reviews-grid">
        <?php foreach ($reviews as $review) { ?>
            <div class="review">
                <div class="card io-review-card" style="border: 1px solid #ddd; padding: 1em; min-height: 16rem; overflow: hidden;">
                    <div class="card-header d-flex align-items-center" style="display: flex; align-items: center; padding: 0.5em 1em;">
                        <?php if ($settings['show_reviewer_photo'] === 'yes') { ?>
                            <?php
                            $profile_photo_html = !empty($review['profile_photo_url'])
                                ? '<img src="' . esc_url($review['profile_photo_url']) . '" alt="User Photo" style="width: 50px; height: 50px; border-radius: 50%; margin-right: 2em;">'
                                : $this->generate_placeholder_image($review['author']);
                            echo $profile_photo_html;
                            ?>
                        <?php } ?>
                        <div style="flex-grow: 1;">
                            <?php if ($settings['show_reviewer_name'] === 'yes') { ?>
                                <h5 class="card-title mb-1" style="font-size: 1.25em; margin: 0;"><?php echo esc_html($review['author']); ?></h5>
                            <?php } ?>
                            <?php if ($settings['show_review_date'] === 'yes') { ?>
                                <p class="mb-1" style="margin: 0; font-size: 0.9em; color: #666;"><?php echo esc_html($review['date']); ?></p>
                            <?php } ?>
                        </div>
                    </div>
                    <div class="card-body" style="display: flex; flex-direction: column; justify-content: space-between; height: calc(100% - 4rem);">
                        <?php if ($settings['show_stars'] === 'yes') { ?>
                            <p class="mb-1" style="margin: 0; margin-bottom: 1em;"><?php echo $this->render_stars($review['rating']); ?></p>
                        <?php } ?>
                        <p class="card-text" style="height: 8rem; overflow-y: auto; font-size: 1em;"><?php echo esc_html($review['text']); ?></p>
                        <div class="review-branding" style="display: flex; align-items: center; margin-top: .25em;">
                            <?php if ($review['source'] === 'google') { ?>
                                <img src="<?php echo plugins_url('assets/images/google_g_icon.png', __FILE__); ?>" alt="Google Logo" style="width: 20px; height: 20px; margin-right: 0.5em;">
                                <span style="font-size: .75em; color: #555; margin-top: .55em;">Posted on Google</span>
                            <?php } else if ($review['source'] === 'iotestimonials') { ?>
                                <img src="<?php echo plugins_url('assets/images/io_icon.png', __FILE__); ?>" alt="InflatableOffice Logo" style="width: 20px; height: 20px; margin-right: 0.5em;">
                                <span style="font-size: .75em; color: #555; margin-top: .6em;">Posted on InflatableOffice</span>
                            <?php } ?>
                        </div>
                    </div>
                </div>
            </div>
        <?php } ?>
    </div>
    <?php
}

    private function normalize_reviews($iotestimonials, $google_reviews, $settings)
    {
    // Apply filters to the testimonials
		$ratingFilter = (int) get_option( 'io_reviews_iotestimonials_star_filterlevel', 0 );
		$timeFilterTimestamp = $this->get_time_filter_timestamp( get_option( 'io_reviews_iotestimonials_time_filter', 'all' ) );

		$filteredTestimonials = array_filter( $iotestimonials, function( $t ) use ( $ratingFilter, $timeFilterTimestamp )
		{
			if ( ! isset( $t['testimonial_rating'] ) || (int) $t['testimonial_rating'] < $ratingFilter ) return false;

			$rawTime = $t['testimonial_time'] ?? '';

			if ( is_numeric( $rawTime ) ) $created = (int) $rawTime;
			else
			{
				$created = strtotime( $rawTime );
				if ( $created === false ) return false;
			}
			if ( $created < $timeFilterTimestamp ) return false;
			return true;
        });

    // Calculate and store the average rating and total count for IO Testimonials
        $iotestimonials_total_rating = $this->calculate_average_rating($filteredTestimonials, 'testimonial_rating');
        $iotestimonials_total_count = count($filteredTestimonials);
        update_option('io_reviews_iotestimonials_filtered_average_rating', $iotestimonials_total_rating);
        update_option('io_reviews_iotestimonials_filtered_total_review_count', $iotestimonials_total_count);

    // Apply filters to the Google reviews
        $googleRatingFilter = get_option('io_reviews_google_star_filterlevel', 0);
        $googleTimeFilter = get_option('io_reviews_google_time_filter', 'all');
        $googleTimeFilterTimestamp = $this->get_time_filter_timestamp($googleTimeFilter);
        $filteredGoogleReviews = array_filter($google_reviews, function($review) use ($googleRatingFilter, $googleTimeFilterTimestamp)
        {
            return $review['rating'] >= $googleRatingFilter &&
                   $review['time'] >= $googleTimeFilterTimestamp;
        });

    // Combine and normalize the reviews
        $normalized_reviews = [];

        foreach ($filteredTestimonials as $testimonial)
        {
            $testimonial_time = $testimonial['testimonial_time'];

            if (is_numeric($testimonial_time))
            {
                $timestamp = (int)$testimonial_time;
            }
            else
            {
                $timestamp = strtotime($testimonial_time);
                if ($timestamp === false)
                {
                    // Handle the error, e.g., skip this testimonial or set to current time
                    $timestamp = time(); // Or any default you prefer
                }
        }

    $normalized_reviews[] = [
        'author' => $testimonial['testimonial_name'],
        'text' => $testimonial['testimonial_description'],
        'rating' => $testimonial['testimonial_rating'],
        'profile_photo_url' => '',
        'date' => date('F j, Y', $timestamp),
        'source' => 'iotestimonials'
    ];
}


        foreach ($filteredGoogleReviews as $review)
        {
            $normalized_reviews[] =
            [
                'author' => $review['author_name'],
                'text' => $review['text'],
                'rating' => $review['rating'],
                'profile_photo_url' => $review['profile_photo_url'], // Real image for Google reviews
                'date' => date('F j, Y', $review['time']), // Convert timestamp to readable date
                'source' => 'google' // Add the source information
            ];
        }

    // Order reviews based on selected setting
        if ($settings['review_order'] === 'rating')
        {
            usort($normalized_reviews, function ($a, $b)
            {
                return $b['rating'] - $a['rating'];
            });
        }
        elseif ($settings['review_order'] === 'time')
        {
            usort($normalized_reviews, function ($a, $b)
            {
                return strtotime($b['date']) - strtotime($a['date']);
            });
        }
        else
        {
        // Randomize the order of the reviews
            shuffle($normalized_reviews);
        }

    // Limit the number of reviews if "Show All" is not selected
        if (($settings['show_all_reviews'] ?? 'yes') !== 'yes')
        {
        // Coerce number_of_reviews to an integer and guard against invalid values
            if (isset($settings['number_of_reviews']) && is_numeric($settings['number_of_reviews']))
            {
                $limit = (int) $settings['number_of_reviews'];
            }
            else
            {
                $defaultSettings = $this->get_default_settings();
                $limit = (int) ($defaultSettings['number_of_reviews'] ?? 5);
            }
            if ($limit < 0) { $limit = 0; }

            $normalized_reviews = array_slice($normalized_reviews, 0, $limit);
        }

        return $normalized_reviews;
    }

    private function generate_placeholder_image($author)
    {
    // Ensure the author is not empty
        if (empty($author))
        {
            echo '<script>console.log("Author is empty, unable to generate initial.");</script>';
            return ''; // Early return to avoid processing an empty author
        }

    // Get the first initial of the author
        $initial = strtoupper(substr($author, 0, 1));

    // Generate a random color
        $colors = ['#4285f4', '#ea4335', '#fbbc05', '#34a853', '#ff6f61', '#6f42c1', '#17a2b8'];
        $color = $colors[array_rand($colors)];

    // Return the inline SVG as HTML with exact margin, font size, and positioning
        return '<svg width="50" height="50" viewBox="0 0 50 50" style="margin-right: 1.5em;">'
            . '<circle cx="25" cy="25" r="24" fill="' . $color . '"/>'
            . '<text x="50%" y="50%" text-anchor="middle" fill="white" dy=".35em" font-size="22" font-family="Arial">'
            . $initial
            . '</text></svg>';
    }

    private function calculate_average_rating($reviews, $rating_key = 'rating')
    {
        if (empty($reviews)) return 0;

        $total_rating = array_sum(array_column($reviews, $rating_key));
        return $total_rating / count($reviews);
    }

    private function get_time_filter_timestamp($timeFilter)
    {
        $timeFilterTimestamps =
        [
            '6_months' => strtotime('-6 months'),
            '1_year' => strtotime('-1 year'),
            '3_years' => strtotime('-3 years'),
            'all' => 0
        ];

		return $timeFilterTimestamps[ $timeFilter ] ?? 0;
    }

    private function render_stars($rating)
    {
        $output = '';
        for ($i = 0; $i < 5; $i++)
        {
            if ($i < $rating)
            {
                $output .= '<span class="dashicons dashicons-star-filled" style="color: gold;"></span>';
            }
            else
            {
                $output .= '<span class="dashicons dashicons-star-empty" style="color: gold;"></span>';
            }
        }
        return $output;
    }
}

// Register the widget
\Elementor\Plugin::instance()->widgets_manager->register_widget_type( new \IO_Reviews_Widget() );