<?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 Product
{
    /**
     * @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\Product $subject
     * @param mixed $result
     * @param string $attributeCode
     * @return mixed
     */
    public function afterGetData(\Magento\Catalog\Model\Product $subject, $result, $attributeCode = '')
    {
        if ($this->request->getFullActionName() == 'catalog_product_view' &&
            $this->request->getParam('wtai-preview')
        ) {
            $previewText = $this->getAttributePreviewValue($subject->getId(), $attributeCode);

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

        return $result;
    }

    /**
     * After get media gallery images
     *
     * @param \Magento\Catalog\Model\Product $subject
     * @param mixed $result
     * @return mixed
     */
    public function afterGetMediaGalleryImages(\Magento\Catalog\Model\Product $subject, $result)
    {
        if ($this->request->getFullActionName() == 'catalog_product_view' &&
            $this->request->getParam('wtai-preview')
        ) {
            if (empty($result->getItems())) {
                return $result;
            }

            $imageIds = array_map(function ($image) {
                return $image->getId();
            }, $result->getItems());

            try {
                $apiImages = $this->previewHelper->getGeneratedImages($imageIds);
            } catch (\Exception $e) {
                $apiImages = [];
            }

            if (empty($apiImages)) {
                return $result;
            }
            
            foreach ($result as &$image) {
                $filteredImages = array_filter(
                    $apiImages,
                    function ($filteredImage) use ($image) {
                        return $filteredImage['imageId'] == $image->getId();
                    }
                );
                $apiImage = reset($filteredImages);
                if ($apiImage && isset($apiImage['altText']['value'])) {
                    $image->setLabel($apiImage['altText']['value']);
                }
            }
        }

        return $result;
    }

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

        return $preview;
    }
}
