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

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Grid;

use Magento\Backend\App\Action;
use WriteTextAI\WriteTextAI\Controller\Adminhtml\Grid\MassGenerate;
use Magento\Backend\App\Action\Context;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Data\Form\FormKey;
use Magento\Framework\HTTP\PhpEnvironment\RemoteAddress;
use Magento\Store\Model\ScopeInterface;
use Magento\Ui\Component\MassAction\Filter;
use WriteTextAI\WriteTextAI\Helper\Data;
use WriteTextAI\WriteTextAI\Ui\Component\MassAction\JsonFilter;
use WriteTextAI\WriteTextAI\Helper\Generate as GenerateHelper;
use WriteTextAI\WriteTextAI\Model\ApiManager;
use WriteTextAI\WriteTextAI\Model\Config\Source\ProductAttributes;
use WriteTextAI\WriteTextAI\Model\OptionSource\Filter\Fields;
use Magento\Catalog\Api\ProductRepositoryInterface;
use WriteTextAI\WriteTextAI\Model\AiProductManager;
use WriteTextAI\WriteTextAI\Model\Config\Source\ProductAttributes\Excluded;
use Magento\Customer\Api\GroupRepositoryInterface;
use Magento\Customer\Api\Data\GroupInterface;
use Magento\Catalog\Helper\Output as OutputHelper;
use WriteTextAI\WriteTextAI\Helper\Html as HtmlHelper;
use Magento\Framework\Filter\FilterManager;
use Magento\Backend\Model\UrlInterface;
use WriteTextAI\WriteTextAI\ViewModel\Premium;
use WriteTextAI\WriteTextAI\ViewModel\Settings;
use WriteTextAI\WriteTextAI\ViewModel\UserFieldsSelected;
use Magento\Catalog\Helper\Image as ImageHelper;
use WriteTextAI\WriteTextAI\Helper\Image as WTAImageHelper;
use Magento\Eav\Model\ResourceModel\Entity\Attribute\CollectionFactory as AttributeCollectionFactory;
use WriteTextAI\WriteTextAI\Model\BulkGenerateRequestsManager;
use WriteTextAI\WriteTextAI\Model\FullAutomationRequestsManager;
use WriteTextAI\WriteTextAI\Model\BulkKeywordAnalysisRequestsManager;
use WriteTextAI\WriteTextAI\Model\Api\Session as ApiSession;
use Magento\Framework\Escaper;
use Magento\Framework\Exception\FileSystemException;
use WriteTextAI\WriteTextAI\Model\BulkTransferRequestsManager;
use Magento\Store\Model\Store;
use WriteTextAI\WriteTextAI\Helper\Store as StoreHelper;
use WriteTextAI\WriteTextAI\Model\Api\Keywords;
use WriteTextAI\WriteTextAI\Model\Config\Source\AutomaticTextOptimization;
use WriteTextAI\WriteTextAI\Helper\Product as ProductHelper;
use WriteTextAI\WriteTextAI\Helper\Fields as FieldHelper;
use WriteTextAI\WriteTextAI\ViewModel\Permissions;

class MassFullAutomation extends MassGenerate implements HttpPostActionInterface
{
    public const ADMIN_RESOURCE = 'WriteTextAI_WriteTextAI::generate';

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

    /**
     * @var RemoteAddress
     */
    protected $remoteAddress;

    /**
     * @var ScopeConfigInterface
     */
    protected $scopeConfig;
    
    /**
     * @var JsonFilter
     */
    protected $filter;

    /**
     * @var CollectionFactory
     */
    protected $collectionFactory;

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

    /**
     * @var FormKey
     */
    protected $formKey;

    /**
     * @var ProductAttributes
     */
    protected $productAttributes;

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

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

    /**
     * @var GroupRepositoryInterface
     */
    protected $groupRepository;

    /**
     * @var OutputHelper
     */
    protected $outputHelper;

    /**
     * @var GenerateHelper
     */
    protected $generateHelper;

    /**
     * @var HtmlHelper
     */
    protected $htmlHelper;

    /**
     * @var FilterManager
     */
    protected $filterManager;

    /**
     * @var Escaper
     */
    protected $escaper;

    /**
     * @var UrlInterface
     */
    protected $urlBuilder;

    /**
     * @var Premium
     */
    protected $premium;

    /**
     * @var Settings
     */
    protected $settings;

    /**
     * @var UserFieldsSelected
     */
    protected $userFieldsSelected;

    /**
     * @var ImageHelper
     */
    protected $imageHelper;

    /**
     * @var WTAImageHelper
     */
    protected $wtaImageHelper;

    /**
     * @var AttributeCollectionFactory
     */
    protected $attributeCollectionFactory;

    /**
     * @var BulkGenerateRequestsManager
     */
    protected $bulkGenerateRequestsManager;

    /**
     * @var FullAutomationRequestsManager
     */
    protected $fullAutomationRequestsManager;

    /**
     * @var BulkKeywordAnalysisRequestsManager
     */
    protected $bulkKeywordAnalysisRequestsManager;

    /**
     * @var ApiSession
     */
    protected $apiSession;

    /**
     * @var BulkTransferRequestsManager
     */
    protected $BulkTransferRequestsManager;

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

    /**
     * @var Keywords
     */
    protected $keywords;

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

    /**
     * @var FieldHelper
     */
    protected $fieldHelper;

    /**
     * @var Permissions
     */
    protected $permissions;

    /**
     * Constructor
     *
     * @param Context $context
     * @param ApiManager $apiManager
     * @param RemoteAddress $remoteAddress
     * @param ScopeConfigInterface $scopeConfig
     * @param JsonFilter $filter
     * @param CollectionFactory $collectionFactory
     * @param Data $helper
     * @param FormKey $formKey
     * @param ProductAttributes $productAttributes
     * @param ProductRepositoryInterface $productRepository
     * @param AiProductManager $aiProductManager
     * @param GroupRepositoryInterface $groupRepository
     * @param OutputHelper $outputHelper
     * @param GenerateHelper $generateHelper
     * @param HtmlHelper $htmlHelper
     * @param FilterManager $filterManager
     * @param Escaper $escaper
     * @param UrlInterface $urlBuilder
     * @param Premium $premium
     * @param Settings $settings
     * @param UserFieldsSelected $userFieldsSelected
     * @param ImageHelper $imageHelper
     * @param WTAImageHelper $wtaImageHelper
     * @param AttributeCollectionFactory $attributeCollectionFactory
     * @param BulkGenerateRequestsManager $bulkGenerateRequestsManager
     * @param FullAutomationRequestsManager $fullAutomationRequestsManager
     * @param BulkKeywordAnalysisRequestsManager $bulkKeywordAnalysisRequestsManager
     * @param ApiSession $apiSession
     * @param BulkTransferRequestsManager $BulkTransferRequestsManager
     * @param StoreHelper $storeHelper
     * @param Keywords $keywords
     * @param ProductHelper $productHelper
     * @param FieldHelper $fieldHelper
     * @param Permissions $permissions
     */
    public function __construct(
        Context $context,
        ApiManager $apiManager,
        RemoteAddress $remoteAddress,
        ScopeConfigInterface $scopeConfig,
        JsonFilter $filter,
        CollectionFactory $collectionFactory,
        Data $helper,
        FormKey $formKey,
        ProductAttributes $productAttributes,
        ProductRepositoryInterface $productRepository,
        AiProductManager $aiProductManager,
        GroupRepositoryInterface $groupRepository,
        OutputHelper $outputHelper,
        GenerateHelper $generateHelper,
        HtmlHelper $htmlHelper,
        FilterManager $filterManager,
        Escaper $escaper,
        UrlInterface $urlBuilder,
        Premium $premium,
        Settings $settings,
        UserFieldsSelected $userFieldsSelected,
        ImageHelper $imageHelper,
        WTAImageHelper $wtaImageHelper,
        AttributeCollectionFactory $attributeCollectionFactory,
        BulkGenerateRequestsManager $bulkGenerateRequestsManager,
        FullAutomationRequestsManager $fullAutomationRequestsManager,
        BulkKeywordAnalysisRequestsManager $bulkKeywordAnalysisRequestsManager,
        ApiSession $apiSession,
        BulkTransferRequestsManager $BulkTransferRequestsManager,
        StoreHelper $storeHelper,
        Keywords $keywords,
        ProductHelper $productHelper,
        FieldHelper $fieldHelper,
        Permissions $permissions
    ) {
        $this->apiManager = $apiManager;
        $this->remoteAddress = $remoteAddress;
        $this->scopeConfig = $scopeConfig;
        $this->filter = $filter;
        $this->collectionFactory = $collectionFactory;
        $this->helper = $helper;
        $this->formKey = $formKey;
        $this->productAttributes = $productAttributes;
        $this->productRepository = $productRepository;
        $this->aiProductManager = $aiProductManager;
        $this->groupRepository = $groupRepository;
        $this->outputHelper = $outputHelper;
        $this->generateHelper = $generateHelper;
        $this->htmlHelper = $htmlHelper;
        $this->filterManager = $filterManager;
        $this->escaper = $escaper;
        $this->urlBuilder = $urlBuilder;
        $this->premium = $premium;
        $this->settings = $settings;
        $this->userFieldsSelected = $userFieldsSelected;
        $this->imageHelper = $imageHelper;
        $this->wtaImageHelper = $wtaImageHelper;
        $this->attributeCollectionFactory = $attributeCollectionFactory;
        $this->bulkGenerateRequestsManager = $bulkGenerateRequestsManager;
        $this->fullAutomationRequestsManager = $fullAutomationRequestsManager;
        $this->bulkKeywordAnalysisRequestsManager = $bulkKeywordAnalysisRequestsManager;
        $this->apiSession = $apiSession;
        $this->BulkTransferRequestsManager = $BulkTransferRequestsManager;
        $this->storeHelper = $storeHelper;
        $this->keywords = $keywords;
        $this->productHelper = $productHelper;
        $this->fieldHelper = $fieldHelper;
        $this->permissions = $permissions;

        parent::__construct(
            $context,
            $apiManager,
            $remoteAddress,
            $scopeConfig,
            $filter,
            $collectionFactory,
            $helper,
            $formKey,
            $productAttributes,
            $productRepository,
            $aiProductManager,
            $groupRepository,
            $outputHelper,
            $generateHelper,
            $htmlHelper,
            $filterManager,
            $escaper,
            $urlBuilder,
            $settings,
            $userFieldsSelected,
            $imageHelper,
            $wtaImageHelper,
            $attributeCollectionFactory,
            $bulkGenerateRequestsManager,
            $fullAutomationRequestsManager,
            $bulkKeywordAnalysisRequestsManager,
            $apiSession,
            $BulkTransferRequestsManager,
            $storeHelper,
            $keywords,
            $productHelper,
            $fieldHelper
        );
    }

    /**
     * Execute
     *
     * @return \Magento\Framework\Controller\Result\Json
     */
    public function execute()
    {
        $response = $this->resultFactory->create(ResultFactory::TYPE_JSON);

        if (!$this->premium->getHasProAccess()) {
            $response->setData([
                'success' => false,
                'reload' => true,
                'message' => __('Premium is required to do this action.')
            ]);

            return $response;
        }
        
        try {
            $uploadedImages = $this->getRequest()->getPost('uploaded_images', []);
            $selectedFields = $this->getRequest()->getPost('fields');
            $skipImages = $this->getRequest()->getPost('skip_images', []);
            $skipThumbnails = $this->getRequest()->getPost('skip_thumbnails', []);
            $tones = $this->getRequest()->getPost('tones', explode(",", (string) $this->helper->getTones()));
            $style = $this->getRequest()->getPost('styles', (string) $this->helper->getStyles());
            $customTone = $this->getRequest()->getPost('custom_tone', "");
            $customStyle = $this->getRequest()->getPost('custom_style', "");
            $audience = $this->getRequest()->getPost('audience');
            $attributes = $this->getRequest()->getPost('attributes', []);
            $otherDetails = $this->getRequest()->getPost('product_details');
            $pageTitleTemplate = $this->getRequest()->getPost('wtai_template_page_title');
            $productDescriptionTemplate = $this->getRequest()->getPost('wtai_template_product_description');
            $shortProductDescriptionTemplate = $this->getRequest()->getPost('wtai_template_short_product_description');
            $voiceAndStyleMethod = $this->getRequest()->getPost('voice_and_style_method', 'manual');
            $useAiModel = $voiceAndStyleMethod === 'ai_model';
            $selectedAiModel = $this->getRequest()->getPost('wtai_selected_ai_model', '');
            
            $descriptionMin = $this->getRequest()->getPost(
                'description_min',
                $this->helper->getDescriptionSettings('min')
            );
            $descriptionMax = $this->getRequest()->getPost(
                'description_max',
                $this->helper->getDescriptionSettings('max')
            );
            $excerptMin = $this->getRequest()->getPost('excerpt_min', $this->helper->getExcerptSettings('min'));
            $excerptMax = $this->getRequest()->getPost('excerpt_max', $this->helper->getExcerptSettings('max'));
            $filters = $this->getRequest()->getPost('filters', []);

            $storeId = isset($filters['store_id']) ? $filters['store_id'] : Store::DEFAULT_STORE_ID;
            
            $mappingSettings = $this->helper->getMappingSettings();

            $country =  $this->scopeConfig->getValue(
                'general/country/default',
                ScopeInterface::SCOPE_STORE,
                $storeId
            );
            $language = $this->storeHelper->getFormattedLanguage($storeId);
            $ipAddress = $this->remoteAddress->getRemoteAddress();

            $rules = $this->settings->getSettings('rules');
            $maxOutputWords = $rules['maxOutputWords'] ?? '';
            $maxReferenceTextLength = $rules['maxReferenceTextLength'] ?? '';
            $additionalReferenceTextLength = $rules['additionalReferenceTextLength'] ?? '';
            $maxAttributes = $rules['maxAttributes'] ?? '';
            $maxAttributeValueLength = $rules['maxAttributeValueLength'] ?? '';

            $credits = $this->settings->getSettings('credits');
            $wordsPerCredit = $credits['wordsPerCredit'] ?? '';
            
            $maxInputChar = ((($maxOutputWords / $wordsPerCredit) - 1) * $additionalReferenceTextLength)
                + $maxReferenceTextLength;

            $texts = [];
            $collection = $this->filter->getCollection($this->collectionFactory
                    ->create()
                    ->addAttributeToSelect('*'))
                    ->setStoreId($storeId)
                    ->addMediaGalleryData();

            $frontendStoreId = $this->storeHelper->getFrontendStoreId($storeId);
            $isProductResearchDataSelected = false;
            $fetchImages = false;
            $withAltTextGeneration = false;
            foreach ($collection as $product) {
                $attributesData = [];
                $images = [];
                $productId = $product->getId();
                $productName = $this->outputHelper->productAttribute(
                    $product,
                    $product->getName(),
                    'name'
                );
                //$productAttributes = $this->getProductAttributes($product, $attributes);
                foreach ($attributes as $attribute) {
                    if (strtolower($attribute)
                        === ProductAttributes::PRODUCT_RESEARCH_DATA_ATTRIBUTE_CODE
                    ) {
                        $isProductResearchDataSelected = true;
                        continue;
                    }

                    /*if ($maxAttributes <= count($attributesData)) {
                        break;
                    }*/
                    
                    if (strtolower($attribute) === 'thumbnail') {
                        $fetchImages = true;
                    }
                }

                // fields to generate
                $fieldNames = [
                    '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
                ];

                $templatesUsed = [
                    'page_title' => $pageTitleTemplate,
                    'product_description' => $productDescriptionTemplate,
                    'short_product_description' => $shortProductDescriptionTemplate
                ];

                $fields = [];
                foreach ($fieldNames as $fieldName => $fieldConstant) {
                    if (in_array($fieldName, $selectedFields)) {
                        $field = [
                            "field" => $fieldConstant
                        ];

                        if ($fieldName == 'product_description') {
                            $field["minWords"] = $descriptionMin;
                            $field["maxWords"] = $descriptionMax;
                        } elseif ($fieldName == 'short_product_description') {
                            $field["minWords"] = $excerptMin;
                            $field["maxWords"] = $excerptMax;
                        }

                        if (isset($templatesUsed[$fieldName]) && $templatesUsed[$fieldName]) {
                            $field['templateId'] = $templatesUsed[$fieldName];
                        }
                        
                        $fields[] = $field;
                    }
                }

                $_product = $product;

                $textData = [
                    "name" => $productName,
                    "recordId" => $productId,
                    "sku" => $product->getSku(),
                    // "options" => 1,
                    // "autoselectFirst" => true,
                    // "attributes" => $attributesData,
                    // "enableResearch" => $isProductResearchDataSelected,
                    "fields" => $fields,
                    "url" => $_product->setStoreId($frontendStoreId)->getUrlInStore()
                ];

                // if (filter_var($useAiModel, FILTER_VALIDATE_BOOLEAN)) {
                //     $textData['brandVoiceId'] = $selectedAiModel;
                // }
                //$galleryImages = $this->productHelper->getImages($product, $storeId, $language);

                if (in_array('product_description', $selectedFields)
                    || in_array('short_product_description', $selectedFields)
                ) {
                    $fetchImages = true;
                    // $imageUrls = $this->getImageUrls($galleryImages);
                    // if (isset($imageUrls['main_image']) && $imageUrls['main_image']) {
                    //     $textData['featuredImage'] = $imageUrls['main_image'];
                    // }
                    // if (isset($imageUrls['gallery_images']) && $imageUrls['gallery_images']) {
                    //     $textData['galleryImages'] = $imageUrls['gallery_images'];
                    // }
                }

                // if (!empty($images)) {
                //     $textData["images"] = $images;
                // }
                
                if (in_array('alt_text', $selectedFields)) {
                    $fetchImages = true;
                    $withAltTextGeneration  = true;
                    // $altTexts = $this->getAltTextParams($product, $galleryImages, $skipImages);
                    // if (!empty($altTexts)) {
                    //     $textData["imageAltTexts"] = $altTexts;
                    // }
                }

                // if (!empty($audience)) {
                //     $textData['audiences'] = $audience;
                // }

                $autoOptimizeKeywords = filter_var(
                    $this->getRequest()->getPost('auto_optimize_keywords'),
                    FILTER_VALIDATE_BOOLEAN
                );
                $keywords = null;

                if (!empty($fields) || $withAltTextGeneration) {
                    $texts[] = $textData;
                }
            }
            $forPublishing = filter_var(
                $this->getRequest()->getPost('transfer_to_magento'),
                FILTER_VALIDATE_BOOLEAN
            );

            // Check transfer permissions before allowing publishing
            if ($forPublishing && !$this->permissions->isTransferAllowed()) {
                $forPublishing = false;
            }

            // if ($forPublishing) {
            //     $tokenTime = $this->apiManager->getTokenTime();
            //     if (!$tokenTime) {
            //         $configScheduledCronTime = $this->helper->getAutotransferSettings('cron_schedule');
            //         $cronTime = $this->helper->cronToTime($configScheduledCronTime);
            //         $tokenTime = $this->helper->convertToConfigTimezone($cronTime);
            //         $bodyTokenTime = [
            //             'time' => $tokenTime
            //         ];
            //         $tokenTimeResponse = $this->apiManager->sendTokenTime($bodyTokenTime);
            //     }
            // }

            $params = [
                "type" => "Product",
                "forPublishing" => $forPublishing,
                "storeId" => (string) $storeId,
                "language" => $language,
                "countries" => [$country],
                "ipAddress" => $ipAddress,
                "keywordOptimization" => $this->getKeywordOptimizationParams($country),
                "texts" => $texts,
                "fetchImages" => $fetchImages,
                "withAltTextGeneration" => $withAltTextGeneration,
                "fetchRecordData" => [
                    "attributes" => $attributes
                ],
                "generationParameters" => [
                    "enableResearch" => $isProductResearchDataSelected
                ]
            ];

            if (filter_var($useAiModel, FILTER_VALIDATE_BOOLEAN)) {
                 $params['generationParameters']['brandVoiceId'] = $selectedAiModel;
            }

            if (!$useAiModel) {
               
                if (in_array('custom', $tones)) {
                    $params['generationParameters']['customTone'] = $customTone;
                } else {
                    $params['generationParameters']['tones'] = $tones;
                }

                if ($style == 'custom') {
                    $params['generationParameters']['customStyle'] = $customStyle;
                } else {
                    $params['generationParameters']['style'] = $style;
                }

                if (!empty($audience)) {
                    $params['generationParameters']['audiences'] = $audience;
                }
            }

            $autoOptimizeKeywords = filter_var(
                $this->getRequest()->getPost('auto_optimize_keywords'),
                FILTER_VALIDATE_BOOLEAN
            );
            $keywordOpParams = $this->getKeywordOptimizationParams($country);
            if (!empty($keywordOpParams)) {
                $params['keywordOptimization'] = $keywordOpParams;
                $params['development'] = filter_var($this->helper->getKoDev(), FILTER_VALIDATE_BOOLEAN);
            }
            if ($this->helper->getForceQueueSeconds()) {
                $params['developmentQueueWaitTimeInSeconds'] = $this->helper->getForceQueueSeconds();
            }

            if ($otherDetails) {
                $params['specialInstructions'] = $otherDetails;
            }
            
            $singleRecordId = null;
            if (count($texts) === 1 && $autoOptimizeKeywords) {
                $singleRecordId = $texts[0]['recordId'];
            }

            if (count($texts) < 2) {
                $params['queue'] = true;
            }
            
            $params = json_encode($params, JSON_INVALID_UTF8_IGNORE);
            $apiResponse = $this->apiManager->generate($params);

            //$this->saveBulkRequest($apiResponse, $singleRecordId);

            foreach ($collection as $product) {
                $this->aiProductManager->saveDate($product->getId(), $storeId, 'generated');
                $this->aiProductManager->saveDate($product->getId(), $storeId, 'edited');
            }

            $result = [
                'success' => true,
                'form_key' => $this->formKey->getFormKey(),
                'params' => $params,
                'api_response' => $apiResponse
            ];
        } 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) {
            $errorMessage = $e->getMessage();
            if (strpos($errorMessage, 'Images with Ids') !== false &&
                strpos($errorMessage, 'have not been uploaded yet') !== false
            ) {
                $errorMessage = __("A system error has occurred. Please refresh the page and try again."
                . " If the issue persists, please contact our support team at support@writetext.ai.");
            }

            if (!$errorMessage) {
                $errorMessage = __(
                    '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' => $errorMessage,
                'params' => $params ?? []
            ];
        }

        $response->setData($result);

        return $response;
    }

    /**
     * Get keyword optimization params
     *
     * @param string $country
     * @return array
     */
    protected function getKeywordOptimizationParams($country)
    {
        $searchIntent = $this->getRequest()->getPost('search_intent');
        $clusterCount = $this->getRequest()->getPost('cluster_count');
        $autoTextOptimization = $this->getRequest()->getPost('automatic_text_optimization');
        $triggerActionLow = $this->getRequest()->getPost('trigger_action_low');
        $triggerActionLowMid = $this->getRequest()->getPost('trigger_action_low_mid');
        $triggerActionMid = $this->getRequest()->getPost('trigger_action_mid');
        $triggerActionMidHigh = $this->getRequest()->getPost('trigger_action_mid_high');
        $triggerActionNPositionLow = $this->getRequest()->getPost('trigger_action_n_position_low');
        $triggerActionNPositionLowMid = $this->getRequest()->getPost('trigger_action_n_position_low_mid');
        $triggerActionNPositionMid = $this->getRequest()->getPost('trigger_action_n_position_mid');
        $triggerActionNPositionMidHigh = $this->getRequest()->getPost('trigger_action_n_position_mid_high');
        $triggerActionNDaysLow = $this->getRequest()->getPost('trigger_action_n_days_low');
        $triggerActionNDaysLowMid = $this->getRequest()->getPost('trigger_action_n_days_low_mid');
        $triggerActionNDaysMid = $this->getRequest()->getPost('trigger_action_n_days_mid');
        $triggerActionNDaysMidHigh = $this->getRequest()->getPost('trigger_action_n_days_mid_high');
        $products = $this->getRequest()->getPost('product_texts');
        
        $action = $this->helper->getKeywordOptimizationSettings(
            'automatic_text_optimization'
        ) ?? AutomaticTextOptimization::FLAG;

        $actionOriginal = $action;

        switch ($action) {
            case AutomaticTextOptimization::AUTO_REWRITE_AND_QUEUE:
                $action = 'AutomaticRewrite';
                break;
            case AutomaticTextOptimization::FLAG:
                $action = 'FlagForRewrite';
                break;
            case AutomaticTextOptimization::AUTO_REWRITE_AND_TRANSFER:
                $action = 'FullAutomation';
                break;
        }

        $triggerSettings = [
            "pipeline_keyword" => [
                "low" => [
                    "trigger_action" => $triggerActionLow,
                    "trigger_action_n_position" => $triggerActionNPositionLow,
                    "trigger_action_n_days" => $triggerActionNDaysLow
                ],
                "low_mid" => [
                    "trigger_action" => $triggerActionLowMid,
                    "trigger_action_n_position" => $triggerActionNPositionLowMid,
                    "trigger_action_n_days" => $triggerActionNDaysLowMid
                ],
                "mid" => [
                    "trigger_action" => $triggerActionMid,
                    "trigger_action_n_position" => $triggerActionNPositionMid,
                    "trigger_action_n_days" => $triggerActionNDaysMid
                ],
                "mid_high" => [
                    "trigger_action" => $triggerActionMidHigh,
                    "trigger_action_n_position" => $triggerActionNPositionMidHigh,
                    "trigger_action_n_days" => $triggerActionNDaysMidHigh
                ]
            ],
            "automatic_text_optimization" => $autoTextOptimization,
            "products" => implode(',', $products)
        ];

        $triggers = $this->keywords->prepareCustomTriggerSettingsParameters(
            'Product',
            $triggerSettings
        );
        // foreach ($triggers as $key => $trigger) {
        //     $triggers[$key]['action'] = $action;
        // }

        $params = [
            "intents" => explode(', ', $searchIntent),
            "countryCode" => $country,
            "clusters" => $clusterCount,
            "triggers" => $triggers
        ];
        
        if (filter_var($this->helper->getKoDev(), FILTER_VALIDATE_BOOLEAN)) {
            $params["developmentSettings"] = [
                "waitTimePerStep" => 1000,
                "maxSteps" => 9,
                "failAfterFirstStep" => filter_var($this->helper->getForceFailed(), FILTER_VALIDATE_BOOLEAN)
            ];
        }

        return $params;
    }

    /**
     * Save bulk request
     *
     * @param array $apiResponse
     * @param string $singleRecordId
     * @return void
     */
    protected function saveBulkRequest($apiResponse, $singleRecordId = null)
    {
        $user = $this->apiSession->getCurrentUser();

        if ($apiResponse['requestId']) {
            $this->fullAutomationRequestsManager->setFullAutomationRequest(
                $apiResponse['requestId'],
                $user->getEmail(),
                $apiResponse['type'],
                $apiResponse['storeId'],
                $singleRecordId
            );
        }
        $this->BulkTransferRequestsManager->delete($user->getEmail());
        $this->bulkGenerateRequestsManager->deleteByUser($user->getEmail());
        $this->bulkKeywordAnalysisRequestsManager->deleteByUser($user->getEmail());
    }
}
