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

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\CatalogSearch\Block\Result as CatalogSearchResult;

/**
 * Class Result
 */
class Result
{
    /**
     * @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 CatalogSearchResult $subject
     * @param string $result
     * @return mixed|null|string|string[]
     */
    public function afterToHtml(
        CatalogSearchResult $subject,
        $result
    ) {
        $productIds = $this->registry->registry(RegistryNameInterface::CURRENT_SEARCH_PRODUCT_IDS);
        $preOrderNoteScope = $this->settingsHelper->getPreOrderNoteScopeSettings();
        if (in_array(PreOrderNoteScopeSourceInterface::SEARCH_RESULT_SCOPE, $preOrderNoteScope)) {
            $result = $this->changeButtonText($result, $productIds);
        }
        $this->registry->unregister(RegistryNameInterface::CURRENT_SEARCH_PRODUCT_IDS);
        return $result;
    }

    /**
     * @param string $html
     * @param int[] $productIds
     * @return string
     */
    public function changeButtonText($html, $productIds)
    {
        $addToCartLabel = __('Add to Cart');
        $preOrderLabel = __('Pre-Order');
        $tempLabel = __('To Cart Temp');
        foreach ($productIds as $productId) {
            $isPreOrder = $this->preOrderHelper->isProductPreOrder($productId);
            $buttonTitle = '/' . preg_quote(">" . $addToCartLabel . "<", '/') . '/';
            if ($isPreOrder) {
                $preOrderButtonTitle = ">" . $preOrderLabel . "<";
            } else {
                $preOrderButtonTitle = ">" . $tempLabel . "<";
            }

            $html = preg_replace($buttonTitle, $preOrderButtonTitle, $html, 1);
        }
        $html = str_replace($tempLabel, $addToCartLabel, $html);
        return $html;
    }
}
