<?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');

            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)
    {
        $tones = $this->generateHelper->updateDefault(
            $this->generateOptionsManager->getOptions('tones'),
            $this->userFieldsSelected->getUserFieldsSelected(
                UserFieldsSelectedManager::ACTION_TYPE_TONES,
                '',
                'edit'
            )
        );

        $userStyles = $this->userFieldsSelected->getUserFieldsSelected(
            UserFieldsSelectedManager::ACTION_TYPE_STYLE,
            '',
            'edit'
        );
        $styles = $this->generateHelper->updateDefault(
            $this->generateOptionsManager->getOptions('styles'),
            $userStyles ? [$userStyles] : []
        );

        $audiences = $this->generateHelper->updateDefault(
            $this->generateOptionsManager->getOptions('audience'),
            $this->userFieldsSelected->getUserFieldsSelected(
                UserFieldsSelectedManager::ACTION_TYPE_AUDIENCES,
                '',
                'edit'
            )
        );

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

        return [
            'custom_tone' => $this->userFieldsSelected->getUserFieldsSelected(
                UserFieldsSelectedManager::ACTION_TYPE_CUSTOM_TONE,
                '',
                'edit'
            ),
            'custom_style' => $this->userFieldsSelected->getUserFieldsSelected(
                UserFieldsSelectedManager::ACTION_TYPE_CUSTOM_STYLE,
                '',
                'edit'
            ),
            '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
        ];
    }
}
