<?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\Categories;

use Magento\Framework\View\Result\PageFactory;
use WriteTextAI\WriteTextAI\Helper\Data;
use Magento\Framework\Event\ManagerInterface as EventManager;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultInterface;
use WriteTextAI\WriteTextAI\ViewModel\Footer;
use WriteTextAI\WriteTextAI\Helper\Statistics;
use WriteTextAI\WriteTextAI\Model\Api\Session as ApiSession;
use WriteTextAI\WriteTextAI\Model\Api\CurlBuilder;
use Magento\Framework\App\Config\ConfigResource\ConfigInterface;
use Magento\Framework\App\CacheInterface;

class Index extends \Magento\Backend\App\Action
{
    public const TEMPLATE_SETTINGS_CACHE_KEY = 'writetext_ai_template_settings';

    /**
     * @var PageFactory
     */
    protected $resultPageFactory;

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

    /**
     * @var EventManager
     */
    protected $eventManager;

    /**
     * @var Footer
     */
    protected $footer;

    /**
     * @var Statistics
     */
    protected $statisticsHelper;

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

    /**
     * @var CurlBuilder
     */
    protected $curlBuilder;

    /**
     * @var ConfigInterface
     */
    protected $configManager;

    /**
     * @var CacheInterface
     */
    protected $cache;

    /**
     * Constructor
     *
     * @param Context $context
     * @param PageFactory $resultPageFactory
     * @param Data $helper
     * @param EventManager $eventManager
     * @param Footer $footer
     * @param Statistics $statisticsHelper
     * @param ApiSession $apiSession
     * @param CurlBuilder $curlBuilder
     * @param ConfigInterface $configManager
     * @param CacheInterface $cache
     */
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory,
        Data $helper,
        EventManager $eventManager,
        Footer $footer,
        Statistics $statisticsHelper,
        ApiSession $apiSession,
        CurlBuilder $curlBuilder,
        ConfigInterface $configManager,
        CacheInterface $cache
    ) {
        $this->resultPageFactory = $resultPageFactory;
        $this->helper = $helper;
        $this->eventManager = $eventManager;
        $this->footer = $footer;
        $this->statisticsHelper = $statisticsHelper;
        $this->apiSession = $apiSession;
        $this->curlBuilder = $curlBuilder;
        $this->configManager = $configManager;
        $this->cache = $cache;
        parent::__construct($context);
    }

    /**
     * Index action
     *
     * @return ResultInterface
     */
    public function execute()
    {
        $resultRedirect = $this->resultRedirectFactory->create();
        $userlanguage = $this->apiSession->getRegionIndependentLanguage();
        $translationNoticeEnabled = $this->helper->isTranslationNoticeEnabled();

        try {
            $this->cache->remove(self::TEMPLATE_SETTINGS_CACHE_KEY);
            if (!$this->isSetupComplete()) {
                return $resultRedirect->setPath('wtai/setup/index');
            } else {
                $this->eventManager->dispatch('wtai_prepare_settings');

                if ($userlanguage !== 'en' && $translationNoticeEnabled) {
                    $this->messageManager->addNotice(
                        __("Notice: Translation of extension help text and labels is ongoing. Please stay tuned.")
                    );
                }

                $getCredit = $this->curlBuilder->getApiResponse('text/Credit') ?? [];
                
                $resultPage = $this->resultPageFactory->create();
                $resultPage->getConfig()->getTitle()->set(__('WriteText.ai - Category'));
                $resultPage->setActiveMenu('WriteTextAI_WriteTextAI::menu');

                if ($this->helper->isFirstVisitCannibalization()) {
                    $this->curlBuilder->registerDomains();
                    $this->configManager->saveConfig('writetextai_settings/cannibalization/first_visit', 1);
                }
                $this->statisticsHelper->sendStatistics('step5');
                return $resultPage;
            }
        } catch (\WriteTextAI\WriteTextAI\Exception\UnauthorizedException $e) {
            return $resultRedirect->setPath('wtai/setup/index');
        } catch (\WriteTextAI\WriteTextAI\Exception\UnsupportedLanguageException $e) {
            $this->messageManager->addError($e->getMessage());

            $resultPage = $this->resultPageFactory->create();
            $resultPage->getConfig()->getTitle()->set(__('WriteText.ai - Category'));
            $resultPage->setActiveMenu('WriteTextAI_WriteTextAI::menu');
            $resultPage->getLayout()->unsetElement('content');
            $resultPage->getLayout()->unsetElement('header');

            return $resultPage;
        } catch (\WriteTextAI\WriteTextAI\Exception\VersionException $e) {
            $resultPage = $this->resultPageFactory->create();
            $resultPage->getConfig()->getTitle()->set(__('WriteText.ai - Category'));
            $resultPage->setActiveMenu('WriteTextAI_WriteTextAI::menu');
            $resultPage->getLayout()->unsetElement('content');
            $resultPage->getLayout()->unsetElement('header');

            return $resultPage;
        } catch (\WriteTextAI\WriteTextAI\Exception\TermsException $e) {
            $this->messageManager->getMessages(true);
            $this->messageManager->addError($e->getMessage());
            $resultPage = $this->resultPageFactory->create();
            $resultPage->getConfig()->getTitle()->set(__('WriteText.ai - Category'));
            $resultPage->setActiveMenu('WriteTextAI_WriteTextAI::menu');
            $resultPage->getLayout()->unsetElement('content');
            $resultPage->getLayout()->unsetElement('header');

            return $resultPage;
        }
    }

    /**
     * Check if setup is complete
     *
     * @return bool
     */
    private function isSetupComplete()
    {
        /**
         * check if account token and region is set
         * then verify account token
         */
        if ($this->footer->isLoggedIn()) {
            // Check if all text fields are mapped to an existing attribute
            if ($this->helper->isDataMapped()) {
                // Check if final step is done and finalized
                if ($this->helper->isSetupFinalized()) {
                    return true;
                }
            } else {
                if ($this->helper->isSetupFinalized()) {
                    $notMappedField = $this->helper->getNotMappedField();
                    $this->messageManager->addError(
                        sprintf(
                            (string)__(
                                "You have been redirected here because we detected a change " .
                                "in the field that you have set for %s. You will need to map " .
                                "a text field so WriteText.ai has a place to transfer your %s to. " .
                                "Don't worry, all your content is saved and you will be redirected " .
                                "back to your dashboard after setting this up."
                            ),
                            $notMappedField,
                            $notMappedField
                        )
                    );
                }
            }
        } else {
            //SEND statistic - user is in step 1
            if ($this->statisticsHelper->sendStatistics('step1')) {
                $this->helper->flushConfigCache();
            }
        }

        return false;
    }
}
