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

use Aitoc\PreOrders\Helper\PreOrder as PreOrderHelper;
use Magento\CatalogWidget\Block\Product\ProductsList as CatalogWidgetProductsList;
use Magento\Framework\Exception\LocalizedException;

/**
 * Class ProductsList
 */
class ProductsList
{

    const PRODUCT_LIST_BLOCK_NAME = "category.products.list";

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

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

    /**
     * @param CatalogWidgetProductsList $subject
     * @param string $result
     * @return string
     * @throws LocalizedException
     */
    public function afterToHtml(
        CatalogWidgetProductsList $subject,
        $result
    ) {
        $productCollection = $subject->getProductCollection();
        if ($productCollection) {
            $productIds = $productCollection->getColumnValues($productCollection->getIdFieldName());
            $result = $this->changeButtonText($result, $productIds);
        }

        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;
    }
}
