<?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\Controller\Cart;

use Magento\Checkout\Controller\Cart\Configure as ConfigureCore;
use Magento\Checkout\Model\Cart;
use Magento\Framework\App\ViewInterface;
use Mageplaza\QuickCart\Helper\QuickViewData as HelperData;

/**
 * Class Configure
 * @package Mageplaza\QuickCart\Plugin\Controller\Cart
 */
class Configure
{
    /**
     * @var ViewInterface
     */
    protected $_view;

    /**
     * @var Cart
     */
    protected $_cart;

    /**
     * @var HelperData
     */
    protected $_helperData;

    /**
     * Configure constructor.
     *
     * @param ViewInterface $view
     * @param Cart $cart
     * @param HelperData $helperData
     */
    public function __construct(
        ViewInterface $view,
        Cart $cart,
        HelperData $helperData
    ) {
        $this->_view = $view;
        $this->_cart = $cart;
        $this->_helperData = $helperData;
    }

    /**
     * @param ConfigureCore $subject
     * @param $result
     *
     * @return mixed
     */
    public function afterExecute(ConfigureCore $subject, $result)
    {
        if ($subject->getRequest()->getParam('mpquickview')) {
            $quoteItem = null;
            $itemId = (int)$subject->getRequest()->getParam('id');
            $productId = (int)$subject->getRequest()->getParam('product_id');
            if ($itemId) {
                $quoteItem = $this->_cart->getQuote()->getItemById($itemId);
            }
            $this->_view->loadLayout();
            $layout = $this->_view->getLayout();

            $infoConfig = explode(',', $this->_helperData->getQuickViewConfig('edit_cart_info'));
            $this->_helperData->removeInfo($infoConfig, $layout);

            $resultPage['html_content'] = $layout->renderElement('main.content');
            $resultPage['qty'] = $quoteItem->getQty();
            $resultPage['productId'] = $productId;

            return $subject->getResponse()->representJson(HelperData::jsonEncode($resultPage));
        }

        return $result;
    }
}
