<?php

namespace Leadlion\Autogedal\Plugin;

class DescriptionPlugin
{
    protected $configHelper;
    protected $url;
    protected $helperUrl;
    protected $catalogHelper;
    protected $request;

    public function __construct(
        \Leadlion\Autogedal\Helper\Config $configHelper,
        \Amasty\ShopbySeo\Helper\Url $helperUrl,
        \Leadlion\Autogedal\Helper\CatalogHelper $catalogHelper,
        \Magento\Framework\App\Request\Http $request
    ) {
        $this->configHelper = $configHelper;
        $this->helperUrl = $helperUrl;
        $this->catalogHelper = $catalogHelper;
        $this->request = $request;
    }

    public function afterProductAttribute(
        \Magento\Catalog\Helper\Output $subject,
        $result,
        $product,
        $attributeHtml,
        $attributeName
    ) {
        if ($this->request->getFullActionName() == 'catalog_product_view' &&
            $attributeName == 'description'
        ) {
            //$attributesConfig = $this->configHelper->getConfig('leadlion/layer_navigation/filters');
            $attributesConfig = 'auto_brand,auto_model,model_bare_transversale';
            if ($attributesConfig) {
                $allowedFilters = explode(
                    ',',
                    $attributesConfig
                );
                if (!empty($allowedFilters)) {
                    $attributes = [];
                    foreach ($allowedFilters as $key => $filterCode) {
                        if ($product->getData($filterCode)) {
                            $attributes[$filterCode] =
                            [
                                'optionId' => $product->getData($filterCode),
                                'attributeValue' => $product->getAttributeText($filterCode)
                            ];
                        }
                    }
        
                    if (!empty($attributes)) {
                        $index = 0;
                        $keywords = [];
                        foreach ($attributes as $filterCode => $config) {
                            $keywords[] = $config['attributeValue'];
                            $this->url = $this->getFiltersUrl($product, $attributes, $index, $filterCode, $config['optionId']);
                            $index++;
                        }
                        $implodedKeywords = implode(' ', $keywords);
                        $keyword = $this->prepareKeyword($implodedKeywords);
                        if ($result) {
                            $result = preg_replace_callback("/(\<a[^\<]*)?{$keyword}/im", [$this, 'replace'], $result);
                        }
                    }
                }
            }
        }
        return $result;
    }

    protected function prepareKeyword($keyword)
    {
        $rawKeyword = trim($keyword, '+');

        $enclosedRawKeyword = str_replace(
            ['\\', '+', '.', '/', '<', '>', '{', '}', '[', ']', '$', '^', '(', ')', '|', '*', '?'],
            ['\\\\' , '\+', '\.', '\/', '\<', '\>', '\{', '\}', '\[', '\]', '\$', '\^', '\(', '\)', '\|', '\*', '\?'],
            $rawKeyword
        );

        $keyword = str_replace($rawKeyword, $enclosedRawKeyword, $keyword);
        $regexpr = '[A-Za-z0-9]+]';

        $keyword = (substr($keyword, 0, 1) === '+') ?
            substr_replace($keyword, $regexpr, 0, 1)
            : '([a-zA-Z0-9]*)' . $keyword;

        $keyword = (substr($keyword, -1, 1) === '+') ?
            substr_replace($keyword, $regexpr, -1, 1)
            : $keyword . '([a-zA-Z0-9]*)';

        return $keyword;
    }

    protected function getFiltersUrl($product, $attributes, $index, $filterCode, $optionId)
    {
        $params = '';
        $insideIndex = 0;
        if ($index == 0) {
            $params = '?'.$filterCode.'='.$optionId;
        }
        if ($index > 0) {
            foreach ($attributes as $insideFilterCode => $insideConfig) {
                if ($insideIndex <= $index) {
                    if ($insideIndex == 0) {
                        $params =
                            '?'.$insideFilterCode.'='.$insideConfig['optionId'];
                    } else {
                        $params .=
                            '&'.$insideFilterCode.'='.$insideConfig['optionId'];
                    }
                }
                $insideIndex++;
            }
        }

        $categoryUrl = $this->getCategoryUrl($product);
        return $this->helperUrl->seofyUrl(
            $categoryUrl.$params
        );
    }

    protected function getCategoryUrl($product)
    {
        $categoryCollection = $product->getCategoryCollection();
        $categoryCollection->clear();
        $categoryCollection
            ->addAttributeToSort('level', $categoryCollection::SORT_ORDER_DESC)
            ->addAttributeToFilter('path', ['like' => "1/" . $this->catalogHelper->getRootCategory() . "/%"]);
        $categoryCollection->setPageSize(1);
        $categories = $categoryCollection->getFirstItem()->getParentCategories();
        $categoryUrl = '';
        foreach ($categories as $category) {
            $categoryUrl = $category->getUrl();
        }

        return $categoryUrl;
    }

    protected function replace($matches)
    {
        return $this->getLinkHtml($matches[0]);
    }

    /**
     * @param $innerText
     * @return string
     */
    protected function getLinkHtml($innerText)
    {
        return '<a href="' . $this->url. '" title="' . $innerText . '"'
            . ' target="_blank"'
            . '>' . $innerText . '</a>';
    }
}
