<?php
namespace Modules\Admin\Config\Gds\Amadeus;

class Controller extends \App\Mvc\Controller\Form\WindowAbstract
{
	protected function initialize()
	{
		parent::initialize();
		$this->actionsCfg['generateInputMatrixRow'] = [];
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Form\WindowAbstract::getDefaultFormData()
	 */
	protected function getDefaultFormData($R)
	{
		$sftpDetails = unserialize((string)\App\Amadeus\Config::getInstance()->get("sftp"));
		if ($sftpDetails && isset($sftpDetails['privateKey'])) {
			$privateKeyDetails = \ModulesAbstract\ElectronicInvoice\SignXml\CertificateHelper::getInstance()->detectPrivateKeyFormat(\App\Amadeus\Config::getInstance()->decryptStr($sftpDetails['privateKey']));
			$sftpDetails['privateKeyDetails'] = $privateKeyDetails;
		}

		return [
			'importPassengerEmail' => 							\App\Amadeus\Config::getInstance()->get("importPassengerEmail"),
			'importPassengerEmail_ignoredAddresses' => 			unserialize((string)\App\Amadeus\Config::getInstance()->get("importPassengerEmail_ignoredAddresses")),
			'importPassengerTelephone' => 						\App\Amadeus\Config::getInstance()->get("importPassengerTelephone"),
			'importPassengerTelephone_ignoredPhoneNumbers' => 	unserialize((string)\App\Amadeus\Config::getInstance()->get("importPassengerTelephone_ignoredPhoneNumbers")),
			"importServiceFeeForService" => 					\App\Amadeus\Config::getInstance()->get("importServiceFeeForService"),
			"importServiceFeeForServiceCurrency" => 			\App\Amadeus\Config::getInstance()->get("importServiceFeeForServiceCurrency"),
			"importDiscountForService" => 						\App\Amadeus\Config::getInstance()->get("importDiscountForService"),
			"importDiscountForServiceCurrency" => 				\App\Amadeus\Config::getInstance()->get("importDiscountForServiceCurrency"),
			"importCommissionForService" => 					\App\Amadeus\Config::getInstance()->get("importCommissionForService"),
			"importCommissionForServiceCurrency" => 			\App\Amadeus\Config::getInstance()->get("importCommissionForServiceCurrency"),
			"importInvalidReissues" => 							\App\Amadeus\Config::getInstance()->get("importInvalidReissues"),
			"importHotelSupplierSource" => 						\App\Amadeus\Config::getInstance()->get("importHotelSupplierSource"),
			"importHotelFormOfPaymentSource" => 				\App\Amadeus\Config::getInstance()->get("importHotelFormOfPaymentSource"),
			"importCarFormOfPaymentSource" => 					\App\Amadeus\Config::getInstance()->get("importCarFormOfPaymentSource"),
			'ignoreSupplierOnDocuments' => 						unserialize((string)\App\Amadeus\Config::getInstance()->get("ignoreSupplierOnDocuments")),
			"taxManipulationsMatrix" => 						unserialize(@gzdecode(base64_decode((string)\App\Amadeus\Config::getInstance()->get("taxManipulationsMatrix")))),
			'vatPercent' =>										unserialize((string)\App\Amadeus\Config::getInstance()->get("vatPercent")),
			'sftp' =>											$sftpDetails,
		];
	}

	protected function getSubmitFormData($R, \App\MessagesCollector $msgs)
	{
		$sftpDetails = unserialize((string)\App\Amadeus\Config::getInstance()->get("sftp"));
		if ($sftpDetails && isset($sftpDetails['privateKey'])) {
			$privateKeyDetails = \ModulesAbstract\ElectronicInvoice\SignXml\CertificateHelper::getInstance()->detectPrivateKeyFormat(\App\Amadeus\Config::getInstance()->decryptStr($sftpDetails['privateKey']));
			$sftpDetails['privateKeyDetails'] = $privateKeyDetails;
		}

		$R['sftp'] = $sftpDetails;
		return $R;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Form\WindowAbstract::processFormData()
	 */
	protected function processFormData(Array $R, \App\MessagesCollector $msgs)
	{
		// handle sftp connection settings first. They need to be encrypted, cleaned up, etc.
		$sftpDetails = (array)$R['sftp'];
		$uploadedFile = new \App\Form\UploadedFiles\File('sftp_privateKey');

		if ($R['sftp']['removePrivateKey']) {
			unset($sftpDetails['privateKey']);
		}
		elseif ($uploadedFile->hasValidFile()) {
			$sftpDetails['privateKey'] = \App\Amadeus\Config::getInstance()->encryptStr($uploadedFile->getContents());
			$sftpDetails = array_filter($sftpDetails);
		}
		else {
			// keep private key if defined in the DB
			$sftpDetailsDb = unserialize((string)\App\Amadeus\Config::getInstance()->get("sftp"));
			if ($sftpDetailsDb && isset($sftpDetailsDb['privateKey'])) {
				$sftpDetails['privateKey'] = $sftpDetailsDb['privateKey'];
			}

		}


		//////////////////////////////////////////////////////////////////////////////////////
		// SAVE DATA ON AMADEUS CONFIG
		\App\Amadeus\Config::getAdmin()->setAll([
			"importPassengerEmail" => 						$R['importPassengerEmail'],
			"importPassengerEmail_ignoredAddresses" => 		serialize(array_values(array_filter((array)$R['importPassengerEmail_ignoredAddresses']))),
			"importPassengerTelephone" => 					$R['importPassengerTelephone'],
			"importPassengerTelephone_ignoredPhoneNumbers" => serialize(array_values(array_filter((array)$R['importPassengerTelephone_ignoredPhoneNumbers']))),
			"importServiceFeeForService" => 				$R['importServiceFeeForService'],
			"importServiceFeeForServiceCurrency" => 		$R['importServiceFeeForServiceCurrency'],
			"importDiscountForService" => 					$R['importDiscountForService'],
			"importDiscountForServiceCurrency" => 			$R['importDiscountForServiceCurrency'],
			"importCommissionForService" => 				$R['importCommissionForService'],
			"importCommissionForServiceCurrency" => 		$R['importCommissionForServiceCurrency'],
			"importInvalidReissues" => 						$R["importInvalidReissues"],
			"importHotelSupplierSource" => 					$R["importHotelSupplierSource"],
			"importHotelFormOfPaymentSource" => 			$R["importHotelFormOfPaymentSource"],
			"importCarFormOfPaymentSource" => 				$R["importCarFormOfPaymentSource"],
			"ignoreSupplierOnDocuments" => 					serialize(array_filter((array)$R['ignoreSupplierOnDocuments'])),
			"taxManipulationsMatrix" => 					base64_encode(gzencode(serialize(array_values(array_filter((array)$R['taxManipulationsMatrix'], function ($row) {
					return ($row['service'] || $row['offerLocationCriterion']) && $row['taxCode'];
				}))))),
			'vatPercent' =>									serialize((array)$R['vatPercent']),
			'sftp' =>										serialize(array_filter($sftpDetails)?$sftpDetails:[]),
		]);

		\App\Amadeus\Config::getAdmin()->save();

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

	/**
	 * Render a new matrix row
	 * @param array $R
	 * @return \Engine\Mvc\Response\Html
	 */
	protected function actionGenerateInputMatrixRow($R)
	{
		$matrix = \Engine\Cache\General::getInstance('disk')->get($R['inputMatrixStorageId']);
		if (!$matrix) {
			throw new \Engine\Mvc\ControllerException("Matrix not found");
		}

		$view = $this->buildViewObjectFromCurrentModuleForAction('index');

		return new \Engine\Mvc\Response\Json(['responseRow'=>$view->renderInputMatrixRowOnAjaxRequest($matrix, $R['index'], $R['counter'])]);
	}

}
