<?php

namespace Modules\Admin\Config\Server\Email\Settings;

class Controller extends \App\Mvc\Controller\Form\PopupAbstract
{

	/**
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Form\PopupAbstract::initialize()
	 */
	protected function initialize()
	{
		parent::initialize();

		$this->actionsCfg['index'] = [ 'checkSection' => 'Modules/Admin/Config/Server/Email', 'checkOption' => false ];
	}


	protected function actionIndex($R)
	{

		// collects messages
		$msgs = \App\MessagesCollector::create();

		$modelOutput = null;
		// SAVE THE FORM DATA /////////////////////////////////////////////////////////////////////
		if ($R[$this->formSubmitButtonName]??null) {
			$modelOutput = $this->processFormData($R, $msgs);
		}

		// get form data for this operation
		if (!($R[$this->formSubmitButtonName]??null)) {
			$formData = $this->getDefaultFormData($R);
		} else {
			$formData = $R;
		}

		if ($modelOutput===null or is_bool($modelOutput)) {
			// instantiate the view
			$view = $this->buildViewObjectFromCurrentModuleForAction($this->getAction());
			// send data to the view
			$view->addInput('formData', $formData);
			$view->getMessagesCollector()->appendMessages($msgs);
			$view->addInput('formSubmitButtonName', $this->formSubmitButtonName);
			if ($modelOutput === true) {
				$view->setClosePopup(true);
			}

			// do some more stuff (if needed)
			$this->preRenderOperations($view, $formData);

			// render the view
			return new \Engine\Mvc\Response\Html($view->render());
		}
		elseif ($modelOutput=='redirectMsLogin') {

			return new \Engine\Mvc\Response\HtmlRedirect( \Engine\Mvc\Dispatcher::getInstance()->getAppUrl("Modules/Admin/Config/Server/Email/AuthProviders/Microsoft", "", ['client' => 'system']) );

		} else {
			throw new \Exception('Invalid model output.');
		}
	}


	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Form\WindowAbstract::getDefaultFormData()
	 */
	protected function getDefaultFormData($R)
	{
		// get vars from class storage
		$emailSettingsObj = \App\Config\EmailSettings::getInstance();

		// associate default vars
		$formData = [];

		$formData['protocol'] =						$emailSettingsObj->get('protocol') ? : 'sendmail'; // fallback to sendmail (it this is the first time here)
		$formData['smtpHost'] = 					$emailSettingsObj->get('smtpHost');
		$formData['smtpPort'] = 					$emailSettingsObj->get('smtpPort');
		$formData['smtpUser'] = 					$emailSettingsObj->get('smtpUser');
		$formData['smtpPass'] = 					'';
		$formData['smtpSecure'] = 					$emailSettingsObj->get('smtpSecure');
		$formData['smtpIgnoreCertif'] = 			$emailSettingsObj->get('smtpIgnoreCertif');
		$formData['smtpSslCiphers'] = 				$emailSettingsObj->get('smtpSslCiphers');
		$formData['smtpOauthTenantId'] = 			$emailSettingsObj->get('smtpOauthTenantId');
		$formData['smtpOauthClientId'] = 			$emailSettingsObj->get('smtpOauthClientId');
		$formData['smtpOauthClientSecret'] = 		(bool)$emailSettingsObj->get('smtpOauthClientSecret');
		$formData['smtpOauthRefreshToken'] = 		(bool)$emailSettingsObj->get('smtpOauthRefreshToken');
		$formData['forceSenderFromSmtpUser'] = 		$emailSettingsObj->get('forceSenderFromSmtpUser');

		return $formData;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Form\WindowAbstract::processFormData()
	 */
	protected function processFormData(Array $R, \App\MessagesCollector $msgs): bool|string
	{

		// STORE THE DETAILS ----------------------------------------------------------------------

		try {

			$redirect = false;

			$settingsObj = \App\Config\EmailSettings::getAdmin();

			$settingsObj->set('protocol', $R['protocol']);
			$settingsObj->set('smtpHost', $R['smtpHost']);
			$settingsObj->set('smtpPort', $R['smtpPort']);
			$settingsObj->set('smtpUser', $R['smtpUser']);
			if (strlen($R['smtpPass'])) {
				$settingsObj->set('smtpPass', ($R['smtpPass'] == '_') ? '' : $R['smtpPass']);
			}
			$settingsObj->set('smtpSecure', $R['smtpSecure']);
			$settingsObj->set('smtpIgnoreCertif', $R['smtpIgnoreCertif']);
			$settingsObj->set('smtpSslCiphers', $R['smtpSslCiphers']);
			$settingsObj->set('smtpOauthTenantId', $R['smtpOauthTenantId']);
			$settingsObj->set('smtpOauthClientId', $R['smtpOauthClientId']);
			if (strlen($R['smtpOauthClientSecret'])) {
				$settingsObj->set('smtpOauthClientSecret', ($R['smtpOauthClientSecret'] == '_') ? '' : $R['smtpOauthClientSecret']);
				$settingsObj->set('smtpOauthRefreshToken', ''); // reset the refresh token also
				$redirect = ($R['smtpOauthClientSecret'] != '_');
			}
			$settingsObj->set('forceSenderFromSmtpUser', $R['forceSenderFromSmtpUser']);


			$settingsObj->save();
		} catch (\App\Config\MessageException $e) {
			$msgs->addError( $e->getMessage() );
			return false;
		}

		// close the page, or force redirect to MS if this is required
		if ($redirect) {
			return 'redirectMsLogin';
		} else {
			$msgs->addSuccess($this->lang['index']['success']);
			return true;
		}

	}

}
