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

use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\App\Response\RedirectInterface;
use Magetop\Quotesystem\Api\QuoteRepositoryInterface;

class SwitchAction extends \Magento\Directory\Controller\Currency\SwitchAction
{
    /**
     * @var \Magento\Checkout\Model\Session
     */
    protected $_checkoutSession;
    /**
     * @var \Magetop\Quotesystem\Helper\Data
     */
    protected $_helper;
    /**
     * @var StoreManagerInterface
     */
    protected $_storeManager;
    /**
     * @var \Magento\Checkout\Model\Cart
     */
    protected $_cartModel;
    /**
     * @var RedirectInterface
     */
    protected $_redirectInterface;

    /**
     * @var Magetop\Quotesystem\Api\QuoteRepositoryInterface
     */
    protected $_quoteRepository;

    /**
     * Switch construct
     *
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magetop\Quotesystem\Helper\Data       $helper
     * @param \Magento\Checkout\Model\Session       $checkoutSession
     * @param \Magento\Checkout\Model\Cart          $checkoutCartModel
     * @param StoreManagerInterface                 $storeManager
     * @param RedirectInterface                     $redirectInterface
     * @param QuoteRepositoryInterface              $quoteRepository
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magetop\Quotesystem\Helper\Data $helper,
        \Magento\Checkout\Model\Session $checkoutSession,
        \Magento\Checkout\Model\Cart $checkoutCartModel,
        StoreManagerInterface $storeManager,
        RedirectInterface $redirectInterface,
        QuoteRepositoryInterface $quoteRepository
    ) {
        $this->_helper = $helper;
        $this->_checkoutSession = $checkoutSession;
        $this->_storeManager = $storeManager;
        $this->_cartModel = $checkoutCartModel;
        $this->_redirectInterface = $redirectInterface;
        $this->_quoteRepository = $quoteRepository;
        parent::__construct($context);
    }

    /**
     * Execute
     *
     * @return $this
     */
    public function execute()
    {
        /**
         * @var \Magento\Store\Model\StoreManagerInterface $storeManager
         */
        $storeManager = $this->_storeManager;
        $currency = (string) $this->getRequest()->getParam('currency');
        if ($currency) {
            $currentCurrencyCode = $currency;
            $baseCurrency = $this->_helper->getBaseCurrencyCode();
            $storeManager->getStore()->setCurrentCurrencyCode($currency);

            $session = $this->_helper->getCheckoutSession();
            foreach ($session->getQuote()->getAllItems() as $item) {
                if ($item->getParentItemId() === null && $item->getItemId() > 0) {
                    $price = 0;
                    $quoteId = 0;
                    $quoteQty = 0;
                    $quoteCollection = $this->_helper->getMtQuoteModel()->getCollection()
                        ->addFieldToFilter("item_id", $item->getItemId());
                    
                    if ($quoteCollection->getSize()) {
                        foreach ($quoteCollection as $quote) {
                            $price = $quote->getQuotePrice();
                            $quoteId = $quote->getEntityId();
                            $quoteQty = $quote->getQuoteQty();
                        }
                    }
                    if ($currency == $baseCurrency) {
                        $priceOne = $price;
                    } else {
                        $priceOne = $this->_helper->getmtconvertCurrency($currentCurrencyCode, $currency, $price);
                    }
                   
                    if ($quoteId != 0) {
                        $item->setCustomPrice($priceOne);
                        $item->setOriginalCustomPrice($priceOne);
                        $item->setQty($quoteQty);
                        $item->setRowTotal($priceOne * $quoteQty);
                        $item->getProduct()->setIsSuperMode(true);
                        $item->save();
                    }
                } else {
                    $quote = $quote = $this->_quoteRepository->getById($quoteId);
                    $quoteBundleOption = $this->_helper->convertStringAccToVersion(
                        $quote->getBundleOption(),
                        'decode'
                    );
                    $this->addQuoteItem($quoteBundleOption, $quote, $currentCurrencyCode, $item);
                }
            }
        }
        $this->_cartModel->save();
        $storeUrl = $storeManager->getStore()->getBaseUrl();
        $this->getResponse()->setRedirect($this->_redirectInterface->getRedirectUrl($storeUrl));
    }

    /**
     * Add Quote Item
     *
     * @param array $quoteBundleOption
     * @param object $quote
     * @param string $currentCurrencyCode
     * @param object $quoteItem
     */
    public function addQuoteItem($quoteBundleOption, $quote, $currentCurrencyCode, $quoteItem)
    {
        $itemProductId = $quoteItem->getProductId();
        if (!empty($quoteBundleOption)) {
            $bundleProductConfiguredPrice = $quote->getProductPrice();
            foreach ($quoteBundleOption['bundle_option'] as $optionId => $optionValue) {
                if ($quoteBundleOption['bundle_option_product'][$optionId] == $itemProductId) {
                    $currentOptionProductPrice = $quoteBundleOption['bundle_option_price'][$optionId];
                    $currentTotalPrice = $currentOptionProductPrice;
                    $calculatePercent = ($currentTotalPrice * 100)/$bundleProductConfiguredPrice;
                    $price = (($quote->getQuotePrice() * $calculatePercent)/100)/
                    $quoteBundleOption['bundle_option_qty'][$optionId];
                    $quoteCurrency = $quote->getQuoteCurrency();
                    if ($quoteCurrency != $currentCurrencyCode) {
                        $priceOne = $this->_helper->getmtconvertCurrency(
                            $quoteCurrency,
                            $currentCurrencyCode,
                            $price
                        );
                    } else {
                        $priceOne = $price;
                    }
                    $quoteItem->setPrice($priceOne);
                    $quoteItem->setCustomPrice($priceOne);
                    $quoteItem->setOriginalCustomPrice($priceOne);
                    $quoteItem->setRowTotal($priceOne * $quoteBundleOption['bundle_option_qty'][$optionId]);
                    if ($this->_helper->checkAndUpdateForDiscount($quoteItem)) {
                        $quoteItem->setNoDiscount(1);
                    } else {
                        $quoteItem->setNoDiscount(0);
                    }
                    $quoteItem->getProduct()->setIsSuperMode(true);
                }
            }
        }
    }
}
