<?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\Catalog\Block\Product;

use Aitoc\PreOrders\Helper\PreOrder as PreOrderHelper;
use Aitoc\PreOrders\Helper\Settings as SettingsHelper;
use Aitoc\PreOrders\Api\Data\Source\PreOrderNoteScope as PreOrderNoteScopeSourceInterface;
use Aitoc\PreOrders\Api\Data\Source\PaymentTypeInterface;
use Magento\Catalog\Block\Product\View as BlockProductView;

/**
 * Class View
 */
class View
{
    const ADD_TO_CART_BLOCK_NAME = "product.info.addtocart";
    const ADD_TO_CART_ADDITIONAL_BLOCK_NAME = "product.info.addtocart.additional";

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

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

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

    /**
     * @param BlockProductView $subject
     * @param string $result
     * @return string
     */
    public function afterToHtml(
        BlockProductView $subject,
        $result
    ) {
        $product = $subject->getProduct();
        $isPreOrder = $this->preOrderHelper->isProductPreOrder($product->getId());
        if ($isPreOrder) {
            switch ($subject->getNameInLayout()) {
                case self::ADD_TO_CART_BLOCK_NAME:
                case self::ADD_TO_CART_ADDITIONAL_BLOCK_NAME:
                    if ($this->settingsHelper->getPaymentTypeSetting() == PaymentTypeInterface::TYPE_NOTIFICATION) {
                        $result = '';
                    } else {
                        $preOrderNoteScope = $this->settingsHelper->getPreOrderNoteScopeSettings();
                        if (in_array(PreOrderNoteScopeSourceInterface::PRODUCT_PAGE_SCOPE, $preOrderNoteScope)) {
                            $result = $this->changeButtonText($result);
                        }
                    }
                    break;
            }
        }
        return $result;
    }

    /**
     * @param string$html
     * @return string
     */
    public function changeButtonText($html)
    {
        $buttonTitle = __('Add to Cart');
        $preOrderButtonTitle = __('Pre-Order');
        $html = str_replace($buttonTitle, $preOrderButtonTitle, $html);
        return $html;
    }
}
