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

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', '100');

		// add container
		$fieldset = \Engine\Form\Container\Fieldset::create($this->lang['index']['formFields']['cronjobConfigFieldset']);
		$fieldset->setCollapsible();
		$form->addContainer($fieldset);

		$fldSystems = \Engine\Form\Input\Checkboxes::create($this->lang['index']['formFields']['systems'], "systems", $this->values['systems']);

		// build the systems list
		$possibleValues = [];
		$sysListObj = new \App\EntityList\ImportedOrdersSystems();
		$sysListObj->setColumns(['name', 'code']);
		$sysListObj->setFilter('extResSys.active', '=', 1);
		$sysListObj->setOrderBy('extResSys.name', 'ASC');
		foreach ($sysListObj->exportRecords() as $rec) {
			$possibleValues[$rec['code']] = $rec['name'];
		}
		$fldSystems->setPossibleValues($possibleValues);
		$fldSystems->setStyle('renderMode', 'aligned');
		$fieldset->addElement($fldSystems);

		// build the services list
		$fldServices = \Engine\Form\Input\Checkboxes::create($this->lang['index']['formFields']['services'], "services", $this->values['services']);
		$possibleValues = \App\Config\Services_Basic::getInstance()->getListLinearSimple();
		$fldServices->setPossibleValues($possibleValues);
		$fldServices->setStyle('renderMode', 'aligned');
		$fieldset->addElement($fldServices);


		$fieldsetSupplierInvoice = \Engine\Form\Container\Fieldset::create($this->lang['index']['formFields']['supplierInvoice']);
		$form->addContainer($fieldsetSupplierInvoice);

		// VAT data
		$serviceKeys = 				[ 'ticketing', 'EMD', 'ADM', ];
		$destinationTypeFilters = 	['international', 'domestic', 'undefined', ];

		foreach ($serviceKeys as $key) {
			$fieldsetSupplierInvoiceVat = \Engine\Form\Container\Fieldset::create($this->lang['index']['formFields']["supplierInvoice_{$key}_fieldsetLabel"]);
			$fieldsetSupplierInvoiceVat->setCollapsible(true);
			$fieldsetSupplierInvoice->addContainer($fieldsetSupplierInvoiceVat);

			$supplierInvoicesVats = \App\Config\SupplierInvoice_Vats::getInstance()->getAll();
			$ticketingVatArr = [];
			if ($supplierInvoicesVats) {
				$ticketingVatArr = $supplierInvoicesVats[$this->values[$key]];
				$ticketingVatArr = array_combine(array_keys($ticketingVatArr['list']), array_keys($ticketingVatArr['list']));
			}

			foreach ($destinationTypeFilters as $dtf) {
				$vatSupplierInternational = new \App\Form\Input\Select_SupplierInvoiceVats(
					$this->lang['index']['formFields']["supplierInvoice_{$dtf}_supplier"],
					"supplierInvoiceVat[{$key}][{$dtf}][supplier]",
					$this->values['supplierInvoiceVat'][$key][$dtf]['supplier']
				);
				$fieldsetSupplierInvoiceVat->addElement($vatSupplierInternational);

				$vatTaxInternational = new \App\Form\Input\Select_SupplierInvoiceVats(
					$this->lang['index']['formFields']["supplierInvoice_{$dtf}_tax"],
					"supplierInvoiceVat[{$key}][{$dtf}][tax]",
					$this->values['supplierInvoiceVat'][$key][$dtf]['tax']
				);
				$fieldsetSupplierInvoiceVat->addElement($vatTaxInternational);
			}
		}


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

		$fieldsetTaxManipulations = \Engine\Form\Container\Fieldset::create('');
		$fieldsetTaxManipulations->addElement($matrix);
		$form->addContainer($fieldsetTaxManipulations);

		// add container
		$fieldset = \Engine\Form\Container\Fieldset::create($this->lang['index']['formFields']['bspSettlementSettings']);
		$fieldset->setCollapsible();
		$form->addContainer($fieldset);

		$fldCommissionHandling = \Engine\Form\Input\Select::create($this->lang['index']['formFields']['commissionHandling'], "commissionHandling", $this->values['commissionHandling'], [
			'useInitialCommission' => 		$this->lang['index']['formFields']['commissionHandling_useInitialCommission'],
			'useCalculatedCommission' => 	$this->lang['index']['formFields']['commissionHandling_useCalculatedCommission'],
		]);
		$fieldset->addElement($fldCommissionHandling);


		// 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->addCell($cell1 = new \Engine\Form\Input\Matrix\Cell($this->lang['index']['formFields']['taxManipulationsMatrix']['cell']['service']))
			->addCell($cell3 = new \Engine\Form\Input\Matrix\Cell($this->lang['index']['formFields']['taxManipulationsMatrix']['cell']['taxCode']))
			->addCell($cell4 = new \Engine\Form\Input\Matrix\Cell($this->lang['index']['formFields']['taxManipulationsMatrix']['cell']['operation']));

		$cell1->addElement( \Engine\Form\Input\Select::create(null, "service", null, [
				'issue' => 		$this->lang['index']['formFields']['taxManipulationsMatrix']['service']['issue'],
				'reissue' => 	$this->lang['index']['formFields']['taxManipulationsMatrix']['service']['reissue'],
				'ADM' => 		$this->lang['index']['formFields']['taxManipulationsMatrix']['service']['ADM'],
			])
			->showDefaultOption()
			->setStyle('highlight', 'current_if_set')
		);

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

		$cell4->addElement( \Engine\Form\Input\Select::create(null, "action", null, [
				'moveTaxToSupplier' => $this->lang['index']['formFields']['taxManipulationsMatrix']['action']['moveTaxToSupplier'],
			])
			->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;
	}
}
