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

declare(strict_types=1);

namespace WriteTextAI\WriteTextAI\Controller\Adminhtml\Settings;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use WriteTextAI\WriteTextAI\Model\UserFieldsSelectedManager;
use WriteTextAI\WriteTextAI\Model\GenerateOptionsManager;
use WriteTextAI\WriteTextAI\Helper\Generate as GenerateHelper;
use WriteTextAI\WriteTextAI\ViewModel\UserFieldsSelected;
use WriteTextAI\WriteTextAI\Model\AiProductManager;
use WriteTextAI\WriteTextAI\Model\AiCategoryManager;
use WriteTextAI\WriteTextAI\Helper\ProductAttributes as ProductAttributesHelper;
use WriteTextAI\WriteTextAI\Helper\Product as ProductHelper;
use WriteTextAI\WriteTextAI\Helper\Store as StoreHelper;
use WriteTextAI\WriteTextAI\Helper\Data as DataHelper;

class Restore extends Action
{
    /**
     * @var UserFieldsSelectedManager
     */
    protected $userFieldsSelectedManager;

    /**
     * @var GenerateOptionsManager
     */
    protected $generateOptionsManager;

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

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

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

    /**
     * @var AiCategoryManager
     */
    protected $aiCategoryManager;

    /**
     * @var ProductAttributesHelper
     */
    protected $productAttributesHelper;

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

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

    /**
     * @var DataHelper
     */
    protected $dataHelper;

    /**
     * Constructor
     *
     * @param Context $context
     * @param UserFieldsSelectedManager $userFieldsSelectedManager
     * @param GenerateOptionsManager $generateOptionsManager
     * @param GenerateHelper $generateHelper
     * @param UserFieldsSelected $userFieldsSelected
     * @param AiProductManager $aiProductManager
     * @param AiCategoryManager $aiCategoryManager
     * @param ProductAttributesHelper $productAttributesHelper
     * @param ProductHelper $productHelper
     * @param StoreHelper $storeHelper
     * @param DataHelper $dataHelper
     */
    public function __construct(
        Context $context,
        UserFieldsSelectedManager $userFieldsSelectedManager,
        GenerateOptionsManager $generateOptionsManager,
        GenerateHelper $generateHelper,
        UserFieldsSelected $userFieldsSelected,
        AiProductManager $aiProductManager,
        AiCategoryManager $aiCategoryManager,
        ProductAttributesHelper $productAttributesHelper,
        ProductHelper $productHelper,
        StoreHelper $storeHelper,
        DataHelper $dataHelper
    ) {
        $this->userFieldsSelectedManager = $userFieldsSelectedManager;
        $this->generateOptionsManager = $generateOptionsManager;
        $this->generateHelper = $generateHelper;
        $this->userFieldsSelected = $userFieldsSelected;
        $this->aiProductManager = $aiProductManager;
        $this->aiCategoryManager = $aiCategoryManager;
        $this->productAttributesHelper = $productAttributesHelper;
        $this->productHelper = $productHelper;
        $this->storeHelper = $storeHelper;
        $this->dataHelper = $dataHelper;
        parent::__construct($context);
    }

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

        try {
            $entityType = $this->getRequest()->getParam('entity_type', 'product');

            $this->userFieldsSelectedManager->deleteAllPerType($entityType);
            $this->userFieldsSelectedManager->deleteSpecificSettings($entityType, 'attributes_selected', 'grid');
            $this->userFieldsSelectedManager->deleteSpecificSettings($entityType, 'search_intent', 'grid');
            $this->userFieldsSelectedManager->deleteSpecificSettings($entityType, 'search_intent', '');
            $this->userFieldsSelectedManager->deleteSpecificSettings('global', 'tones', 'grid');
            $this->userFieldsSelectedManager->deleteSpecificSettings('global', 'style', 'grid');
            $this->userFieldsSelectedManager->deleteSpecificSettings('global', 'audiences', 'grid');
            $this->userFieldsSelectedManager->deleteSpecificSettings('global', 'custom_tone', 'grid');
            $this->userFieldsSelectedManager->deleteSpecificSettings('global', 'custom_style', 'grid');

            $this->userFieldsSelectedManager->deleteSpecificSettings('', 'tones', 'grid');
            $this->userFieldsSelectedManager->deleteSpecificSettings('', 'style', 'grid');
            $this->userFieldsSelectedManager->deleteSpecificSettings('', 'audiences', 'grid');
            $this->userFieldsSelectedManager->deleteSpecificSettings('', 'custom_tone', 'grid');
            $this->userFieldsSelectedManager->deleteSpecificSettings('', 'custom_style', 'grid');

            switch ($entityType) {
                case 'product':
                    $data = $this->getProductSettings();
                    break;
                case 'category':
                    $data = $this->getCategorySettings();
                    break;
                default:
                    $data = [];
                    break;
            }

            $commonSeetings = $this->getCommonSettings($entityType);
            
            $result = [
                'success' => true,
                'data' => array_merge($data, $commonSeetings)
            ];
        } 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;
    }

    /**
     * Get common settings
     *
     * @param string $entityType
     *
     * @return array
     */
    protected function getCommonSettings($entityType)
    {
        $tonesOptions = $this->generateOptionsManager->getOptions('tones');
        $stylesOptions = $this->generateOptionsManager->getOptions('styles');
        $audienceOptions = $this->generateOptionsManager->getOptions('audience');

        $userTones = $this->userFieldsSelected->getUserFieldsSelected(
            UserFieldsSelectedManager::ACTION_TYPE_TONES,
            'global',
            'grid'
        );

        if (empty($userTones)) {
            $globalTones = $this->dataHelper->getTones();
            $userTones = $globalTones ? explode(',', $globalTones) : [];
        }

        $tones = $this->generateHelper->updateDefault(
            $tonesOptions,
            $userTones
        );

        $userStyles = $this->userFieldsSelected->getUserFieldsSelected(
            UserFieldsSelectedManager::ACTION_TYPE_STYLE,
            'global',
            'grid'
        );

        if (empty($userStyles)) {
            $globalStyles = $this->dataHelper->getStyles();
            $globalStyles = $globalStyles ? explode(',', $globalStyles) : [];
            $userStyles = array_shift($globalStyles);
        }

        $styles = $this->generateHelper->updateDefault(
            $stylesOptions,
            $userStyles ? [$userStyles] : []
        );

        $userAudiences = $this->userFieldsSelected->getUserFieldsSelected(
            UserFieldsSelectedManager::ACTION_TYPE_AUDIENCES,
            'global',
            'grid'
        );

        if (empty($userAudiences)) {
            $globalAudiences = $this->dataHelper->getAudiences();
            $userAudiences = $globalAudiences ? explode(',', $globalAudiences) : [];
        }

        $audiences = $this->generateHelper->updateDefault(
            $audienceOptions,
            $userAudiences
        );

        $searchIntent = $this->userFieldsSelected->getUserFieldsSelected(
            UserFieldsSelectedManager::ACTION_TYPE_SEARCH_INTENT,
            strtolower($entityType ?? 'product'),
            ''
        );

        $customTone = $this->userFieldsSelected->getUserFieldsSelected(
            UserFieldsSelectedManager::ACTION_TYPE_CUSTOM_TONE,
            'global',
            'grid'
        );
        if (empty($customTone)) {
            $customTone = $this->dataHelper->getCustomTone();
        }

        $customStyle = $this->userFieldsSelected->getUserFieldsSelected(
            UserFieldsSelectedManager::ACTION_TYPE_CUSTOM_STYLE,
            'global',
            'grid'
        );
        if (empty($customStyle)) {
            $customStyle = $this->dataHelper->getCustomStyle();
        }

        return [
            'custom_tone' => $customTone,
            'custom_style' => $customStyle,
            'guide_steps' => filter_var($this->userFieldsSelected->getUserFieldsSelected(
                UserFieldsSelectedManager::ACTION_TYPE_GUIDE_STEPS,
                $entityType,
                'edit'
            ), FILTER_VALIDATE_BOOLEAN),
            'selected_fields' => $this->userFieldsSelected->getUserFieldsSelected(
                UserFieldsSelectedManager::ACTION_TYPE_SINGLE_EDITOR_FIELDS,
                $entityType,
                'edit'
            ),
            'highlight_pronouns' => $this->userFieldsSelected->getUserFieldsSelected(
                UserFieldsSelectedManager::ACTION_TYPE_HIGHLIGHT_PRONOUNS,
                $entityType,
                'edit'
            ),
            'product_research_data' => $this->userFieldsSelected->getUserFieldsSelected(
                UserFieldsSelectedManager::ACTION_TYPE_PRODUCT_RESEARCH_DATA,
                '',
                ''
            ),
            'tones' => $tones,
            'styles' => $styles,
            'audience' => $audiences,
            'search_intent' => $searchIntent,
        ];
    }

    /**
     * Get product settings
     *
     * @return array
     */
    protected function getProductSettings()
    {
        $productId = $this->getRequest()->getParam('product_id');
        $storeId = $this->getRequest()->getParam('store_id');

        $this->aiProductManager->saveAttributesSelected(
            $productId,
            $storeId,
            ''
        );

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

        $userDescMin = $this->userFieldsSelected->getUserFieldsSelected(
            UserFieldsSelectedManager::ACTION_TYPE_DESC_MIN,
            '',
            ''
        );
        $userDescMax = $this->userFieldsSelected->getUserFieldsSelected(
            UserFieldsSelectedManager::ACTION_TYPE_DESC_MAX,
            '',
            ''
        );
        $userExcMin = $this->userFieldsSelected->getUserFieldsSelected(
            UserFieldsSelectedManager::ACTION_TYPE_EXC_MIN,
            '',
            ''
        );
        $userExcMax = $this->userFieldsSelected->getUserFieldsSelected(
            UserFieldsSelectedManager::ACTION_TYPE_EXC_MAX,
            '',
            ''
        );

        if (!$userDescMin) {
            $userDescMin = $this->dataHelper->getDescriptionSettings('min');
        }
        if (!$userDescMax) {
            $userDescMax = $this->dataHelper->getDescriptionSettings('max');
        }
        if (!$userExcMin) {
            $userExcMin = $this->dataHelper->getExcerptSettings('min');
        }
        if (!$userExcMax) {
            $userExcMax = $this->dataHelper->getExcerptSettings('max');
        }

        return [
            'product_attributes' => $this->productAttributesHelper->getProductAttributes($product),
            'product_attributes_selected' => $this->productAttributesHelper->getAttributesSelectedFromGlobalSettings(),
            'gallery' => $this->userFieldsSelected->getUserFieldsSelected(
                UserFieldsSelectedManager::ACTION_TYPE_GALLERY,
                'product',
                'edit'
            ),
            'images' => $this->productHelper->getImages($product, $storeId, $language),
            'desc_min' => $userDescMin,
            'desc_max' => $userDescMax,
            'exc_min' => $userExcMin,
            'exc_max' => $userExcMax
        ];
    }

    /**
     * Get category settings
     *
     * @return array
     */
    protected function getCategorySettings()
    {
        $productId = $this->getRequest()->getParam('product_id');
        $storeId = $this->getRequest()->getParam('store_id');

        $userDescMin = $this->userFieldsSelected->getUserFieldsSelected(
            UserFieldsSelectedManager::ACTION_TYPE_DESC_MIN,
            '',
            ''
        );
        $userDescMax = $this->userFieldsSelected->getUserFieldsSelected(
            UserFieldsSelectedManager::ACTION_TYPE_DESC_MAX,
            '',
            ''
        );

        if (!$userDescMin) {
            $userDescMin = $this->dataHelper->getCategoryDescriptionSettings('min');
        }
        if (!$userDescMax) {
            $userDescMax = $this->dataHelper->getCategoryDescriptionSettings('max');
        }

        return [
            'desc_min' => $userDescMin,
            'desc_max' => $userDescMax
        ];
    }
}
