<?php
/**
 * Webkul Software.
 * 
 * PHP version 7.0+
 *
 * @category  Webkul
 * @package   Webkul_MobikulGraphQL
 * @author    Webkul <support@webkul.com>
 * @copyright 2010-2019 Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html ASL Licence
 * @link      https://store.webkul.com/license.html
 */

declare(strict_types=1);
namespace Webkul\MobikulGraphQL\Model\Resolver;

class ReviewData implements \Magento\Framework\GraphQl\Query\ResolverInterface
{

    protected $vote;
    protected $helper;
    protected $review;
    protected $storeManager;
    protected $helperCatalog;
    protected $productFactory;

    public function __construct(
        \Magento\Review\Model\Review $review,
        \Webkul\MobikulGraphQL\Helper\Data $helper,
        \Magento\Review\Model\Rating\Option\Vote $vote,
        \Webkul\MobikulCore\Helper\Catalog $helperCatalog,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        \Magento\Store\Model\StoreManagerInterface $storeManager
    ) {
        $this->vote = $vote;
        $this->review = $review;
        $this->helper = $helper;
        $this->storeManager = $storeManager;
        $this->helperCatalog = $helperCatalog;
        $this->productFactory = $productFactory;
    }

    /**
     * @inheritdoc
     */
    public function resolve(
        \Magento\Framework\GraphQl\Config\Element\Field $field,
        $context,
        \Magento\Framework\GraphQl\Schema\Type\ResolveInfo $info,
        array $value = null,
        array $args = null
    ) {
        $returnArray = [];
        $token = $args["token"] ?? "";
        $reviewId = $args["reviewId"] ?? 0;
        $storeId = $this->storeManager->getStore()->getId();
        $customer = $this->helper->getCustomerByToken($token);
        $review = $this->review->load($reviewId);
        if ($review->getCustomerId() != $customer->getId()) {
            // $this->returnArray["message"] = __("Invalid review.");
            // return $this->getJsonResponse($this->returnArray);
        }
        $product = $this->productFactory->create()
            ->setStoreId($storeId)
            ->load($review->getEntityPkValue());
        $returnArray["thumbNail"] = $this->helperCatalog->getImageUrl($product, 1000/3);
        $returnArray["productId"] = (int)$product->getId();
        $returnArray["productName"] = html_entity_decode($this->helperCatalog->stripTags($product->getName()));
        $returnArray["reviewDate"] = $this->helperCatalog->formatDate($review->getCreatedAt(), "long");
        $returnArray["reviewTitle"] = html_entity_decode($this->helperCatalog->stripTags($review->getTitle()));
        $returnArray["reviewDetail"] = html_entity_decode($this->helperCatalog->stripTags($review->getDetail()));
        $ratingCollection = $this->vote
            ->getResourceCollection()
            ->setReviewFilter($reviewId)
            ->addRatingInfo($storeId)
            ->setStoreFilter($storeId)
            ->load();
        $average = 0.0;
        foreach ($ratingCollection as $rating) {
            $average += (double)number_format((float)$rating->getPercent(), 2, ".", "");
        }
        $returnArray["givenRating"] = $average/count($average);
        $reviews = $this->review
            ->getResourceCollection()
            ->addStoreFilter($storeId)
            ->addEntityFilter("product", $product->getId())
            ->addStatusFilter(\Magento\Review\Model\Review::STATUS_APPROVED)
            ->setDateOrder()
            ->addRateVotes();
        $ratings = [];
        $totalRatingCount = $reviews->getSize();
        if ($totalRatingCount > 0) {
            foreach ($reviews->getItems() as $review) {
                foreach ($review->getRatingVotes() as $vote) {
                    $ratings[] = $vote->getPercent();
                }
            }
        }
        if (count($ratings) > 0) {
            $returnArray["averageRating"] = (double)number_format((5*(array_sum($ratings) / count($ratings)))/100, 2, ".", "");
        } else {
            $returnArray["averageRating"] = 0.0;
        }
        $returnArray["totalProductReviews"] = $totalRatingCount;
        return $returnArray;
    }

}