<?php
/**
 * Webkul Software.
 *
 * @category Webkul
 *
 * @author    Webkul
 * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */

 namespace Webkul\AdvanceSeoManager\Model\RichSnippet\Context\Product;

use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Store\Api\Data\StoreInterface;
use Magento\Review\Model\ReviewFactory;
use Magento\Store\Model\StoreManager;

class AggregateRating implements ProductDataInterface
{

    private $reviewFactory;
    private $productRepository;
    private $storeManager;
    private $productReviewFactory;
    public function __construct(
        ReviewFactory $reviewFactory,
        ProductRepositoryInterface $productRepository,
        StoreManager $storeManager
    ) {
        $this->reviewFactory = $reviewFactory;
        $this->productRepository = $productRepository;
        $this->storeManager = $storeManager;
    }

    /**
     * inherit
     */
    public function getData($product)
    {
        $aggregateRating = [];
        $data = $this->getAggregateRating($product);
        if ($data['RatingsCount'] > 0 && $data['AverageRatingReview']) {
            $aggregateRating = [
                "@type" => "AggregateRating",
                "ratingValue" => $data['AverageRatingReview'],
                "reviewCount" => $data['RatingsCount']
            ];
        }
        return $aggregateRating;
    }

    private function getAggregateRating($product)
    {
        $store = $this->storeManager->getStore();
        $product = $this->productRepository->get($product->getSku());
        $reviewsPerStore = [];
        
        /**
         * @var int $storeId
         * @var StoreInterface $store
         */
        $this->reviewFactory->create()->getEntitySummary($product, $store->getId());
        $averageReviewRating = (float)$product->getRatingSummary()->getRatingSummary();
        $ratingsCount = $product->getRatingSummary()->getReviewsCount();
        $averageReviewRating = ($averageReviewRating/100)*5;
        $reviewsPerStore['storeId'] = $store->getId();
        $reviewsPerStore['StoreCode']= $store->getCode();
        $reviewsPerStore['AverageRatingReview'] = $averageReviewRating;
        $reviewsPerStore['RatingsCount'] = $ratingsCount;
        
        return $reviewsPerStore;
    }
}
