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

declare(strict_types=1);

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\CategoriesGrid;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Catalog\Model\CategoryFactory;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Controller\ResultFactory;
use Magento\Store\Model\Store;
use WriteTextAI\WriteTextAI\Helper\Categories\Fields as FieldsHelper;
use WriteTextAI\WriteTextAI\Model\AiCategoryManager;
use WriteTextAI\WriteTextAI\Model\Categories\GeneratedText;
use WriteTextAI\WriteTextAI\Model\Categories\ReviewStatus;

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

    /**
     * Constructor
     *
     * @param Context $context
     * @param GeneratedText $generatedText
     * @param FieldsHelper $fieldsHelper
     * @param CategoryFactory $categoryFactory
     * @param AiCategoryManager $aiCategoryManager
     * @param ReviewStatus $reviewStatus
     */
    public function __construct(
        Context $context,
        private readonly GeneratedText $generatedText,
        private readonly FieldsHelper $fieldsHelper,
        private readonly CategoryFactory $categoryFactory,
        private readonly AiCategoryManager $aiCategoryManager,
        private readonly ReviewStatus $reviewStatus
    ) {
        parent::__construct($context);
    }

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

        try {
            $fields = (array) $this->getRequest()->getPost('fields', []);
            $stores = (array) $this->getRequest()->getPost('stores', []);
            $queueIds = (array) $this->getRequest()->getPost('queue_ids', []);
            $filters = (array) $this->getRequest()->getPost('filters', []);

            $categoryId = (int) ($queueIds[0] ?? 0);
            $storeFilter = isset($filters['store_id'])
                ? (int) $filters['store_id']
                : (int) $this->getRequest()->getPost('store_id', Store::DEFAULT_STORE_ID);

            if ($categoryId <= 0) {
                $result->setData([
                    'success' => false,
                    'message' => __('Invalid category id.')
                ]);
                return $result;
            }

            $resultData = [
                'success' => false,
                'message' => __(
                    'Transfer failed because there are no generated texts yet for the categories selected. '
                    . 'Generate text first before transferring.'
                )
            ];

            $item = $this->generatedText->getTextFields($categoryId, $storeFilter, true);
            $mappingSettings = $this->fieldsHelper->getMappingSettings();

            $toUpdate = [];
            $selectedFieldsWithValues = [];
            foreach ($fields as $field) {
                if (!isset($mappingSettings[$field])) {
                    continue;
                }

                $value = $item[$field] ?? '';
                if ($value === '' || $value === null) {
                    continue;
                }

                $attributeCode = $mappingSettings[$field];
                $toUpdate[$attributeCode] = $value;
                $selectedFieldsWithValues[$field] = $value;
            }

            if (empty($toUpdate)) {
                $result->setData($resultData);
                return $result;
            }

            foreach ($stores as $storeId) {
                $category = $this->categoryFactory->create()
                    ->setStoreId((int) $storeId)
                    ->load($categoryId);

                foreach ($toUpdate as $attributeCode => $value) {
                    $category->setData($attributeCode, $value);
                    $category->getResource()->saveAttribute($category, $attributeCode);
                }

                $this->aiCategoryManager->saveDate($categoryId, (int) $storeId, 'transferred');
                $this->aiCategoryManager->saveDate($categoryId, (int) $storeId, 'reviewed');
            }

            $this->generatedText->saveCategoryText(
                $storeFilter,
                $categoryId,
                $selectedFieldsWithValues
            );

            $this->reviewStatus->updateReview(
                array_keys($selectedFieldsWithValues),
                $categoryId,
                $stores
            );

            $result->setData([
                'success' => true,
                'fields' => array_keys($selectedFieldsWithValues)
            ]);
        } catch (\WriteTextAI\WriteTextAI\Exception\UnauthorizedException $e) {
            $result->setData([
                'success' => false,
                'unauthorized' => true,
                'login_url' => $this->_url->getUrl('wtai/setup/index'),
                'message' => $e->getMessage()
            ]);
        } 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;
    }
}
