<?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 DashboardData implements \Magento\Framework\GraphQl\Query\ResolverInterface
{

    protected $vote;
    protected $helper;
    protected $coreHelper;
    protected $subscriber;
    protected $orderConfig;
    protected $storeManager;
    protected $helperCatalog;
    protected $productFactory;
    protected $orderCollection;
    protected $collectionFactory;
    protected $orderHistoryBlock;

    public function __construct(
        \Webkul\MobikulGraphQL\Helper\Data $helper,
        \Webkul\MobikulCore\Helper\Data $coreHelper,
        \Magento\Sales\Model\Order\Config $orderConfig,
        \Magento\Review\Model\Rating\Option\Vote $vote,
        \Magento\Newsletter\Model\Subscriber $subscriber,
        \Webkul\MobikulCore\Helper\Catalog $helperCatalog,
        \Magento\Sales\Block\Order\History $orderHistoryBlock,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Sales\Model\ResourceModel\Order\Collection $orderCollection,
        \Magento\Review\Model\ResourceModel\Review\Product\CollectionFactory $collectionFactory
    ) {
        $this->vote = $vote;
        $this->helper = $helper;
        $this->subscriber = $subscriber;
        $this->coreHelper = $coreHelper;
        $this->orderConfig = $orderConfig;
        $this->storeManager = $storeManager; 
        $this->helperCatalog = $helperCatalog;
        $this->productFactory = $productFactory;
        $this->orderCollection = $orderCollection;
        $this->collectionFactory = $collectionFactory;
        $this->orderHistoryBlock = $orderHistoryBlock;
    }

    /**
     * @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
    ) {
        $storeId = $this->storeManager->getStore()->getId();
        $customer = $this->helper->getCustomerByToken($args["token"]);
        $returnArray = [];
        $returnArray["name"] = $customer->getName();
        $returnArray["email"] = $customer->getEmail();
        $subscriber = $this->subscriber->loadByEmail($returnArray["email"]);
        if ($subscriber->isSubscribed()) {
            $returnArray["subscriptionMsg"] = __("You are subscribed to \"General Subscription\".");
        } else {
            $returnArray["subscriptionMsg"] = __("You aren't subscribed to our newsletter.");
        }

        $address = $customer->getPrimaryBillingAddress();
        if ($address) {
            $returnArray["billingId"] = $address->getId();
            $returnArray["billingAddress"] = $address->format("html");
        }
        $address = $customer->getPrimaryShippingAddress();
        if ($address) {
            $returnArray["shippingId"] = $address->getId();
            $returnArray["shippingAddress"] = $address->format("html");
        }
        $orderCollection = $this->orderCollection
            ->addFieldToSelect("*")
            ->addFieldToFilter("customer_id", $customer->getId())
            ->addFieldToFilter("status", ["in"=>$this->orderConfig->getVisibleOnFrontStatuses()])
            ->setOrder("created_at", "DESC")
            ->setPageSize(5)
            ->setCurPage(1);
        $orderList = [];
        foreach ($orderCollection as $order) {
            $eachOrder = [];
            $eachOrder["date"] = $this->orderHistoryBlock->formatDate($order->getCreatedAt());
            $eachOrder["date"] = date('F j, Y ', strtotime($eachOrder["date"]));
            $eachOrder["state"] = $order->getState();
            $eachOrder["status"] = $order->getStatusLabel();
            $eachOrder["order_id"] = $order->getRealOrderId();
            $eachOrder["order_total"] = $this->helperCatalog->stripTags($order->formatPrice($order->getGrandTotal()));
            $eachOrder["statusColorCode"] = $this->coreHelper->getOrderStatusColorCode($order->getStatus());
            $canReorder = false;
            if ($this->canReorder($order)) {
                $canReorder = $this->canReorder($order);
            }
            $eachOrder["canReorder"] = $canReorder;
            $orderList[] = $eachOrder;
        }
        $returnArray["orderList"] = $orderList;


        $reviewCollection = $this->collectionFactory
            ->create()
            ->setDateOrder()
            ->addStoreFilter($storeId)
            ->addCustomerFilter($customer->getId())
            ->setPageSize(5)->setCurPage(1);
        $reviewList = [];
        foreach ($reviewCollection as $key => $review) {
            $product = $this->productFactory->create()->load($review->getEntityPkValue());
            $eachReview = [];
            $eachReview["id"] = (int)$key;
            $eachReview["productId"] = (int)$product->getId();
            $eachReview["thumbNail"] = $this->helperCatalog->getImageUrl($product, 1000/3);
            $eachReview["productName"] = $this->helperCatalog->stripTags($product->getName());
            $ratingCollection = $this->vote
                ->getResourceCollection()
                ->setReviewFilter($review->getReviewId())
                ->addRatingInfo($storeId)
                ->setStoreFilter($storeId)
                ->load();
            $totalRating = 0;
            $ratingCount = 0;
            foreach ($ratingCollection as $rating) {
                $totalRating += $rating->getPercent();
                $ratingCount++;
            }
            if ($ratingCount == 0) {
                $eachReview["customerRating"] = 0;
            } else {
                $eachReview["customerRating"] = (int)($totalRating/$ratingCount)/20;
            }
            $reviewList[] = $eachReview;
        }
        $returnArray["reviewList"] = $reviewList;
        return $returnArray;
    }

    /**
     * Check wheather order can be reordered or not.
     *
     * @param \Magento\Sales\Model\Order $order order
     * 
     * @return integer
     */
    public function canReorder(\Magento\Sales\Model\Order $order)
    {
        if (!$this->coreHelper->getConfigData("sales/reorder/allow")) {
            return 0;
        } else {
            return $order->canReorder();
        }
    }

}