<?php
/**
 * Magetop Store
 *
 * @category  Magetop Extensions
 * @package   Magetop_Quotesystem
 * @author    Magetop Developer
 * @copyright Copyright (c) Magetop (https://www.magetop.com)
 * @license   https://www.magetop.com/license.html
 */

namespace Magetop\Quotesystem\Model\Plugin\Quote;

use Magento\Framework\Registry;

class Item
{
    /**
     * @var \Magetop\Quotesystem\Helper\Data
     */
    protected $quoteHelper;

    /**
     * @var \Magento\Framework\App\Request\Http
     */
    protected $request;

    /**
     * @param \Magetop\Quotesystem\Helper\Data     $quoteHelper
     * @param \Magento\Framework\App\Request\Http $request
     */
    public function __construct(
        \Magetop\Quotesystem\Helper\Data $quoteHelper,
        \Magento\Framework\App\Request\Http $request
    ) {
        $this->quoteHelper = $quoteHelper;
        $this->request = $request;
    }

    /**
     * After Represent Product
     *
     * @param \Magento\Quote\Model\Quote\Item $subject
     * @param array                           $result
     * @return array
     */
    public function afterRepresentProduct(
        \Magento\Quote\Model\Quote\Item $subject,
        $result
    ) {
        if ($result==true) {
            $helper = $this->quoteHelper;
            if ($quoteId = $helper->isQuoteItem($subject)) {
                if ($quoteId!=0) {
                    return false;
                }
            }
            $params = $this->request->getParams();
            $quoteItems = $helper->getCheckoutSession()->getQuote()->getAllItems();
            if (count($quoteItems)) {
                foreach ($quoteItems as $item) {
                    if ($item->getParentItem()) {
                        continue;
                    }
                    if (array_key_exists('product', $params) && $item->getProductId()==$params['product']) {
                        return (bool)(!($helper->checkQuoteProductinItem($item)));
                    }
                }
            }
        }
        return $result;
    }
}
