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

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Grid;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Controller\ResultFactory;
use Magento\Ui\Component\MassAction\Filter;
use WriteTextAI\WriteTextAI\Helper\Image as WtaImageHelper;
use Magento\Store\Model\Store;

class GetImages extends Action implements HttpPostActionInterface
{
    /**
     * @var Filter
     */
    protected $filter;

    /**
     * @var CollectionFactory
     */
    protected $collectionFactory;

    /**
     * @var WtaImageHelper
     */
    protected $wtaImageHelper;

    /**
     * Constructor
     *
     * @param Context $context
     * @param Filter $filter
     * @param CollectionFactory $collectionFactory
     * @param WtaImageHelper $wtaImageHelper
     */
    public function __construct(
        Context $context,
        Filter $filter,
        CollectionFactory $collectionFactory,
        WtaImageHelper $wtaImageHelper
    ) {
        $this->filter = $filter;
        $this->collectionFactory = $collectionFactory;
        $this->wtaImageHelper = $wtaImageHelper;
        parent::__construct($context);
    }

    /**
     * Execute
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $result = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        
        try {
            $filters = $this->getRequest()->getPost('filters', []);
            $selectedFields = $this->getRequest()->getPost('fields', []);
            $attributes = $this->getRequest()->getPost('attributes', []);
            $autoOptimizeKeywords = $this->getRequest()->getPost('auto_optimize_keywords', false);

            $storeFilter = isset($filters['store_id']) ? $filters['store_id'] : Store::DEFAULT_STORE_ID;

            $collection = $this->filter
                ->getCollection(
                    $this->collectionFactory
                        ->create()
                        ->addAttributeToSelect('*')
                )
                ->setStoreId($storeFilter)
                ->addMediaGalleryData();
            
            $images = [];
            $featuredImageId = '';
            foreach ($collection as $product) {
                $featuredImageId = '';
                $featuredImage = $this->wtaImageHelper->getImageValue($product);
                $mediaGallery = $product->getMediaGalleryImages()->setOrder('position', 'ASC')->getItems();
                /**
                 * Need to manually sort as setOrder is not getting the right position order
                 */
                usort($mediaGallery, function ($a, $b) {
                    return $a->getPosition() <=> $b->getPosition();
                });
                if (!empty($mediaGallery)) {
                    $mediaGalleryIds = [];
                    foreach ($mediaGallery as $mediaGalleryEntry) {
                        if ($mediaGalleryEntry->getDisabled()) {
                            continue;
                        }
                        if ($featuredImage && $mediaGalleryEntry->getId() === $featuredImage) {
                            $featuredImageId = $mediaGalleryEntry->getId();
                        }
                        $fieldsWithImageUpload = [
                            'alt_text',
                            'product_description',
                            'category_description',
                            'short_product_description'
                        ];
                        $isImageUploadFieldSelected = !empty(
                            array_intersect($fieldsWithImageUpload, $selectedFields)
                        );
                        if ($isImageUploadFieldSelected) {
                            $mediaGalleryIds[] = $mediaGalleryEntry->getId();
                        }
                    }
                    
                    // limit the number of images of gallery to 11 (featured image + 10 images)
                    $mediaGalleryIds = array_slice($mediaGalleryIds, 0, 11);

                    $textTypes = [
                        'page_title',
                        'page_description',
                        'product_description',
                        'short_product_description',
                        'open_graph'
                    ];
                    
                    /** add the featured image id to the beginning
                     * of the media gallery ids if it is not already in the list
                     * */
                    if (!empty($featuredImageId) &&
                        !in_array($featuredImageId, $mediaGalleryIds)
                        && (
                            (
                                in_array('thumbnail', $attributes)
                                && !empty(array_intersect($textTypes, $selectedFields))
                            )
                            || $autoOptimizeKeywords
                        )
                    ) {
                        array_unshift($mediaGalleryIds, $featuredImageId);
                    }
    
                    if (!empty($mediaGalleryIds)) {
                        $images[$product->getId()] = implode(",", $mediaGalleryIds);
                    }
                }
            }

            $resultData = [
                'success' => true,
                'images' => $images
            ];

            $result->setData($resultData);
        } catch (\Exception $e) {
            $message = $e->getMessage();
            if (!$message) {
                $message = __(
                    'A system error has occurred. Please try again. If the issue persists,'
                    . ' please contact our support team at support@writetext.ai.'
                );
            }
            
            $result->setData([
                'success' => false,
                'message' => $message
            ]);
        }

        return $result;
    }
}
