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

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Edit\Image;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use Magento\Catalog\Api\ProductRepositoryInterface;
use WriteTextAI\WriteTextAI\Model\AiProductManager;
use WriteTextAI\WriteTextAI\Helper\Product as ProductHelper;
use WriteTextAI\WriteTextAI\Model\ApiManager;
use WriteTextAI\WriteTextAI\Model\MarkReview;
use WriteTextAI\WriteTextAI\Helper\Store as StoreHelper;

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

    /**
     * @var AiProductManager
     */
    protected $aiProductManager;

    /**
     * @var ProductRepositoryInterface
     */
    protected $productRepository;

    /**
     * @var ProductHelper
     */
    protected $productHelper;

    /**
     * @var ApiManager
     */
    protected $apiManager;

    /**
     * @var MarkReview
     */
    protected $markReview;

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

    /**
     * Constructor
     *
     * @param Context $context
     * @param AiProductManager $aiProductManager
     * @param ProductRepositoryInterface $productRepository
     * @param ProductHelper $productHelper
     * @param ApiManager $apiManager
     * @param MarkReview $markReview
     * @param StoreHelper $storeHelper
     */
    public function __construct(
        Context $context,
        AiProductManager $aiProductManager,
        ProductRepositoryInterface $productRepository,
        ProductHelper $productHelper,
        ApiManager $apiManager,
        MarkReview $markReview,
        StoreHelper $storeHelper
    ) {
        $this->aiProductManager = $aiProductManager;
        $this->productRepository = $productRepository;
        $this->productHelper = $productHelper;
        $this->apiManager = $apiManager;
        $this->markReview = $markReview;
        $this->storeHelper = $storeHelper;
        parent::__construct($context);
    }

    /**
     * Execute
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $response = $this->resultFactory->create(ResultFactory::TYPE_JSON);
        
        try {
            $productId = $this->getRequest()->getPost('product_id');
            $selectedStores = $this->getRequest()->getPost('selected_stores', []);
            $image = $this->getRequest()->getPost('image');
            $storeFilter = $this->getRequest()->getPost('store_id');

            $language = $this->storeHelper->getFormattedLanguage($storeFilter);

            $imagesToUpdate = [];
            foreach ($selectedStores as $storeId) {
                $product = $this->productRepository->getById($productId, true, $storeId);
                $mediaGalleryEntries = $product->getMediaGalleryEntries();
                
                foreach ($mediaGalleryEntries as $mediaGalleryEntry) {
                    if ($mediaGalleryEntry->getId() == $image['id']) {
                        $mediaGalleryEntry->setLabel($image['writetext_alt']);
                        break;
                    }
                }

                try {
                    $getParams = [
                        "storeId" => $storeId,
                        "language" => $language,
                        "imageId" => $image['id']
                    ];
                    $altText = $this->apiManager->getImage($getParams);
                    if (isset($altText['altText']['id'])) {
                        $imagesToUpdate[] = [
                            "storeId" => $storeId,
                            "language" => $language,
                            "imageId" => $image['id'],
                            "textId" => $altText['altText']['id'],
                            "value" => $image['writetext_alt'],
                            "publish" => true,
                            "reviewed" => true
                        ];
                    }
                } catch (\WriteTextAI\WriteTextAI\Exception\ApiException $e) {
                    if ($e->getCode() !== 404) {
                        throw $e;
                    }
                }

                $product->setMediaGalleryEntries($mediaGalleryEntries);
                $this->productRepository->save($product);

                $this->aiProductManager->saveDate($productId, $storeId, 'transferred');
                $this->aiProductManager->saveDate($productId, $storeId, 'reviewed');
            }

            $this->apiManager->batchUpdateAltText(json_encode([
                "images" => $imagesToUpdate
            ]));

            $_product = $this->productRepository->getById($productId, false, $storeFilter);

            $result = [
                'success' => true,
                'reviewed' => $this->markReview->getReviewed($productId, $storeFilter),
                'images' => $this->productHelper->getImages($_product, $storeFilter, $language)
            ];
        } 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;
    }
}
