<?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\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Controller\ResultFactory;
use WriteTextAI\WriteTextAI\Model\ApiManager;
use WriteTextAI\WriteTextAI\Helper\Store as StoreHelper;
use Magento\Framework\Stdlib\DateTime\DateTime;
use WriteTextAI\WriteTextAI\Model\OptionSource\Filter\Fields;
use Magento\Framework\HTTP\PhpEnvironment\RemoteAddress;

class MassTransferViaApi extends Action implements HttpPostActionInterface
{
    public const ADMIN_RESOURCE = 'WriteTextAI_WriteTextAI::transfer';
    
    /**
     * @var ApiManager
     */
    protected $apiManager;
    
    /**
     * @var StoreHelper
     */
    protected $storeHelper;
    
    /**
     * @var DateTime
     */
    protected $dateTime;

    /**
     * @var RemoteAddress
     */
    protected $remoteAddress;
    
    /**
     * Constructor
     *
     * @param Context $context
     * @param ApiManager $apiManager
     * @param StoreHelper $storeHelper
     * @param DateTime $dateTime
     * @param RemoteAddress $remoteAddress
     */
    public function __construct(
        Context $context,
        ApiManager $apiManager,
        StoreHelper $storeHelper,
        DateTime $dateTime,
        RemoteAddress $remoteAddress
    ) {
        parent::__construct($context);
        $this->apiManager = $apiManager;
        $this->storeHelper = $storeHelper;
        $this->dateTime = $dateTime;
        $this->remoteAddress = $remoteAddress;
    }

    /**
     * Execute
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $response = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        try {
            $params = $this->getRequest()->getParams();
            
            $mapping = [
                'page_title' => Fields::PAGE_TITLE,
                'page_description' => Fields::PAGE_DESCRIPTION,
                'product_description' => Fields::PRODUCT_DESCRIPTION,
                'short_product_description' => Fields::EXCERPT,
                'open_graph' => Fields::OPEN_GRAPH,
            ];

            $storeId = $params['store_id'] ?? '0';
            $body = [
                'type' => 'Product',
                'storeId' => $storeId,
                'userName' => $params['user'] ?? '',
            ];

            $language = $this->storeHelper->getFormattedLanguage($storeId);
            $body['language'] = $language;
            $body['ipAddress'] = $this->remoteAddress->getRemoteAddress();
            $body['targetStoreId'] = implode(',', $params['stores']);

            $mappedFields = [];
            $isAltText = false;
            foreach ($params['fields'] as $field) {
                if ($field == 'alt_text') {
                    $isAltText = true;
                    continue;
                }
                $mappedFields[] = $mapping[$field];
            }
            $records = [];
            foreach ($params['queue_ids'] as $record) {
                $recordData = [
                    "id" => $record,
                    "fields" => $mappedFields
                ];
                if ($isAltText) {
                    $recordData['imageIds'] = ['all'];
                }
                $records[] = $recordData;
            }
            
            $body['records'] = $records;
            $apiResponse = $this->apiManager->transferViaApi($body);
            $result = [
                'success' => true,
                'api_params' => $body,
                'api_response' => $apiResponse
            ];
        } catch (\WriteTextAI\WriteTextAI\Exception\UnauthorizedException $e) {
            $result = [
                'success' => false,
                'unauthorized' => true,
                'login_url' => $this->urlBuilder->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 = [
                'success' => false,
                'message' => $message
            ];
        }

        $response->setData($result);

        return $response;
    }
}
