<?php
/**
 * @author Aitoc Team
 * @copyright Copyright (c) 2020 Aitoc (https://www.aitoc.com)
 * @package Aitoc_PreOrders
 */

/**
 * Copyright © 2018 Aitoc. All rights reserved.
 * Developed by Alex Yakimovich
 */

namespace Aitoc\PreOrders\Plugin\Checkout\Model;

use Magento\Framework\Registry;
use Magento\Quote\Model\Quote as QuoteModel;
use Magento\Checkout\Model\Session as CheckoutSession;
use Aitoc\PreOrders\Api\Data\Source\CartTypeInterface;
use Magento\Catalog\Model\Product as ProductModel;
use Aitoc\PreOrders\Helper\PreOrder as PreOrderHelper;
use Magento\Catalog\Model\Product\Type\AbstractType;
use Aitoc\PreOrders\Api\Data\Source\RegistryNameInterface;

/**
 * Class Quote
 */
class Quote
{
    /**
     * @var Registry
     */
    private $registry;

    /**
     * @var PreOrderHelper
     */
    private $preOrderHelper;

    /**
     * @var CheckoutSession
     */
    private $checkoutSession;

    /**
     * @param Registry $registry
     * @param PreOrderHelper $preOrderHelper
     * @param CheckoutSession $checkoutSession
     */
    public function __construct(
        Registry $registry,
        PreOrderHelper $preOrderHelper,
        CheckoutSession $checkoutSession
    ) {
        $this->registry = $registry;
        $this->preOrderHelper = $preOrderHelper;
        $this->checkoutSession = $checkoutSession;
    }

    /**
     * @param QuoteModel $subject
     * @param ProductModel $product
     * @param null $request
     * @param string $processMode
     */
    public function beforeAddProduct(
        QuoteModel $subject,
        ProductModel $product,
        $request = null,
        $processMode = AbstractType::PROCESS_MODE_FULL
    ) {
        $this->registry->register(RegistryNameInterface::CURRENT_CART_TYPE, $this->getCurrentCartType());
    }

    /**
     * @return int
     */
    private function getCurrentCartType()
    {
        $quoteItems = $this->checkoutSession->getQuote()->getAllVisibleItems();
        $regularFlag = false;
        $preOrderFlag = false;
        if (count($quoteItems) === 0) {
            return CartTypeInterface::TYPE_EMPTY;
        }

        foreach ($quoteItems as $quoteItem) {
            if ($this->preOrderHelper->isQuoteItemPreOrder($quoteItem)) {
                $preOrderFlag = true;
            } else {
                $regularFlag = true;
            }
        }

        switch (true) {
            case ($regularFlag && $preOrderFlag):
                return CartTypeInterface::TYPE_MIXED;
            case ($preOrderFlag):
                return CartTypeInterface::TYPE_PRE_ORDER;
            default:
                return CartTypeInterface::TYPE_REGULAR;
        }
    }
}
