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

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Edit\KeywordsOptimization;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\HTTP\PhpEnvironment\RemoteAddress;
use WriteTextAI\WriteTextAI\Helper\Store as StoreHelper;
use WriteTextAI\WriteTextAI\Helper\Image;
use Magento\Backend\Model\UrlInterface;

class Upload extends Action
{
    /**
     * @var Image
     */
    protected $imageHelper;

    /**
     * @var UrlInterface
     */
    protected $urlBuilder;

    /**
     * @var RemoteAddress
     */
    protected $remoteAddress;

    /**
     * @var StoreHelper
     */
    protected $storeHelper;

    /**
     * Error message from api
     * @var string
     */
    protected $errorMessages = '';
    
    /**
     * Constructor
     *
     * @param Context $context
     * @param Image $imageHelper
     * @param UrlInterface $urlBuilder
     * @param RemoteAddress $remoteAddress
     * @param StoreHelper $storeHelper
     */
    public function __construct(
        Context $context,
        Image $imageHelper,
        UrlInterface $urlBuilder,
        RemoteAddress $remoteAddress,
        StoreHelper $storeHelper
    ) {
        $this->imageHelper = $imageHelper;
        $this->urlBuilder = $urlBuilder;
        $this->remoteAddress = $remoteAddress;
        $this->storeHelper = $storeHelper;
        parent::__construct($context);
    }

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

        try {
            $params = $this->getRequest()->getPost();

            $success = $this->uploadImage($params);

            $result = [
                'success' => $success
            ];
            if (!$success) {
                $result['error_messages'] = $this->errorMessages;
            }
        } 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;
    }

    /**
     * Upload image
     *
     * @param array $params
     * @return bool
     */
    private function uploadImage($params)
    {
        try {
            $this->imageHelper->uploadImage(
                $this->remoteAddress->getRemoteAddress(),
                $params['image'],
                [
                    "storeId" => $params['store_id'],
                    "language" => $this->storeHelper->getFormattedLanguage($params['store_id']),
                    "imageId" => $params['image_id']
                ],
                true
            );
            return true;
        } catch (\WriteTextAI\WriteTextAI\Exception\ImageUnsupported $e) {
            $this->errorMessages = $e->getMessage();
            return false;
        } catch (\WriteTextAI\WriteTextAI\Exception\ImageInvalid $e) {
            $this->errorMessages = $e->getMessage();
            return false;
        } catch (\WriteTextAI\WriteTextAI\Exception\ImageDownloadFailed $e) {
            $this->errorMessages = $e->getMessage();
            return false;
        } catch (\Exception $e) {
            $this->errorMessages = __('A system error has occurred. Please try'.
            ' again. If the issue persists, please contact our support team at support@writetext.ai.');
            return false;
        }
    }
}
