<?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\CustomerData;

use Aitoc\PreOrders\Helper\PreOrder as PreOrderHelper;
use Aitoc\PreOrders\Helper\Settings as SettingsHelper;
use Aitoc\PreOrders\Api\Data\Source\PreOrderNoteScope as PreOrderNoteScopeSourceInterface;
use \Magento\Framework\Registry;
use Aitoc\PreOrders\Api\Data\Source\RegistryNameInterface;
use Magento\Checkout\CustomerData\DefaultItem as CheckoutCustomerDataDefaultItem;
use Magento\Quote\Model\Quote\Item as QuoteItem;

/**
 * Class DefaultItem
 */
class DefaultItem
{
    /**
     * @var PreOrderHelper
     */
    private $preOrderHelper;

    /**
     * @var SettingsHelper
     */
    private $settingsHelper;

    /**
     * @var Registry
     */
    private $registry;

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

    /**
     * @param CheckoutCustomerDataDefaultItem $subject
     * @param QuoteItem $item
     */
    public function beforeGetItemData(
        CheckoutCustomerDataDefaultItem $subject,
        QuoteItem $item
    ) {
        if ($this->registry->registry(RegistryNameInterface::CURRENT_QUOTE_ITEM)) {
            $this->registry->unregister(RegistryNameInterface::CURRENT_QUOTE_ITEM);
        }
        $this->registry->register(RegistryNameInterface::CURRENT_QUOTE_ITEM, $item);
    }

    /**
     * @param CheckoutCustomerDataDefaultItem $subject
     * @param $result
     * @return mixed
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function afterGetItemData(
        CheckoutCustomerDataDefaultItem $subject,
        $result
    ) {
        $isPreOrder = false;
        $preOrderNoteScope = $this->settingsHelper->getPreOrderNoteScopeSettings();
        if (in_array(PreOrderNoteScopeSourceInterface::MINI_CART_SCOPE, $preOrderNoteScope)) {
            $quoteItem = $this->registry->registry(RegistryNameInterface::CURRENT_QUOTE_ITEM);
            if ($quoteItem) {
                $isPreOrder = $this->preOrderHelper->isQuoteItemPreOrder($quoteItem);
            }
        }
        $result['is_pre_order'] = $isPreOrder;
        return $result;
    }
}
