<?php

namespace Modules\Admin\UserProfile\Options;

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/UserProfile', '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' => 'currentUser',
//			]) );
//
//		} else {
//			throw new \Exception('Invalid model output.');
//		}
//	}


	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Form\WindowAbstract::getDefaultFormData()
	 */
	protected function getDefaultFormData($R)
	{

		$formData = [];

		// SERVICE AND ORDER
		$formData['addServOnOrder_defaultServiceCode'] =		\App\EntityPreference\User::getInstance()->addServOnOrder_defaultServiceCode;
		$formData['addServOnOrder_defaultRemarks'] =			\App\EntityPreference\User::getInstance()->addServOnOrder_defaultRemarks;
		$formData['addServOnRes_defaultServiceCode'] = 			\App\EntityPreference\User::getInstance()->addServOnRes_defaultServiceCode;
		$formData['defaultPackageServiceCode'] =				\App\EntityPreference\User::getInstance()->defaultPackageServiceCode;
		$formData['addServOnRes_paxSelection'] = 				\App\EntityPreference\User::getInstance()->addServOnRes_paxSelection;
		$formData['addServOnRes_defaultRemarks'] = 				\App\EntityPreference\User::getInstance()->addServOnRes_defaultRemarks;
		$formData['invoiceOnOrderForm_idSeries'] = 				\App\EntityPreference\User::getInstance()->invoiceOnOrderForm_idSeries;
		$formData['invoiceOnOrderForm_invoiceDocType'] = 		\App\EntityPreference\User::getInstance()->invoiceOnOrderForm_invoiceDocType;
		$formData['invoiceOnOrderForm_idTemplate'] = 			\App\EntityPreference\User::getInstance()->invoiceOnOrderForm_idTemplate;

		// EMAIL DOCUMENTS SETTINGS
		$formData['emailDocs_selfBcc'] = 						\App\EntityPreference\User::getInstance()->emailDocs_selfBcc;
		$formData['emailDocs_readReceipt'] = 					\App\EntityPreference\User::getInstance()->emailDocs_readReceipt;
		$formData['docEmail_order_defaultSubject'] = 			\App\EntityPreference\User::getInstance()->docEmail_order_defaultSubject;
		$formData['docEmail_order_defaultBody'] = 				\App\EntityPreference\User::getInstance()->docEmail_order_defaultBody;
		$formData['docEmail_service_defaultSubject'] = 			\App\EntityPreference\User::getInstance()->docEmail_service_defaultSubject;
		$formData['docEmail_service_defaultBody'] = 			\App\EntityPreference\User::getInstance()->docEmail_service_defaultBody;
		$formData['docEmail_invoice_defaultSubject'] = 			\App\EntityPreference\User::getInstance()->docEmail_invoice_defaultSubject;
		$formData['docEmail_invoice_defaultBody'] = 			\App\EntityPreference\User::getInstance()->docEmail_invoice_defaultBody;
		$formData['docEmail_cashing_defaultSubject'] = 			\App\EntityPreference\User::getInstance()->docEmail_cashing_defaultSubject;
		$formData['docEmail_cashing_defaultBody'] = 			\App\EntityPreference\User::getInstance()->docEmail_cashing_defaultBody;
		$formData['docEmail_payment_defaultSubject'] = 			\App\EntityPreference\User::getInstance()->docEmail_payment_defaultSubject;
		$formData['docEmail_payment_defaultBody'] = 			\App\EntityPreference\User::getInstance()->docEmail_payment_defaultBody;
		$formData['docEmail_cashBookDoc_defaultSubject'] = 		\App\EntityPreference\User::getInstance()->docEmail_cashBookDoc_defaultSubject;
		$formData['docEmail_cashBookDoc_defaultBody'] = 		\App\EntityPreference\User::getInstance()->docEmail_cashBookDoc_defaultBody;
		$formData['docEmail_importedService_defaultSubject'] = 	\App\EntityPreference\User::getInstance()->docEmail_importedService_defaultSubject;
		$formData['docEmail_importedService_defaultBody'] = 	\App\EntityPreference\User::getInstance()->docEmail_importedService_defaultBody;

//		// EMAIL CONFIG
//		$formData['emailCfg_protocol'] =						\App\EntityPreference\User::getInstance()->emailCfg_protocol;
//		$formData['emailCfg_smtpHost'] = 						\App\EntityPreference\User::getInstance()->emailCfg_smtpHost;
//		$formData['emailCfg_smtpPort'] = 						\App\EntityPreference\User::getInstance()->emailCfg_smtpPort;
//		$formData['emailCfg_smtpUser'] = 						\App\EntityPreference\User::getInstance()->emailCfg_smtpUser;
//		$formData['emailCfg_smtpPass'] = 						'';
//		$formData['emailCfg_smtpSecure'] = 						\App\EntityPreference\User::getInstance()->emailCfg_smtpSecure;
//		$formData['emailCfg_smtpIgnoreCertif'] = 				\App\EntityPreference\User::getInstance()->emailCfg_smtpIgnoreCertif;
//		$formData['emailCfg_smtpSslCiphers'] = 					\App\EntityPreference\User::getInstance()->emailCfg_smtpSslCiphers;
//		$formData['emailCfg_smtpOauthTenantId'] = 				\App\EntityPreference\User::getInstance()->emailCfg_smtpOauthTenantId;
//		$formData['emailCfg_smtpOauthClientId'] = 				\App\EntityPreference\User::getInstance()->emailCfg_smtpOauthClientId;
//		$formData['emailCfg_smtpOauthClientSecret'] = 			(bool)\App\EntityPreference\User::getInstance()->emailCfg_smtpOauthClientSecret;
//		$formData['emailCfg_smtpOauthRefreshToken'] = 			(bool)\App\EntityPreference\User::getInstance()->emailCfg_smtpOauthRefreshToken;
//		$formData['emailCfg_smtpOauthRedirectToLogin'] = 		false;
//		$formData['emailCfg_forceSenderFromSmtpUser'] = 		\App\EntityPreference\User::getInstance()->emailCfg_forceSenderFromSmtpUser;

		// CORPORATE DEFAULT REMARKS
		$formData['corporate_defaultRemarks'] = 				\App\EntityPreference\User::getInstance()->corporate_defaultRemarks;

		// DOCUMENT TEMPLATES
		foreach(\App\Config\IssueDocuments::getInstance()->getAll() as $docType=>$docDetails) {
			if ($docDetails['active']) {
				$var='defaultDocTpl_'.$docType;
				$formData['docTemplate'][$docType] = 		\App\EntityPreference\User::getInstance()->$var;
			}
		}

		// DOCUMENT SERIES
		foreach(\App\Config\IssueDocuments::getInstance()->getAll() as $docType=>$docDetails) {
			if ($docDetails['active'] and ($docDetails['docNumberType']=='chooseSeries' or $docDetails['docNumberType']=='pivotSeries')) {
				$var='defaultDocSeries_'.$docType;
				$formData['docSeries'][$docType] = \App\EntityPreference\User::getInstance()->$var;
			}
		}
		return $formData;
	}

	private function cleanHtmlContentFromRequest($htmlContent)
	{
		return trim(strip_tags(htmlUnclean($htmlContent)));
	}

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

//		// VALIDATE EMAIL SETTINGS INPUT ----------------------------------------------------------
//		if ($R['emailCfg_protocol'] == 'smtp' && !$R['emailCfg_smtpHost']){
//			$msgs->addWarning($this->lang['index']['error_protocol']);
//			$error = true;
//		}
//
//		if ($R['emailCfg_protocol'] == 'smtpOauthMs') {
//			if (!$R['emailCfg_smtpOauthClientId']) {
//				$msgs->addWarning($this->lang['index']['error_smtpOauthClientIdMandatory']);
//				$error = true;
//			}
//			if (!$R['emailCfg_smtpOauthTenantId']) {
//				$msgs->addWarning($this->lang['index']['error_smtpOauthTenantIdMandatory']);
//				$error = true;
//			}
//			if (!$R['emailCfg_smtpUser']) {
//				$msgs->addWarning($this->lang['index']['error_smtpOauthUserMandatory']);
//				$error = true;
//			}
//		}

		// STORE THE DETAILS ----------------------------------------------------------------------
		$closePageOnSuccess = true;

		\DB::startTransaction();
		$userPrefobj = \App\EntityPreference\User::getInstance();

		// SERVICE AND ORDER
		$userPrefobj->addServOnOrder_defaultServiceCode =			$R['addServOnOrder_defaultServiceCode'];
		$userPrefobj->addServOnOrder_defaultRemarks =				$R['addServOnOrder_defaultRemarks'];
		$userPrefobj->addServOnRes_defaultServiceCode =				$R['addServOnRes_defaultServiceCode'];
		$userPrefobj->defaultPackageServiceCode =					$R['defaultPackageServiceCode'];
		$userPrefobj->addServOnRes_paxSelection =					$R['addServOnRes_paxSelection'];
		$userPrefobj->addServOnRes_defaultRemarks =					$R['addServOnRes_defaultRemarks'];
		$userPrefobj->invoiceOnOrderForm_idSeries =					$R['invoiceOnOrderForm_idSeries'];
		$userPrefobj->invoiceOnOrderForm_invoiceDocType =			$R['invoiceOnOrderForm_invoiceDocType'];
		$userPrefobj->invoiceOnOrderForm_idTemplate =				$R['invoiceOnOrderForm_idTemplate'];

		// EMAIL DOCUMENTS SETTINGS
		$userPrefobj->emailDocs_selfBcc = 							$R['emailDocs_selfBcc'];
		$userPrefobj->emailDocs_readReceipt = 						$R['emailDocs_readReceipt'];
		$userPrefobj->docEmail_order_defaultSubject = 				$R['docEmail_order_defaultSubject'];
		$userPrefobj->docEmail_service_defaultSubject = 			$R['docEmail_service_defaultSubject'];
		$userPrefobj->docEmail_invoice_defaultSubject = 			$R['docEmail_invoice_defaultSubject'];
		$userPrefobj->docEmail_cashing_defaultSubject = 			$R['docEmail_cashing_defaultSubject'];
		$userPrefobj->docEmail_payment_defaultSubject = 			$R['docEmail_payment_defaultSubject'];
		$userPrefobj->docEmail_cashBookDoc_defaultSubject = 		$R['docEmail_cashBookDoc_defaultSubject'];
		$userPrefobj->docEmail_importedService_defaultSubject = 	$R['docEmail_importedService_defaultSubject'];

		$userPrefobj->docEmail_order_defaultBody = 					$this->cleanHtmlContentFromRequest($R['docEmail_order_defaultBody'])			? $R['docEmail_order_defaultBody']				: '';
		$userPrefobj->docEmail_service_defaultBody = 				$this->cleanHtmlContentFromRequest($R['docEmail_service_defaultBody'])			? $R['docEmail_service_defaultBody']			: '';
		$userPrefobj->docEmail_invoice_defaultBody = 				$this->cleanHtmlContentFromRequest($R['docEmail_invoice_defaultBody'])			? $R['docEmail_invoice_defaultBody']			: '';
		$userPrefobj->docEmail_cashing_defaultBody = 				$this->cleanHtmlContentFromRequest($R['docEmail_cashing_defaultBody'])			? $R['docEmail_cashing_defaultBody']			: '';
		$userPrefobj->docEmail_payment_defaultBody = 				$this->cleanHtmlContentFromRequest($R['docEmail_payment_defaultBody'])			? $R['docEmail_payment_defaultBody']			: '';
		$userPrefobj->docEmail_cashBookDoc_defaultBody = 			$this->cleanHtmlContentFromRequest($R['docEmail_cashBookDoc_defaultBody'])		? $R['docEmail_cashBookDoc_defaultBody']		: '';
		$userPrefobj->docEmail_importedService_defaultBody = 		$this->cleanHtmlContentFromRequest($R['docEmail_importedService_defaultBody'])	? $R['docEmail_importedService_defaultBody']	: '';

//			$userPrefobj->emailCfg_protocol =							$R['emailCfg_protocol'];
//			$userPrefobj->emailCfg_smtpHost =							$R['emailCfg_smtpHost'];
//			$userPrefobj->emailCfg_smtpPort =							$R['emailCfg_smtpPort'];
//			$userPrefobj->emailCfg_smtpUser =							$R['emailCfg_smtpUser'];
//			if (strlen($R['emailCfg_smtpPass'])) {
//				$userPrefobj->emailCfg_smtpPass =						($R['emailCfg_smtpPass']=='_') ? '' : $R['emailCfg_smtpPass'];
//			}
//			$userPrefobj->emailCfg_smtpSecure =							$R['emailCfg_smtpSecure'];
//			$userPrefobj->emailCfg_smtpIgnoreCertif =					$R['emailCfg_smtpIgnoreCertif'];
//			$userPrefobj->emailCfg_smtpSslCiphers =						$R['emailCfg_smtpSslCiphers'];
//			$userPrefobj->emailCfg_smtpOauthTenantId =					$R['emailCfg_smtpOauthTenantId'];
//			$userPrefobj->emailCfg_smtpOauthClientId =					$R['emailCfg_smtpOauthClientId'];
//			if (strlen($R['emailCfg_smtpOauthClientSecret'])) {
//				$userPrefobj->emailCfg_smtpOauthClientSecret =			($R['emailCfg_smtpOauthClientSecret']=='_') ? '' : $R['emailCfg_smtpOauthClientSecret'];
//				$userPrefobj->emailCfg_smtpOauthRefreshToken =			''; // reset the refresh token also
//				$closePageOnSuccess = false;
//			}
//			$userPrefobj->emailCfg_forceSenderFromSmtpUser =			$R['emailCfg_forceSenderFromSmtpUser'];

		// CORPORATE DEFAULT REMARKS
		$userPrefobj->corporate_defaultRemarks = 					$R['corporate_defaultRemarks'];

		// DOCUMENT SERIES
		if ($R['docSeries']) {
			foreach($R['docSeries'] as $docType=>$idSeries) {
				if (!$idSeries) {
					$idSeries=null;
				}
				$var = 'defaultDocSeries_'.$docType;
				$userPrefobj->$var = $idSeries;
			}
		}

		// DOCUMENT TEMPLATES
		if ($R['docTemplate']) {
			foreach($R['docTemplate'] as $docType=>$idTemplate) {
				if (!$idTemplate) {
					$idTemplate=null;
				}
				$var = 'defaultDocTpl_'.$docType;
				$userPrefobj->$var = $idTemplate;
			}
		}
		\DB::commitTransaction();

		$msgs->addSuccess($this->lang['index']['success']);
		return true;

	}
}