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

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Edit;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use WriteTextAI\WriteTextAI\Model\ApiManager;
use WriteTextAI\WriteTextAI\Model\GeneratedText;
use WriteTextAI\WriteTextAI\Model\AiProductManager;
use WriteTextAI\WriteTextAI\Model\OptionSource\Filter\Fields;
use WriteTextAI\WriteTextAI\Helper\Store as StoreHelper;

class Save extends Action
{
    public const ADMIN_RESOURCE = 'WriteTextAI_WriteTextAI::edit';

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

    /**
     * @var GeneratedText
     */
    protected $generatedText;

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

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

    /**
     * Constructor
     *
     * @param Context $context
     * @param ApiManager $apiManager
     * @param GeneratedText $generatedText
     * @param AiProductManager $aiProductManager
     * @param StoreHelper $storeHelper
     */
    public function __construct(
        Context $context,
        ApiManager $apiManager,
        GeneratedText $generatedText,
        AiProductManager $aiProductManager,
        StoreHelper $storeHelper
    ) {
        $this->apiManager = $apiManager;
        $this->generatedText = $generatedText;
        $this->aiProductManager = $aiProductManager;
        $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');
            $pageTitle = $this->getRequest()->getParam('page_title');
            $pageDescription = $this->getRequest()->getParam('page_description');
            $productDescription = $this->getRequest()->getParam('product_description');
            $productShortDescription = $this->getRequest()->getParam('product_short_description');
            $openGraph = $this->getRequest()->getParam('open_graph');
            $updatedFields = $this->getRequest()->getParam('update_fields', []);

            $ids = $this->generatedText->getTextIds($productId, $storeId);

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

            $images = $this->saveImages($storeId, $language);

            if (!empty($ids) || !empty($images)) {
                $apiResponse = [];
                
                if (!empty($ids)) {
                    $fields = [];
                    $fieldMapping = [
                        'page_title' => [
                            'id' => isset($ids['page_title']) ? $ids['page_title'] : null,
                            'field' => Fields::PAGE_TITLE,
                            'value' => $pageTitle
                        ],
                        'page_description' => [
                            'id' => isset($ids['page_description']) ? $ids['page_description'] : null,
                            'field' => Fields::PAGE_DESCRIPTION,
                            'value' => $pageDescription
                        ],
                        'product_description' => [
                            'id' => isset($ids['product_description']) ? $ids['product_description'] : null,
                            'field' => Fields::PRODUCT_DESCRIPTION,
                            'value' => $productDescription
                        ],
                        'short_product_description' => [
                            'id' => isset($ids['short_product_description']) ? $ids['short_product_description'] : null,
                            'field' => Fields::EXCERPT,
                            'value' => $productShortDescription
                        ],
                        'open_graph' => [
                            'id' => isset($ids['open_graph']) ? $ids['open_graph'] : null,
                            'field' => Fields::OPEN_GRAPH,
                            'value' => $openGraph
                        ],
                    ];
                    foreach ($fieldMapping as $key => $value) {
                        if ($value['id'] === null) {
                            continue;
                        }

                        if (!in_array($key, $updatedFields)) {
                            continue;
                        }
                        
                        $fields[] = [
                            "textId" => $value['id'],
                            "field" => $value['field'],
                            "value" => $value['value'],
                            "platform" => "Magento",
                            "publish" => false,
                            "reviewed" => false
                        ];
                    }
                
                    $params = [
                        'type' => 'Product',
                        'language' => $language,
                        'recordId' => $productId,
                        'storeId' => $storeId,
                        'fields' => $fields
                    ];
        
                    $apiResponse = $this->apiManager->save($params);
        
                    $this->aiProductManager->saveDate($productId, $storeId, 'edited');
                }
    
                $result = [
                    'success' => true,
                    'response' => $apiResponse,
                    'params' => $params ?? [],
                    'images' => $images,
                    'textfields_statuses' => $this->generatedText->getTextFieldsStatuses($productId, $storeId)
                ];
            } else {
                $result = [
                    'success' => false,
                    'message' => __("You haven't generated any text yet.")
                ];
            }
        } 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;
    }

    /**
     * Save images
     *
     * @param int $storeId
     * @param string $language
     * @return array
     */
    protected function saveImages($storeId, $language)
    {
        $images = $this->getRequest()->getParam('images', []);
        $images = json_decode($images, true);

        foreach ($images as &$image) {
            /**
             * Convert back to boolean
             */
            if (isset($image['status']['generated'])) {
                $image['status']['generated'] = filter_var($image['status']['generated'], FILTER_VALIDATE_BOOLEAN);
            }
            if (isset($image['status']['transferred'])) {
                $image['status']['transferred'] = filter_var($image['status']['transferred'], FILTER_VALIDATE_BOOLEAN);
            }

            if (!$image['writetext_alt_id'] || !$image['writetext_alt']) {
                continue;
            }

            if ($image['original_writetext_alt'] === $image['writetext_alt']) {
                continue;
            }

            $saveParams = [
                "storeId" => $storeId,
                "language" => $language,
                "imageId" => $image['id'],
                "textId" => $image['writetext_alt_id'],
                "value" => $image['writetext_alt'],
                //"publish" => true
            ];
            $resultImage = $this->apiManager->updateAltText(json_encode($saveParams));

            $image['original_writetext_alt'] = $image['writetext_alt'];
        }
        return $images;
    }
}
