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

class View_Utils_FormAdmin extends \App\Mvc\View_Utils_FormAbstract
{

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\View_Utils_FormAbstract::getForm()
	 */
	public function getForm()
	{
		$form=\Engine\Form\General::create();
		$form->setStyle('width', '300');

		// add container
		$fieldset = \Engine\Form\Container\Fieldset::create('');
		$form->addContainer($fieldset);

		// importPassengerEmail
		$importPassengerEmail = new \Engine\Form\Input\Select($this->lang['index']['formFields']['importPassengerEmail'], 'importPassengerEmail', $this->values['importPassengerEmail'], [
			'' => 												$this->globalLang['no'],
			'fromAP' => 										$this->lang['index']['formFields']['importPassengerEmail_fromAP'],
			'fromRemarks' => 									$this->lang['index']['formFields']['importPassengerEmail_fromRemarks'],
			'fromSSR_CTCE' => 									$this->lang['index']['formFields']['importPassengerEmail_fromSSR_CTCE'],
			'fromSSR_CTCE_then_remark_then_AP' => 				$this->lang['index']['formFields']['importPassengerEmail_fromSSR_CTCE_then_remark_then_AP'],
		]);
		$fieldset->addElement($importPassengerEmail);

		// importPassengerEmail_ignoredAddresses
		$importPassengerEmail_ignoredAddresses = new \Engine\Form\Input\Cloned_Text($this->lang['index']['formFields']['importPassengerEmail_ignoredAddresses'], 'importPassengerEmail_ignoredAddresses', $this->values['importPassengerEmail_ignoredAddresses']);
		$importPassengerEmail_ignoredAddresses->setDetails($this->lang['index']['formFields']['importPassengerEmail_ignoredAddresses_']);
		$fieldset->addElement($importPassengerEmail_ignoredAddresses);

		// importPassengerTelephone
		$importPassengerTelephone = new \Engine\Form\Input\Select($this->lang['index']['formFields']['importPassengerTelephone'], 'importPassengerTelephone', $this->values['importPassengerTelephone'], [
			'' => 				$this->globalLang['no'],
			'fromAP' => 		$this->lang['index']['formFields']['importPassengerTelephone_fromAP'],
		]);
		$fieldset->addElement($importPassengerTelephone);

		// importPassengerTelephone_ignoredPhoneNumbers
		$importPassengerTelephone_ignoredPhoneNumbers = new \Engine\Form\Input\Cloned_Text($this->lang['index']['formFields']['importPassengerTelephone_ignoredPhoneNumbers'], 'importPassengerTelephone_ignoredPhoneNumbers', $this->values['importPassengerTelephone_ignoredPhoneNumbers']);
		$importPassengerTelephone_ignoredPhoneNumbers->setDetails($this->lang['index']['formFields']['importPassengerTelephone_ignoredPhoneNumbers_']);
		$fieldset->addElement($importPassengerTelephone_ignoredPhoneNumbers);

		// set controlled elements
		$importPassengerEmail->setControlledElements([
			'' => [$importPassengerEmail_ignoredAddresses],
		], 'enable');

		$importPassengerTelephone->setControlledElements([
			'' => [$importPassengerTelephone_ignoredPhoneNumbers],
		], 'enable');

		$ignoreSupplierOnDocuments = new \Engine\Form\Input\KeyValueCheckboxes($this->lang['index']['formFields']['ignoreSupplierOnDocuments'], 'ignoreSupplierOnDocuments', $this->values['ignoreSupplierOnDocuments']);
		$ignoreSupplierOnDocuments->setDetails($this->lang['index']['formFields']['ignoreSupplierOnDocuments_']);
		$ignoreSupplierOnDocuments->setAssociationsList([
			'ticketing' => 				'ticketing',
			'reissue' => 				'reissue',
			'EMD' => 					'EMD',
			'MCO' => 					'MCO',
			'car' => 					'car',
			'hotel' => 					'hotel',
			'transfer' => 				'transfer',
			'groundTransportation'	=>	'ground transportation',
			'insurance'	=>				'insurance',
			'misc'		=>				'misc',
		]);
		$ignoreSupplierOnDocuments->setPossibleValues([
			'' => 				'unset',
			'cash' => 			'cash',
			'CC' => 			'CC',
			'virtual CC'	=>	'virtual CC',
			'government' => 	'government',
			'check'		=>		'check',
			'invoice'	=>		'invoice',
		]);
		$ignoreSupplierOnDocuments->setStyle('highlight', 'current_if_set');
		$fieldset->addElement($ignoreSupplierOnDocuments);

		// add container
		$fieldset = \Engine\Form\Container\Fieldset::create('');
		$form->addContainer($fieldset);


		// importServiceFeeForService & importServiceFeeForServiceCurrency
		$importCurrencyPossibleValues = [
			'serviceFeeCurrency' => 'remark serviceFeeCurrency',
		];
		foreach (\App\Config\Currencies::getInstance()->getSimple() as $c) {
			$importCurrencyPossibleValues[$c] = sprintf("force to %s", $c);
		}

		$serviceFeeContainer = new \Engine\Form\Input\ElementWithElements($this->lang['index']['formFields']['importServiceFeeForService'], null, []);
		$serviceFeeContainer->addElement(
			\Engine\Form\Input\Select::create(null, 'importServiceFeeForService', $this->values['importServiceFeeForService'], [
				'' => 				$this->globalLang['no'],
				'all' => 			$this->lang['index']['formFields']['importServiceFeeForService_all'],
				'ticketing,EMD' =>	$this->lang['index']['formFields']['importServiceFeeForService_ticketingAndEmd'],
				'ticketing' => 		$this->lang['index']['formFields']['importServiceFeeForService_ticketing'],
			])
			, 'main' );
		$serviceFeeContainer->addElement(
			\Engine\Form\Input\Select::create(null, 'importServiceFeeForServiceCurrency', $this->values['importServiceFeeForServiceCurrency'], $importCurrencyPossibleValues)
		, 'post');
		$serviceFeeContainer->setStyle('renderMode', 'inline');
		$fieldset->addElement($serviceFeeContainer);

		// importDiscountForService & importDiscountForServiceCurrency
		$importCurrencyPossibleValues = [
			'discountCurrency' => 'remark discountCurrency',
		];
		foreach (\App\Config\Currencies::getInstance()->getSimple() as $c) {
			$importCurrencyPossibleValues[$c] = sprintf("force to %s", $c);
		}
		$serviceFeeContainer = new \Engine\Form\Input\ElementWithElements($this->lang['index']['formFields']['importDiscountForService'], null, []);
		$serviceFeeContainer->addElement(
			\Engine\Form\Input\Select::create(null, 'importDiscountForService', $this->values['importDiscountForService'], [
				'' => 				$this->globalLang['no'],
				'all' => 			$this->lang['index']['formFields']['importDiscountForService_all'],
			])
			, 'main' );
		$serviceFeeContainer->addElement(
			\Engine\Form\Input\Select::create(null, 'importDiscountForServiceCurrency', $this->values['importDiscountForServiceCurrency'], $importCurrencyPossibleValues)
		, 'post');
		$serviceFeeContainer->setStyle('renderMode', 'inline');
		$fieldset->addElement($serviceFeeContainer);


		// importCommissionForService & importCommissionForServiceCurrency
		$importCurrencyPossibleValues = [
			'commissionCurrency' => 'remark commissionCurrency',
		];
		foreach (\App\Config\Currencies::getInstance()->getSimple() as $c) {
			$importCurrencyPossibleValues[$c] = sprintf("force to %s", $c);
		}
		$commissionContainer = new \Engine\Form\Input\ElementWithElements($this->lang['index']['formFields']['importCommissionForService'], null, []);
		$commissionContainer->addElement(
			\Engine\Form\Input\Select::create(null, 'importCommissionForService', $this->values['importCommissionForService'], [
				'' => 				$this->globalLang['no'],
				'ticketing' => 		$this->lang['index']['formFields']['importCommissionForService_ticketing'],
				'all' => 			$this->lang['index']['formFields']['importCommissionForService_all'],
			])
			, 'main' );
		$commissionContainer->addElement(
			\Engine\Form\Input\Select::create(null, 'importCommissionForServiceCurrency', $this->values['importCommissionForServiceCurrency'], $importCurrencyPossibleValues)
		, 'post');
		$commissionContainer->setStyle('renderMode', 'inline');
		$fieldset->addElement($commissionContainer);

		// importInvalidReissues
		$importInvalidReissues = \Engine\Form\Input\Select::create($this->lang['index']['formFields']['importInvalidReissues'], 'importInvalidReissues', $this->values['importInvalidReissues'], [
			'' => 					$this->globalLang['no'],
			'standaloneTicket' => 	$this->lang['index']['formFields']['importInvalidReissues_standaloneTicket'],
		]);
		$fieldset->addElement($importInvalidReissues);

		// importHotelSupplierSource
		$importHotelSupplierSource = \Engine\Form\Input\Select::create($this->lang['index']['formFields']['importHotelSupplierSource'], 'importHotelSupplierSource', $this->values['importHotelSupplierSource'], [
			'1A' => 					$this->lang['index']['formFields']['importHotelSupplierSource_1A'],
			'hotelName' => 				$this->lang['index']['formFields']['importHotelSupplierSource_hotelName'],
			'chainCode' => 				$this->lang['index']['formFields']['importHotelSupplierSource_chainCode'],
		]);
		$fieldset->addElement($importHotelSupplierSource);

		// importHotelFormOfPaymentSource
		$importHotelFormOfPaymentSource = \Engine\Form\Input\Select::create($this->lang['index']['formFields']['importHotelFormOfPaymentSource'], 'importHotelFormOfPaymentSource', $this->values['importHotelFormOfPaymentSource'], [
			'G,RM,RIU,FP' =>$this->lang['index']['formFields']['importHotelFormOfPaymentSource_G_RM_RIU_FP'],
			'G,RM,RIU' =>  	$this->lang['index']['formFields']['importHotelFormOfPaymentSource_G_RM_RIU'],
			'RM,RIU,FP' =>  $this->lang['index']['formFields']['importHotelFormOfPaymentSource_RM_RIU_FP'],
			'G,RM' =>  		$this->lang['index']['formFields']['importHotelFormOfPaymentSource_G_RM'],
		]);
		$fieldset->addElement($importHotelFormOfPaymentSource);

		// importCarFormOfPaymentSource
		$importCarFormOfPaymentSource = \Engine\Form\Input\Select::create($this->lang['index']['formFields']['importCarFormOfPaymentSource'], 'importCarFormOfPaymentSource', $this->values['importCarFormOfPaymentSource'], [
			'G,RM,RIU,FP' =>$this->lang['index']['formFields']['importCarFormOfPaymentSource_G_RM_RIU_FP'],
			'G,RM,RIU' =>  	$this->lang['index']['formFields']['importCarFormOfPaymentSource_G_RM_RIU'],
			'RM,RIU,FP' =>  $this->lang['index']['formFields']['importCarFormOfPaymentSource_RM_RIU_FP'],
			'G,RM' =>  		$this->lang['index']['formFields']['importCarFormOfPaymentSource_G_RM'],
		]);
		$fieldset->addElement($importCarFormOfPaymentSource);

		// vat percent
		$CFG = \Engine\Loader_Cfg::getInstance()->getGlobal();
		$vatPercent = new \App\Form\Input\MultipliedText($this->lang['index']['formFields']['vatPercent'], 'vatPercent', $this->values['vatPercent']);
		$vatPercent->setMultiplier(count($CFG['countriesCriteria']));
		$vatPercent->setMultiplierLabelKeys($CFG['countriesCriteria']);
		$vatPercent->setMultiplierLabels($CFG['countriesCriteria']);
		$vatPercent->setStyle('CSSClass', 'input-multipliedElementLabelTop');
		$vatPercent->setMultiplierLabelVisibility(true);
		$vatPercent->setValidatorParam('minValue', 0);
		$vatPercent->setValidatorParam('maxValue', 100);
		$vatPercent->setValidatorParam('type', 'float');
		$fieldset->addElement($vatPercent);

		// add the tax manipulations matrix
		$matrix = $this->generateTaxManipulationsMatrix();
		$matrix
			->setName('taxManipulationsMatrix')
			->setValue($this->values['taxManipulationsMatrix']);

		$fieldsetTaxManipulations = \Engine\Form\Container\Fieldset::create($this->lang['index']['formFields']['taxManipulationsMatrix_title'])->setCollapsible(true);
		$tooltipMarkdown = <<<MD
**1. Move Tax to Supplier**

The tax amount is moved from the tax list to the supplier price. Client total remains unchanged — the tax is simply reclassified internally.

**2. Distribute Tax Over Supplier / Tax / Commission (Amadeus-only)**

Used when a tax code (e.g. "K7") represents VAT spread across price components. The system splits it mathematically:

1. **Find the tax** — locate the tax code and sum its total value
2. **Look up VAT rules** — based on flight route and service type, fetch TINA's VAT percentages
3. **Calculate portions:**
   - Supplier VAT = VAT% × supplier price
   - Tax VAT = VAT% × remaining taxes (after removing K7)
   - Commission VAT = VAT% × commission
4. **Validate** — portions must sum to original K7 amount (±2¢ tolerance)
5. **Apply the split:**
   - Remove K7 from tax list
   - Add commission VAT to commission field (if non-zero)
   - Add customVat placeholder with tax VAT portion
   - Add supplier VAT to supplier price
   - Recalculate totals

**Field Reference:**
- **Tax Code** — mandatory, 2-letter code to manipulate (e.g. "K7")
- **Existing Tax Code** — optional, condition check: rule only applies if this tax code exists in the transaction
- **Operation** — mandatory, select the manipulation type
- **Ignore Tax Code** — optional, 2-letter code to exclude from VAT calculations
- **Stop On Apply** — optional, checkbox to halt processing after this rule matches

The K7 value is redistributed proportionally into supplier cost, commission, and a new VAT entry — matching TINA's pricing engine calculations.
MD;

		$converter = new \League\CommonMark\CommonMarkConverter([
			'html_input' => 'escape',
			'allow_unsafe_links' => true,
		]);
		$fieldsetTaxManipulations->setTooltip(sprintf("<div class='tooltip-wide-markdown'>%s</div>", $converter->convert($tooltipMarkdown)->getContent()));
		$fieldsetTaxManipulations->addElement($matrix);
		$form->addContainer($fieldsetTaxManipulations);


		// add container, for SSH access
		$fieldset = \Engine\Form\Container\Fieldset::create($this->lang['index']['formFields']['sftp']);
		$fieldset->setCollapsible(true)->setCollapsed(true);
		$form->addContainer($fieldset);

		$hostname = new \Engine\Form\Input\Text($this->lang['index']['formFields']['sftp_hostname'], 'sftp[hostname]', $this->values['sftp']['hostname']??'');
		$fieldset->addElement($hostname);

		$port = new \Engine\Form\Input\Text($this->lang['index']['formFields']['sftp_port'], 'sftp[port]', $this->values['sftp']['port']??'22');
		$port->setPlaceholder('22');	// default port, as a placeholder
		$fieldset->addElement($port);

		$username = new \Engine\Form\Input\Text($this->lang['index']['formFields']['sftp_username'], 'sftp[username]', $this->values['sftp']['username']??'');
		$fieldset->addElement($username);

		$password = new \Engine\Form\Input\Password($this->lang['index']['formFields']['sftp_password'], 'sftp[password]', $this->values['sftp']['password']??'');
		$fieldset->addElement($password);

		$privateKey = new \Engine\Form\Input\File($this->lang['index']['formFields']['sftp_privateKey'], 'sftp_privateKey', $this->values['sftp']['privateKey']??'');
		$fieldset->addElement($privateKey);

		if ($this->values['sftp']['privateKeyDetails']) {
            $privateKey->setDetails(sprintf($this->lang['index']['formFields']['sftp_privateKeyDetails'],
                $this->values['sftp']['privateKeyDetails']->format
            ));

			// add checkbox to remove private key
			$removePrivateKey = new \Engine\Form\Input\Checkbox($this->lang['index']['formFields']['sftp_removePrivateKey'], 'sftp[removePrivateKey]', $this->values['sftp']['removePrivateKey']??'');
			$fieldset->addElement($removePrivateKey);
        }

		// the submit button
		$form->addElement(new \Engine\Form\Input\Hidden(null, $this->submitButtonName, 1));

		// submit button
		$form->addButton(new \Engine\Form\Button\Submit('save'));

		return $form;
	}

	public function generateTaxManipulationsMatrix()
	{
		$storageKey = sprintf("%s.%s:%s", str_replace('\\', '', __METHOD__), CURRENT_ID_USER, \Engine\RandomGenerator::randomString(6));
		$matrix = new \Engine\Form\Input\Matrix();

		$matrix->setUrl(\Engine\Mvc\Dispatcher::getInstance()->getAppUrl($this->controller->getModule(), 'generateInputMatrixRow', [
			'counter' => 				1,
			'inputMatrixStorageId' =>	$storageKey,
		]));


		$matrix->addRow($row = new \Engine\Form\Input\Matrix\Row());

		// add the 2 needed columns
		$row
			// conditions
			->addCell($conditionCell1 = new \Engine\Form\Input\Matrix\Cell($this->lang['index']['formFields']['taxManipulationsMatrix']['cell']['service']))
			->addCell($conditionCell2 = new \Engine\Form\Input\Matrix\Cell($this->lang['index']['formFields']['taxManipulationsMatrix']['cell']['location']))
			->addCell($conditionCell3 = new \Engine\Form\Input\Matrix\Cell($this->lang['index']['formFields']['taxManipulationsMatrix']['cell']['taxCode_exists']))
			// actions
			->addCell($actionCell1 = new \Engine\Form\Input\Matrix\Cell($this->lang['index']['formFields']['taxManipulationsMatrix']['cell']['taxCode']))
			->addCell($actionCell2 = new \Engine\Form\Input\Matrix\Cell($this->lang['index']['formFields']['taxManipulationsMatrix']['cell']['operation']))
			->addCell($actionCell3 = new \Engine\Form\Input\Matrix\Cell($this->lang['index']['formFields']['taxManipulationsMatrix']['cell']['ignoreTaxCode']))
			->addCell($actionCell4 = new \Engine\Form\Input\Matrix\Cell($this->lang['index']['formFields']['taxManipulationsMatrix']['cell']['stopOnApply']))
		;

		$conditionCell1->addElement($service = \Engine\Form\Input\Select::create(null, "service", null, [
				'ticketing' => 	$this->lang['index']['formFields']['taxManipulationsMatrix']['service']['ticketing'],
				'reissue' => 	$this->lang['index']['formFields']['taxManipulationsMatrix']['service']['reissue'],
				'refund' => 	$this->lang['index']['formFields']['taxManipulationsMatrix']['service']['refund'],
				'EMD' => 		$this->lang['index']['formFields']['taxManipulationsMatrix']['service']['EMD'],
				'car' => 		$this->lang['index']['formFields']['taxManipulationsMatrix']['service']['car'],
				'hotel' => 		$this->lang['index']['formFields']['taxManipulationsMatrix']['service']['hotel'],
			])
			->showDefaultOption()
			->setStyle('highlight', 'current_if_set')
		);

		$conditionCell2->addElement($offerLocationCriterion = \App\Form\Input\Select_CountryCriterion::create(null, "offerLocationCriterion", null)
			->showDefaultOption()
			->setStyle('highlight', 'current_if_set')
		);

		$conditionCell3->addElement($offerLocationCriterion = \Engine\Form\Input\Text::create(null, "taxCode_exists", null)
			->setValidatorParam('fixLength', 2)
			->setValidatorParam('case','upper')
			->setMandatory()
			->setWidth(50)
		);

		$actionCell1->addElement($taxCode = \Engine\Form\Input\Text::create(null, "taxCode", null)
			->setValidatorParam('fixLength', 2)
			->setValidatorParam('case','upper')
			->setMandatory()
			->setWidth(50)
		);

		$actionCell2->addElement($action = \Engine\Form\Input\Select::create(null, "action", null, [
				'moveTaxToSupplier' => 						$this->lang['index']['formFields']['taxManipulationsMatrix']['action']['moveTaxToSupplier'],
				'distributeTaxOverSupplierTaxCommission' => $this->lang['index']['formFields']['taxManipulationsMatrix']['action']['distributeTaxOverSupplierTaxCommission'],
			])
			->setWidth(0)
		);

		$actionCell3->addElement($ignoreTaxCode = \Engine\Form\Input\Text::create(null, "ignoreTaxCode", null)
			->setValidatorParam('fixLength', 2)
			->setValidatorParam('case','upper')
			->setWidth(50)
		);

		$actionCell4->addElement($action = \Engine\Form\Input\Checkbox::create(null, "stopOnApply", null)
			->setWidth(0)
		);

		// the storage "engine" could be used, but the persistent storage shouldn't be used, as it would just pollute the storage backend. Something more like a semi-persistent storage could be used here (a TTL-guaranteed cache maybe?)
		$matrix->setSaveHandler(function($matrix) use ($storageKey) {
			\Engine\Cache\General::getInstance('disk')->set($storageKey, $matrix, 8*60*60);
		});

		// TODO: modifica testele pt pluginurile to-be-removed

		return $matrix;
	}
}
