<?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;
use WriteTextAI\WriteTextAI\Helper\Data;

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;

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

    /**
     * Execute
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $response = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        try {
            /** Handle JSON payload */
            $contentType = $this->getRequest()->getHeader('Content-Type');
            if ($contentType && strpos($contentType, 'application/json') !== false) {
                $content = $this->getRequest()->getContent();
                if ($content) {
                    /** Remove any trailing query parameters */
                    $lastBrace = strrpos($content, '}');
                    if ($lastBrace !== false && $lastBrace < strlen($content) - 1) {
                        $afterBrace = substr($content, $lastBrace + 1);
                        if (strpos($afterBrace, '&') === 0 || strpos($afterBrace, '?') === 0) {
                            $content = substr($content, 0, $lastBrace + 1);
                        }
                    }
                    
                    $jsonData = json_decode($content, true);
                    if (json_last_error() === JSON_ERROR_NONE && is_array($jsonData)) {
                        foreach ($jsonData as $key => $value) {
                            $this->getRequest()->setPostValue($key, $value);
                        }
                    }
                }
            }
            
            $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' => (string) $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;
            if ($this->helper->getForceQueueSeconds()) {
                $body['developmentQueueWaitTimeInSeconds'] = $this->helper->getForceQueueSeconds();
            }
            $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;
    }
}
