<?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;

class Reviews implements ProductDataInterface
{

    /**
     * @var \Magento\Review\Model\Review
     */
    protected $reviewFactory;

    public function __construct(
        \Magento\Review\Model\ReviewFactory $reviewFactory
    ) {
        $this->reviewFactory = $reviewFactory;
    }

    /**
     * inherit
     */
    public function getData($product)
    {
        $reviews = [];
        $collection =  $this->reviewFactory->create()->getResourceCollection()->addStoreFilter($product->getStoreId())
        ->addEntityFilter("product", $product->getId())
        ->addStatusFilter(
            \Magento\Review\Model\Review::STATUS_APPROVED
        )
        ->setDateOrder()->addRateVotes();
        if ($collection->getSize() > 0) {
            $allRatings = [];
            foreach ($collection as $review) {
                $votes = $review->getRatingVotes();
                $voteAverage = 0;
                if (count($votes)) {
                    foreach ($votes as $vote) {
                        $voteAverage += $vote->getValue();
                    }
                    $allRatings[$review->getId()]['reviewRating']['ratingValue'] = $voteAverage/count($votes);
                } else {
                    continue;
                }
                $allRatings[$review->getId()]['@type'] = "review";
                $allRatings[$review->getId()]['author'] = strip_tags("my customer".$review->getCustomerId());
                $allRatings[$review->getId()]['datePublished'] = $review->getCreatedAt();
                $allRatings[$review->getId()]['description'] = strip_tags($review->getDetail());
                $allRatings[$review->getId()]['name'] = strip_tags($review->getTitle());
                $allRatings[$review->getId()]['reviewRating']['@type'] = "Rating";
                $allRatings[$review->getId()]['reviewRating']['bestRating'] = 5;
                $allRatings[$review->getId()]['reviewRating']['worstRating'] = 1;
            }
            $reviews = array_values($allRatings);
        }
        return $reviews;
    }
}
