<?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\Framework\Pricing\Render;

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\App\Request\Http;
use Magento\Framework\Pricing\Render\Amount as MagentoAmount;

/**
 * Class Amount
 */
class Amount
{
    const PRODUCT_VIEW_PATH = 'catalog/product/view';
    /**
     * @var PreOrderHelper
     */
    private $preOrderHelper;

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

    /**
     * @var Http
     */
    private $request;

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

    /**
     * @param MagentoAmount $subject
     * @param $result
     * @return string
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function afterToHtml(MagentoAmount $subject, $result)
    {
        if ($this->canBeApplied() && $subject->getSchema() === false) {
            $message = '';
            $product = $subject->getSaleableItem();
            $productId = $product->getId();
            if ($this->preOrderHelper->isProductPreOrder($productId)) {
                $message = '(' . $this->preOrderHelper->getPreOrderStatusLabelByProductId($productId) . ')';
            }
            $result .= '<span style="font-size: 0.85em;font-weight: bold;" class="preorder_note">' . $message . '</span>';
        }
        return $result;
    }

    /**
     * @return int
     */
    private function getCurrentScope()
    {
        $scope = '';
        $request = $this->request;
        $requestPath = $request->getRouteName() . '/' . $request->getControllerName() . '/' . $request->getActionName();
        switch ($requestPath) {
            case self::PRODUCT_VIEW_PATH:
                $scope = PreOrderNoteScopeSourceInterface::PRODUCT_PAGE_SCOPE;
                break;
        }
        return $scope;
    }

    /**
     * @return bool
     */
    private function canBeApplied()
    {
        $scope = $this->getCurrentScope();
        $preOrderNoteScope = $this->settingsHelper->getPreOrderNoteScopeSettings();
        return in_array($scope, $preOrderNoteScope);
    }
}
