<?php
/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

namespace WriteTextAI\WriteTextAI\Plugin\Catalog\Model;

use Magento\Framework\App\RequestInterface;
use WriteTextAI\WriteTextAI\Helper\Preview;
use Magento\Framework\Url\DecoderInterface;

/**
 * change attribute value with generated text for
 */
class Category
{
    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @var Preview
     */
    protected $previewHelper;

    /**
     * @var DecoderInterface
     */
    protected $urlDecoder;

    /**
     * Constructor
     *
     * @param RequestInterface $request
     * @param Preview $previewHelper
     * @param DecoderInterface $urlDecoder
     */
    public function __construct(
        RequestInterface $request,
        Preview $previewHelper,
        DecoderInterface $urlDecoder
    ) {
        $this->request = $request;
        $this->previewHelper = $previewHelper;
        $this->urlDecoder = $urlDecoder;
    }

    /**
     * After get data
     *
     * @param \Magento\Catalog\Model\Category $subject
     * @param mixed $result
     * @param string $attributeCode
     * @return mixed
     */
    public function afterGetData(\Magento\Catalog\Model\Category $subject, $result, $attributeCode = '')
    {
        if ($this->request->getFullActionName() == 'catalog_category_view' &&
            $this->request->getParam('wtai-preview')
        ) {
            $previewText = $this->getCategoryAttributePreviewValue($subject->getId(), $attributeCode);

            if ($previewText) {
                //$result = nl2br($previewText);
                $result = $previewText;
            }
        }

        return $result;
    }

    /**
     * Get attribute preview value
     *
     * @param int $categoryId
     * @param string $attributeCode
     * @return string
     */
    protected function getCategoryAttributePreviewValue($categoryId, $attributeCode)
    {
        $userId = $this->urlDecoder->decode($this->request->getParam('wtai-preview'));
        $preview = $this->previewHelper->getCategoryAttributePreviewValue($categoryId, $userId, $attributeCode);

        return $preview;
    }
}
