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

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Categories\Image;

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;

    /**
     * @var array
     */
    protected $errorMessages = [];

    /**
     * @var array
     */
    protected $invalidImages = [];

    /**
     * @var array
     */
    protected $notSupportedImages = [];

    /**
     * @var array
     */
    protected $downloadFailedImages = [];

    /**
     * @var array
     */
    protected $generalImages = [];

    /**
     * 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();

            $categoryImageUpload = true;
            if (isset($params['category_image'])) {
                $categoryImageUpload = $this->uploadCategoryImage($params);
            }

            $productImagesUpload = $this->uploadProductImages($params);

            $result = [
                'success' => empty($failedImages),
                'category_image' => $categoryImageUpload,
                'products' => $productImagesUpload,
                'invalid' => $this->invalidImages,
                'not_supported' => $this->notSupportedImages,
                'download_failed' => $this->downloadFailedImages,
                'general' => $this->generalImages,
                '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 category image
     *
     * @param array $params
     * @return bool
     */
    private function uploadCategoryImage($params)
    {
        try {
            $categoryImageId = $this->imageHelper->getCategoryImageId(
                $params['category_id'],
                $params['store_id'],
                $params['category_image']
            );
            $this->imageHelper->uploadImage(
                $this->remoteAddress->getRemoteAddress(),
                $params['category_image'],
                [
                    "storeId" => $params['store_id'],
                    "language" => $this->storeHelper->getFormattedLanguage($params['store_id']),
                    "imageId" => $categoryImageId
                ],
                true
            );
            return true;
        } catch (\WriteTextAI\WriteTextAI\Exception\ImageUnsupported $e) {
            $this->errorMessages['unsupported'] = $e->getMessage();
            $this->notSupportedImages[] = [
                'id' => $categoryImageId,
                'url' => $params['category_image']
            ];
            return false;
        } catch (\WriteTextAI\WriteTextAI\Exception\ImageInvalid $e) {
            $this->errorMessages['invalid'] = $e->getMessage();
            $this->invalidImages[] = [
                'id' => $categoryImageId,
                'url' => $params['category_image']
            ];
            return false;
        } catch (\WriteTextAI\WriteTextAI\Exception\ImageDownloadFailed $e) {
            $this->errorMessages['download_failed'] = $e->getMessage();
            $this->downloadFailedImages[] = [
                'id' => $categoryImageId,
                'url' => $params['category_image']
            ];
            return false;
        } catch (\Exception $e) {
            $this->errorMessages['general'] = __('A system error has occurred. Please try again.'
                . ' If the issue persists, please contact our support team at support@writetext.ai.');
            $this->generalImages[] = [
                'id' => $categoryImageId,
                'url' => $params['category_image']
            ];
            return false;
        }
    }

    /**
     * Upload product images
     *
     * @param array $params
     * @return array
     */
    private function uploadProductImages($params)
    {
        $success = [];
        $failed = [];
        if (isset($params['products']) && !empty($params['products'])) {
            foreach ($params['products'] as $product) {
                if (!$product['image_id']) {
                    continue;
                }

                try {
                    $this->imageHelper->getImageApiId(
                        $params['store_id'],
                        $this->remoteAddress->getRemoteAddress(),
                        $this->storeHelper->getFormattedLanguage($params['store_id']),
                        $product['image_id'],
                        $product['image']
                    );
                    $success[] = $product;
                } catch (\WriteTextAI\WriteTextAI\Exception\ImageUnsupported $e) {
                    $failed[] = $product;
                    $this->errorMessages['unsupported'] = $e->getMessage();
                    $this->notSupportedImages[] = [
                        'id' => $product['image_id'],
                        'url' => $product['image']
                    ];
                } catch (\WriteTextAI\WriteTextAI\Exception\ImageInvalid $e) {
                    $failed[] = $product;
                    $this->errorMessages['invalid'] = $e->getMessage();
                    $this->invalidImages[] = [
                        'id' => $product['image_id'],
                        'url' => $product['image']
                    ];
                } catch (\WriteTextAI\WriteTextAI\Exception\ImageDownloadFailed $e) {
                    $failed[] = $product;
                    $this->errorMessages['download_failed'] = $e->getMessage();
                    $this->downloadFailedImages[] = [
                        'id' => $product['image_id'],
                        'url' => $product['image']
                    ];
                } catch (\Exception $e) {
                    $failed[] = $product;
                    $this->errorMessages['general'] = __('A system error has occurred. Please try'.
                    ' again. If the issue persists, please contact our support team at support@writetext.ai.');
                    $this->generalImages[] = [
                        'id' => $product['image_id'],
                        'url' => $product['image']
                    ];
                }
            }
        }

        return [
            'failed' => $failed,
            'success' => $success
        ];
    }
}
