<?php
/**
 * Cart product add after Observer
 *
 * @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\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magetop\Quotesystem\Helper\Data;
use \Magento\Framework\Message\ManagerInterface;
use Magento\Checkout\Model\Session as CheckoutSession;

class CheckoutIndexPredispatch implements ObserverInterface
{
    /**
     * @var \Magetop\Quotesystem\Helper\Data
     */
    protected $_helper;
    /**
     * @var \Magento\Framework\Message\ManagerInterface
     */
    protected $_messageManager;

    /**
     * @param Data             $helper
     * @param CheckoutSession  $checkoutSession
     * @param ManagerInterface $messageManager
     */

    public function __construct(
        Data $helper,
        CheckoutSession $checkoutSession,
        ManagerInterface $messageManager
    ) {
        $this->_helper = $helper;
        $this->_checkoutSession = $checkoutSession;
        $this->_messageManager = $messageManager;
    }
    /**
     * Cart product add after event
     *
     * @param \Magento\Framework\Event\Observer $observer
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $helper = $this->_helper;
        $sessionData = $helper->getCheckoutSession();
        foreach ($sessionData->getQuote()->getAllItems() as $item) {
            if ($item->getParentItemId() === null && $item->getItemId() > 0) {
                $quoteCollection = $helper->getMtQuoteModel()->getCollection()
                    ->addFieldToFilter("item_id", $item->getItemId());
                $baseCurrencyCode = $helper->getBaseCurrencyCode();
                $currentCurrencyCode = $helper->getCurrentCurrencyCode();
                if ($quoteCollection->getSize()) {
                    if ($helper->checkAndUpdateForDiscount($item)) {
                        $item->setNoDiscount(1);
                    } else {
                        $item->setNoDiscount(0);
                    }
                    $item->save();
                }
            }
        }
    }
}
