<?php
/**
 * Mageplaza
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Mageplaza.com license that is
 * available through the world-wide-web at this URL:
 * https://www.mageplaza.com/LICENSE.txt
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade this extension to newer
 * version in the future.
 *
 * @category    Mageplaza
 * @package     Mageplaza_QuickCart
 * @copyright   Copyright (c) Mageplaza (https://www.mageplaza.com/)
 * @license     https://www.mageplaza.com/LICENSE.txt
 */

namespace Mageplaza\QuickCart\Plugin\Product\Compare;

use Closure;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Helper\Product\Compare;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\Product\Compare\ItemFactory;
use Magento\Catalog\Model\Product\Compare\ListCompare;
use Magento\Catalog\Model\ResourceModel\Product\Compare\Item\CollectionFactory;
use Magento\Catalog\Model\Session as ModelSession;
use Magento\Customer\Model\Session;
use Magento\Customer\Model\Visitor;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\Data\Form\FormKey\Validator;
use Magento\Framework\Escaper;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\View\Result\PageFactory;
use Magento\Store\Model\StoreManagerInterface;
use Mageplaza\QuickCart\Helper\QuickViewData as HelperData;

/**
 * Class Add
 * @package Mageplaza\QuickCart\Plugin\Product\Compare
 */
class Add extends \Magento\Catalog\Controller\Product\Compare\Add
{
    /**
     * @var HelperData
     */
    protected $_helperData;

    /**
     * Add constructor.
     *
     * @param Context $context
     * @param ItemFactory $compareItemFactory
     * @param CollectionFactory $itemCollectionFactory
     * @param Session $customerSession
     * @param Visitor $customerVisitor
     * @param ListCompare $catalogProductCompareList
     * @param ModelSession $catalogSession
     * @param StoreManagerInterface $storeManager
     * @param Validator $formKeyValidator
     * @param PageFactory $resultPageFactory
     * @param ProductRepositoryInterface $productRepository
     * @param HelperData $helperData
     */
    public function __construct(
        Context $context,
        ItemFactory $compareItemFactory,
        CollectionFactory $itemCollectionFactory,
        Session $customerSession,
        Visitor $customerVisitor,
        ListCompare $catalogProductCompareList,
        ModelSession $catalogSession,
        StoreManagerInterface $storeManager,
        Validator $formKeyValidator,
        PageFactory $resultPageFactory,
        ProductRepositoryInterface $productRepository,
        HelperData $helperData
    ) {
        $this->_helperData = $helperData;

        parent::__construct(
            $context,
            $compareItemFactory,
            $itemCollectionFactory,
            $customerSession,
            $customerVisitor,
            $catalogProductCompareList,
            $catalogSession,
            $storeManager,
            $formKeyValidator,
            $resultPageFactory,
            $productRepository
        );
    }

    /**
     * @param $subject
     * @param Closure $proceed
     *
     * @return Redirect|mixed
     * @throws NoSuchEntityException
     */
    public function aroundExecute($subject, Closure $proceed)
    {
        $result    = [];
        $productId = (int) $this->getRequest()->getParam('product');
        if (!$this->getRequest()->isAjax()) {

            return $proceed();
        }

        $resultRedirect = $this->resultRedirectFactory->create();
        if (!$subject->_formKeyValidator->validate($this->getRequest())) {

            return $resultRedirect->setRefererUrl();
        }

        if ($productId && ($this->_customerVisitor->getId() || $this->_customerSession->isLoggedIn())) {
            $storeId = $this->_storeManager->getStore()->getId();

            try {
                /** @var Product $product */
                $product = $this->productRepository->getById($productId, false, $storeId);
            } catch (NoSuchEntityException $e) {
                $product = null;
            }

            if ($product) {
                $this->_catalogProductCompareList->addProduct($product);
                $productName = $this->_objectManager->get(Escaper::class)
                    ->escapeHtml($product->getName());
                $this->messageManager->addSuccessMessage(__('You added product %1 to the comparison list.',
                    $productName));

                $result = [
                    'success' => true,
                    'message' => __('You added product %1 to the comparison list.', $productName)
                ];

                $this->_eventManager->dispatch('catalog_product_compare_add_product', ['product' => $product]);
                $this->_objectManager->get(Compare::class)->calculate();
            }
        }

        return $this->getResponse()->representJson(HelperData::jsonEncode($result));
    }
}
