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

use Magento\Backend\App\Action\Context;
use WriteTextAI\WriteTextAI\Helper\Data;
use WriteTextAI\WriteTextAI\Model\Api\CurlBuilder;
use Magento\Framework\Event\ManagerInterface as EventManager;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\Controller\ResultInterface;
use WriteTextAI\WriteTextAI\Model\Api\Session as ApiSession;
use WriteTextAI\WriteTextAI\Model\IntegrationApiManager;

class Index extends \Magento\Backend\App\Action
{
    public const ADMIN_RESOURCE = 'WriteTextAI_WriteTextAI::modify_defaults';

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

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

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

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

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

    /**
     * @var IntegrationApiManager
     */
    protected $integrationApiManager;

    /**
     * Constructor
     *
     * @param Context $context
     * @param PageFactory $resultPageFactory
     * @param Data $helper
     * @param CurlBuilder $curlBuilder
     * @param EventManager $eventManager
     * @param ApiSession $apiSession
     * @param IntegrationApiManager $integrationApiManager
     */
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory,
        Data $helper,
        CurlBuilder $curlBuilder,
        EventManager $eventManager,
        ApiSession $apiSession,
        IntegrationApiManager $integrationApiManager
    ) {
        $this->resultPageFactory = $resultPageFactory;
        $this->helper = $helper;
        $this->curlBuilder = $curlBuilder;
        $this->eventManager = $eventManager;
        $this->apiSession = $apiSession;
        $this->integrationApiManager = $integrationApiManager;
        parent::__construct($context);
    }

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

        try {
            $isLoggedIn = $this->login();

            if ($isLoggedIn) {
                $this->eventManager->dispatch('wtai_prepare_settings');

                if ($this->helper->isDataMapped() &&
                    //$this->helper->isFinalStepDone() &&
                    $this->helper->isSetupFinalized()
                ) {
                    $this->integrationApiManager->sendApiIntegration();

                    $resultRedirect = $this->resultRedirectFactory->create();
                    return $resultRedirect->setPath('wtai/grid/index');
                }
            }

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

            $resultPage = $this->resultPageFactory->create();
            $resultPage->getConfig()->getTitle()->prepend(__("Extension setup guide"));
            $resultPage->setActiveMenu('WriteTextAI_WriteTextAI::menu');
            $wizardBlock = $resultPage->getLayout()->getBlock('wtai.setup.wizard');
            if ($wizardBlock) {
                $wizardBlock->setIsLoggedIn($isLoggedIn);
                $this->curlBuilder->registerDomains();
            }

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

            $resultPage = $this->resultPageFactory->create();
            $resultPage->getConfig()->getTitle()->prepend(__("Extension setup guide"));
            $resultPage->setActiveMenu('WriteTextAI_WriteTextAI::menu');
            $wizardBlock = $resultPage->getLayout()->getBlock('wtai.setup.wizard');
            if ($wizardBlock) {
                $wizardBlock->setIsLoggedIn(false);
            }
            
            return $resultPage;
        } catch (\WriteTextAI\WriteTextAI\Exception\VersionException $e) {
            $resultPage = $this->resultPageFactory->create();
            $resultPage->getConfig()->getTitle()->prepend(__("Extension setup guide"));
            $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()->prepend(__("Extension setup guide"));
            $resultPage->setActiveMenu('WriteTextAI_WriteTextAI::menu');
            $resultPage->getLayout()->unsetElement('content');
            $resultPage->getLayout()->unsetElement('header');

            return $resultPage;
        }
    }

    /**
     * Login to Write.ai
     *
     * @return bool
     */
    protected function login()
    {
        $isLoggedIn = false;
        $accountToken = $this->helper->getAccountToken();
        $region = $this->helper->getRegion();

        if ($accountToken && $region) {
            if ($this->curlBuilder->getConnectToken($accountToken)) {
                $isLoggedIn = true;
            }
        }

        return $isLoggedIn;
    }
}
