<?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\Block\Cart\Additional;

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\Block\Cart\Additional\Info as CheckoutCartAdditionalInfoBlock;
use Magento\Quote\Model\Quote\Item as QuoteItem;
use Magento\Framework\Exception\LocalizedException;

/**
 * Class Info
 */
class Info
{
    /**
     * @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 CheckoutCartAdditionalInfoBlock $subject
     * @param QuoteItem $quoteItem
     */
    public function beforeSetItem(
        CheckoutCartAdditionalInfoBlock $subject,
        QuoteItem $quoteItem
    ) {
        if ($this->registry->registry(RegistryNameInterface::CURRENT_QUOTE_ITEM)) {
            $this->registry->unregister(RegistryNameInterface::CURRENT_QUOTE_ITEM);
        }
        $this->registry->register(RegistryNameInterface::CURRENT_QUOTE_ITEM, $quoteItem);
    }

    /**
     * @param CheckoutCartAdditionalInfoBlock $subject
     * @param string $result
     * @return string
     * @throws LocalizedException
     */
    public function afterToHtml(
        CheckoutCartAdditionalInfoBlock $subject,
        $result
    ) {
        $preOrderNoteScope = $this->settingsHelper->getPreOrderNoteScopeSettings();
        if (in_array(PreOrderNoteScopeSourceInterface::CART_SCOPE, $preOrderNoteScope)) {
            $quoteItem = $this->registry->registry(RegistryNameInterface::CURRENT_QUOTE_ITEM);
            $isPreOrder = $this->preOrderHelper->isQuoteItemPreOrder($quoteItem);
            if ($isPreOrder) {
                $result = $result . '<b>* Pre-Order</b>';
            }
        }
        return $result;
    }
}
