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

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\CategoriesGrid;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory as CategoryCollectionFactory;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Controller\ResultFactory;
use Magento\Store\Model\Store;
use WriteTextAI\WriteTextAI\Model\Categories\GeneratedText;
use WriteTextAI\WriteTextAI\Ui\Component\MassAction\JsonFilter;

class Transferable extends Action implements HttpPostActionInterface
{
    public const ADMIN_RESOURCE = 'WriteTextAI_WriteTextAI::transfer';

    /**
     * @var GeneratedText
     */
    protected $generatedText;

    /**
     * @var JsonFilter
     */
    protected $filter;

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

    /**
     * Constructor
     *
     * @param Context $context
     * @param GeneratedText $generatedText
     * @param JsonFilter $filter
     * @param CategoryCollectionFactory $collectionFactory
     */
    public function __construct(
        Context $context,
        GeneratedText $generatedText,
        JsonFilter $filter,
        CategoryCollectionFactory $collectionFactory
    ) {
        parent::__construct($context);
        $this->generatedText = $generatedText;
        $this->filter = $filter;
        $this->collectionFactory = $collectionFactory;
    }

    /**
     * Execute
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $result = $this->resultFactory->create(ResultFactory::TYPE_JSON);

        try {
            $fields = (array) $this->getRequest()->getPost('fields', []);
            $filters = (array) $this->getRequest()->getPost('filters', []);
            $storeFilter = isset($filters['store_id']) ? (int) $filters['store_id'] : Store::DEFAULT_STORE_ID;

            $collection = $this->filter->getCollection(
                $this->collectionFactory->create()->addAttributeToSelect('*')
            );
            $collection->setStoreId($storeFilter);

            if ($collection->getSize() === 0) {
                $result->setData([
                    'success' => false,
                    'message' => __('No categories found')
                ]);
                return $result;
            }

            $categoryIds = $collection->getAllIds();
            $generated = $this->generatedText->getGeneratedByStoreId(implode(',', $categoryIds), $storeFilter, true);

            foreach ($categoryIds as $categoryId) {
                if (!isset($generated[$categoryId])) {
                    continue;
                }
                foreach ($fields as $field) {
                    if (!empty($generated[$categoryId][$field])) {
                        $result->setData(['success' => true]);
                        return $result;
                    }
                }
            }

            $result->setData([
                'success' => false,
                'message' => __(
                    'Transfer failed because there are no generated texts yet for the categories selected. '
                    . 'Generate text first before transferring.'
                )
            ]);
        } 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;
    }
}
