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

use Aitoc\PreOrders\Helper\PreOrder as PreOrderHelper;
use Aitoc\PreOrders\Helper\Settings as SettingsHelper;
use Aitoc\PreOrders\Api\Data\Source\PreOrderNoteScope as PreOrderNoteScopeSourceInterface;
// TODO: deprecated
use Magento\Catalog\Block\Product\View\AbstractView as ProductViewAbstractView;

/**
 * Class AbstractView
 */
class AbstractView
{
    const SIMPLE_PRODUCT_INFO_BLOCK_NAME = "product.info.simple";

    /**
     * @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 ProductViewAbstractView $subject
     * @param string $result
     * @return mixed
     */
    public function afterToHtml(
        ProductViewAbstractView $subject,
        $result
    ) {
        $product = $subject->getProduct();
        $isPreOrder = $this->preOrderHelper->isProductPreOrder($product->getId());
        $preOrderNoteScope = $this->settingsHelper->getPreOrderNoteScopeSettings();
        if ($isPreOrder) {
            switch ($subject->getNameInLayout()) {
                case self::SIMPLE_PRODUCT_INFO_BLOCK_NAME:
                    if (in_array(PreOrderNoteScopeSourceInterface::PRODUCT_PAGE_SCOPE, $preOrderNoteScope)) {
                        $result = $this->changeStatusText($result, $product->getId());
                    }
                    break;
            }
        }
        return $result;
    }

    /**
     * @param string $html
     * @param int $productId
     * @return string
     */
    public function changeStatusText($html, $productId)
    {
        $statusArray = [__('In stock'), __('Out of stock')];
        $preOrderStatus = $this->preOrderHelper->getPreOrderStatusLabelByProductId($productId);
        $html = str_replace($statusArray, $preOrderStatus, $html);
        return $html;
    }
}
