<?php
namespace Banyo\CustomProduct\Block\Product;

use Magento\Catalog\Model\Product;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Registry;
use Magento\Framework\View\Element\Template;
use Magento\Review\Block\Product\ReviewRenderer;

class ReviewTab extends Template
{
    /**
     * @var Registry
     */
    protected $registry;

    /**
     * @var Product
     */
    private $product;

    public function __construct(Template\Context $context,
                                Registry         $registry,
                                array            $data)
    {
        $this->registry = $registry;

        parent::__construct($context, $data);
    }

    /**
     * @return Product
     */
    private function getProduct()
    {
        if (is_null($this->product)) {
            $this->product = $this->registry->registry('product');

            if (!$this->product->getId()) {
                throw new LocalizedException(__('Failed to initialize product'));
            }
        }

        return $this->product;
    }

    public function getProductName()
    {
        return $this->getProduct()->getName();
    }


    public function getReviewRendererBlock()
    {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        return $objectManager->create(\Magento\Review\Block\Product\ReviewRenderer::class);
    }

    public function getaverage()
    {
        $reviewRenderer = $this->getReviewRendererBlock();
        $getRatingSummary = $reviewRenderer->getRatingSummary();

// Convert the percentage to a 5-star scale (out of 5)
        $ratingInStars = $getRatingSummary / 100 * 5;

// Format the rating to one decimal place (e.g., 4.5)
        $formattedRating = number_format($ratingInStars, 1);
return $formattedRating;
//echo $formattedRating;  //formated total rating average

    }

    public function getDynamicTitle()
    {
        $product = $this->getProduct();
        $reviewRenderer = $this->getReviewRendererBlock();

        $ratingHtml = $reviewRenderer->getReviewsSummaryHtml(
            $product,
            \Magento\Review\Block\Product\ReviewRenderer::FULL_VIEW,
            true
        );
        $ratingcount = $reviewRenderer->getReviewsCount();
        $averagerating= $reviewRenderer->getRatingSummary();
        $ratingInStars = $averagerating / 100 * 5;

// Format the rating to one decimal place (e.g., 4.5)
        $formattedRatings = number_format($ratingInStars, 1);
        $formattedRating=$formattedRatings.'/5';

        return __('Reviews' . ' ' . $formattedRating );

    }


    public function getAllStart() {
        $pid=$this->getProduct()->getId();
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $reviewModel = $objectManager->get(\Magento\Review\Model\Review::class);
        $storeManager = $objectManager->get(\Magento\Store\Model\StoreManagerInterface::class);

        $collection = $reviewModel->getCollection()
            ->addFieldToFilter('main_table.status_id', 1)
            ->addEntityFilter('product', $pid)
            ->addStoreFilter($storeManager->getStore()->getId())
            ->addFieldToSelect('review_id');

        $collection->getSelect()->columns('detail.detail_id')->joinInner(
            ['vote' => $collection->getTable('rating_option_vote')],
            'main_table.review_id = vote.review_id',
            ['review_value' => 'vote.value']
        );

        $collection->getSelect()->order('review_value DESC');
        $collection->getSelect()->columns('count(vote.vote_id) as total_vote')->group('review_value');

        // Fetch raw result as array to avoid duplicate key hydration
        $connection = $collection->getConnection();
        $results = $connection->fetchAll($collection->getSelect());

        // Initialize result array
        $arrRatings = [];
        for ($i = 5; $i >= 1; $i--) {
            $arrRatings[$i]['value'] = 0;
        }

        foreach ($results as $_result) {
            $arrRatings[$_result['review_value']]['value'] = $_result['total_vote'];
        }

        return $arrRatings;
    }


}
