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

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Edit\Mark;

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\Helper\Data;
use WriteTextAI\WriteTextAI\Model\OptionSource\Filter\Fields;
use WriteTextAI\WriteTextAI\Helper\Product as ProductHelper;
use WriteTextAI\WriteTextAI\Helper\Store as StoreHelper;
use WriteTextAI\WriteTextAI\Model\AiProductManager;

class Reviewed extends Action
{
    public const ADMIN_RESOURCE = 'WriteTextAI_WriteTextAI::review';

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

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

    /**
     * @var Data
     */
    protected $helper;

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

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

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

    /**
     * Constructor
     *
     * @param Context $context
     * @param ApiManager $apiManager
     * @param GeneratedText $generatedText
     * @param Data $helper
     * @param ProductHelper $productHelper
     * @param StoreHelper $storeHelper
     * @param AiProductManager $aiProductManager
     */
    public function __construct(
        Context $context,
        ApiManager $apiManager,
        GeneratedText $generatedText,
        Data $helper,
        ProductHelper $productHelper,
        StoreHelper $storeHelper,
        AiProductManager $aiProductManager
    ) {
        $this->apiManager = $apiManager;
        $this->generatedText = $generatedText;
        $this->helper = $helper;
        $this->productHelper = $productHelper;
        $this->storeHelper = $storeHelper;
        $this->aiProductManager = $aiProductManager;
        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');
            $reviewed = filter_var($this->getRequest()->getParam('reviewed'), FILTER_VALIDATE_BOOLEAN);

            $textsReviewed = $this->processTexts($productId, $storeId, $reviewed);
            $imagesReviewed = $this->processImages($productId, $storeId, $reviewed);

            if ($textsReviewed || $imagesReviewed) {
                $this->aiProductManager->saveDate($productId, $storeId, 'reviewed');
                $result = [
                    'success' => true
                ];
            } 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;
    }

    /**
     * Process text fields
     *
     * @param int $productId
     * @param int $storeId
     * @param bool $reviewed
     *
     * @return void
     */
    private function processTexts($productId, $storeId, $reviewed)
    {
        $ids = $this->generatedText->getTextIds($productId, $storeId);
        $textfields = $this->generatedText->getTextFields($productId, $storeId, true);

        if (!empty($ids)) {
            $fields = [];
            $fieldMappings = [
                'page_title' => Fields::PAGE_TITLE,
                'page_description' => Fields::PAGE_DESCRIPTION,
                'product_description' => Fields::PRODUCT_DESCRIPTION,
                'short_product_description' => Fields::EXCERPT,
                'open_graph' => Fields::OPEN_GRAPH,
            ];

            foreach ($fieldMappings as $key => $value) {
                if (isset($ids[$key]) &&
                    isset($textfields[$key]) &&
                    isset($textfields['status'][$key]) &&
                    !$textfields['status'][$key] &&
                    ($key != 'open_graph' || $this->helper->getCustomOpenGraph())
                ) {
                    $fields[] = [
                        "textId" => $ids[$key],
                        "field" => $value,
                        "platform" => "Magento",
                        "value" => $textfields[$key],
                        "reviewed" => $reviewed,
                        "publish" => false
                    ];
                }
            }

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

            $params = [
                'type' => 'Product',
                'language' => $language,
                'recordId' => $productId,
                'storeId' => $storeId,
                'fields' => $fields
            ];

            $this->apiManager->save($params);

            return true;
        } else {
            return false;
        }
    }

    /**
     * Process image alt texts
     *
     * @param int $productId
     * @param int $storeId
     * @param bool $reviewed
     *
     * @return void
     */
    private function processImages($productId, $storeId, $reviewed)
    {
        $language = $this->storeHelper->getFormattedLanguage($storeId);
        $product = $this->productHelper->getProduct($productId, $storeId);
        $images = $this->productHelper->getImages($product, $storeId, $language);

        if (empty($images)) {
            return false;
        }
        
        $imagesToUpdate = [];
        foreach ($images as $image) {
            if (empty($image['writetext_alt_id'])) {
                continue;
            }
            $imagesToUpdate[] = [
                "storeId" => $storeId,
                "language" => $language,
                "imageId" => $image['id'],
                "textId" => $image['writetext_alt_id'],
                "value" => $image['writetext_alt'],
                "reviewed" => $reviewed
            ];
        }

        if (empty($imagesToUpdate)) {
            return false;
        }

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

        return true;
    }
}
