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

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Image;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use WriteTextAI\WriteTextAI\Helper\Product as ProductHelper;
use WriteTextAI\WriteTextAI\Helper\Store as StoreHelper;

class Get extends Action
{
    /**
     * @var ProductHelper
     */
    protected $productHelper;

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

    /**
     * Constructor
     *
     * @param Context $context
     * @param ProductHelper $productHelper
     * @param StoreHelper $storeHelper
     */
    public function __construct(
        Context $context,
        ProductHelper $productHelper,
        StoreHelper $storeHelper
    ) {
        $this->productHelper = $productHelper;
        $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()->getParam('product_id');
            $storeId = $this->getRequest()->getParam('store_id');

            $product = $this->productHelper->getProduct($productId, $storeId);
            
            $language = $this->storeHelper->getFormattedLanguage($storeId);

            $result = [
                'success' => true,
                'images' => $this->productHelper->getImages($product, $storeId, $language)
            ];
        } catch (\Exception $e) {
            $result = [
                'success' => false,
                'message' => __(
                    'A system error has occurred. Please try again. If the issue persists,'
                    . ' please contact our support team at support@writetext.ai.'
                ),
                'error' => $e->getMessage(),
                'trace' => $e->getTrace()
            ];
        }

        $response->setData($result);

        return $response;
    }
}
