<?php
namespace Modules\Invoices\SupplierInvoices\Management;

class View_Insert extends \App\Mvc\View_Window_GeneralAbstract
{
	protected $renderingTemplate='insert.tpl';

	public function render()
	{

		$CFG = \Engine\Loader_Cfg::getInstance()->getGlobal();

		$this->setOutputVar('servicesFieldsSettings', $this->input['servicesFieldsSettings']);
		$this->setOutputVar('supplierInvoicesVats', $this->input['supplierInvoicesVats']);
		$this->setOutputVar('currencyDecimals', \App\Config\CurrencyDecimals::getAll());
		$this->setOutputVar('invoiceIsBalanced', $this->input['invoiceIsBalanced']);
		$this->setOutputVar('idBankAccount', (int)$this->input['supplierData']['bankAccount']);

		return parent::render();
	}

	/**
	 * Retrieves the extra information.
	 *
	 * @return \Engine\Form\Container\Simple The container with the extra information.
	 */
	public function getExtraInfo()
	{
		$container = \Engine\Form\Container\Simple::create();

		$container = $this->generateInputFromArray($container, $this->input['extraInfo'], []);

		return $container;
	}

	/**
	 * A recursive function to generate hidden form inputs from a nested array.
	 *
	 * @param \Engine\Form\Container\Simple $container The form container to add inputs to.
	 * @param array $dataArray The array containing data to generate inputs from.
	 * @param array $parents The array of parent keys for nesting inputs.
	 * @return \Engine\Form\Container\Simple
	 */
	private function generateInputFromArray(\Engine\Form\Container\Simple $container, array $dataArray, array $parents)
	{
		foreach ($dataArray as $key => $value) {
			if (is_array($value)) {
				$p = $parents;
				$p[] = $key;
				$this->generateInputFromArray($container, $value, $p);
			}
			else {
				$parentsPath = "";
				if ($parents) {
					$parentsPath = "[" . implode('][', $parents) . "]";
				}
				$inputName = "extraInfo" . $parentsPath . "[{$key}]";

				$fld = new \Engine\Form\Input\Hidden(null, $inputName, $value);
				$container->addElement($fld);
			}
		}

		return $container;
	}

	/**
	 * Get fieldset for supplier details
	 * @return \Engine\Form\Container\Fieldset
	 */
	public function getSupplierDetails()
	{
		$fieldset = \Engine\Form\Container\Fieldset::create($this->lang['formFieldTh']['supplierFields']);
		$fieldset->setId("form_Supplier");
		$fieldset->setStyle('width', 200);

		$supplierInvoiceCfg =  \Entity\SupplierInvoice::loadCFG();

		// supplier name
		$fldSupplierName = new \App\Form\Input\Autocomplete_Supplier($this->lang['formField']['supplierFields']['supplier'], 'supplierData[idSupplier]', $this->input['supplierData']['idSupplier']);
		$fldSupplierName->importFromConfig($supplierInvoiceCfg['idSupplier']);
		$fldSupplierName->onPostSelect("
			MVC.showSupplierAutocompleteButtons(this.element.code.up('fieldset#form_Supplier').down('div.elementOperationsButtons'));
			MVC.loadRemoteSupplierDetails(\$F(this.element.code), $('{$fieldset->getId()}'));
			MVC.updateInvoiceDueDate();
			MVC.revalidateElement($('invoiceData_invoiceNumber_'));
		");


		$fldSupplierName->onCancel("
			MVC.hideSupplierAutocompleteButtons(this.element.code.up('fieldset#form_Supplier').down('div.elementOperationsButtons'));
			MVC.refreshSupplierDetails({}, $('{$fieldset->getId()}'));
			MVC.updateInvoiceDueDate();
			MVC.revalidateElement($('invoiceData_invoiceNumber_'));
		");

		// compose custom html
		$customHtml = '';
		if (\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('Modules/Partners/Suppliers-insert')) {
			$customHtml.= "<a style='display:none' href='#;'";
			$customHtml.= "onclick='supplierUpdate(\$F(\"supplierData_idSupplier_\"));' class='link supplierUpdate'";
			$customHtml.= ">".$this->lang['buttons']['editSupplier']."</a>";
		}

		if ($this->controller->getAction() == 'insert' and $this->input['supplierData']['reservationId']) {
			$customHtml.= "<a href='#;'";
			$customHtml.= "onclick=\"
				RemoteHtmlViewHandler
					.attach(this, '{$this->lang['remoteTitle']['supplierSuggestions']}')
					.loadUrl( MVC.appUrl('Invoices/SupplierInvoices/Management', 'supplierSuggestions') + '&id={$this->input['supplierData']['reservationId']}' );
			\"";
			$customHtml.= ">".$this->lang['buttons']['supplierSuggestions']."</a>";
		}

		$customHtml.= "<ul><li> <var style='display:none'";
		$customHtml.= " onclick='RemoteLoad.load(this, MVC.appUrl(\"RemoteData/InfoBox\", \"supplier\", { \"id\": \$F(\"supplierData_idSupplier_\")}))'";
		$customHtml.= " class='icon-remoteLoad supplierInfo'";
		$customHtml.= "></var></li></ul>";

		$fldSupplierName->setCustomHTML($customHtml, 'postOperations');

		if ($this->input['invoiceIsBalanced']) {
			$fldSupplierName->setDisabled(true);
			$fieldset->addElement(\Engine\Form\Input\Hidden::create(null, 'supplierData_idSupplier_', $this->input['supplierData']['idSupplier']['id']));
		}

		$fieldset->addElement($fldSupplierName);

		// supplier company
		$fldSupplierCompany = new \Engine\Form\Input\Label($this->lang['formField']['supplierFields']['company'], 'company');
		$fieldset->addElement($fldSupplierCompany);

		// supplier regno
		$fldSupplierRegNo = new \Engine\Form\Input\Label($this->lang['formField']['supplierFields']['regNo'], 'regNo');
		$fieldset->addElement($fldSupplierRegNo);

		// supplier fiscalCode
		$fldSupplierFiscalCode = new \Engine\Form\Input\Label($this->lang['formField']['supplierFields']['fiscalCode'], 'fiscalCode');
		$fieldset->addElement($fldSupplierFiscalCode);

		// bank account
		$fldBankAccount = new \Engine\Form\Input\Select($this->lang['formField']['supplierFields']['bankAccount'], 'supplierData[bankAccount]', $this->input['supplierData']['bankAccount']);
		$fldBankAccount->showDefaultOption(true);
		$fieldset->addElement($fldBankAccount);

		return $fieldset;
	}

	/**
	 * Get fieldset for invoice details
	 * @return \Engine\Form\Container\GeneralAbstract
	 */
	public function getInvoiceDetailsContainer()
	{
		$fieldset = \Engine\Form\Container\Fieldset::create($this->lang['formFieldTh']['supplierInvoiceField']);
		$fieldset->setStyle('width', 200);

		$supplierInvoiceCfg =  \Entity\SupplierInvoice::loadCFG();
		$invoiceData = $this->input['invoiceData'];

		// SUPPLIER INVOICE SERIES
		$fldInvoiceSeries = new \Engine\Form\Input\Text($this->lang['invoiceFields']['series'], 'invoiceData[invoiceSeries]', $invoiceData['invoiceSeries']);
		$fldInvoiceSeries->importFromConfig($supplierInvoiceCfg['invoiceSeries']);
		$fieldset->addElement($fldInvoiceSeries);

		// SUPPLIER INVOICE NUMBER
		$fldInvoiceNumber = new \Engine\Form\Input\Text($this->lang['invoiceFields']['number'], 'invoiceData[invoiceNumber]', $invoiceData['invoiceNumber']);
		$fldInvoiceNumber->importFromConfig($supplierInvoiceCfg['invoiceNumber']);

		$validatorAction = \Engine\Mvc\Dispatcher::getInstance()->getAppUrl('Modules/Invoices/SupplierInvoices/Management', 'validateInvoiceNumberUniqueness');
		$fldInvoiceNumber->setValidatorParam("AJAX", ['url'=>$validatorAction, 'gatherCallback'=>'return MVC.gatherCallback();']);

		if ($this->input['invoiceIsBalanced']) {
			$fldInvoiceNumber->setDisabled(true);
		}

		$fieldset->addElement($fldInvoiceNumber);

		// INVOICE DATE
		$fldInvoiceDate = new \Engine\Form\Input\Date($this->lang['invoiceFields']['date'], 'invoiceData[date]', $invoiceData['date']);
		$fldInvoiceDate->importFromConfig($supplierInvoiceCfg['invoiceDate']);
		$fldInvoiceDate->onChange("MVC.revalidateElement($('invoiceData_invoiceNumber_')); MVC.updateInvoiceDueDate();");
		$fldInvoiceDate->setMandatory(true);

		if ($this->input['invoiceIsBalanced']) {
			$fldInvoiceDate->setDisabled(true);

			// set hidden
			$fieldset->addElement(\Engine\Form\Input\Hidden::create('', 'oldInvoiceDate', $invoiceData['date']));
		}

		$fieldset->addElement($fldInvoiceDate);

		// DUE DATE
		$fldDueDate = new \Engine\Form\Input\Date($this->lang['invoiceFields']['dueDate'], 'invoiceData[dueDate]', $invoiceData['dueDate']);
		$fldDueDate->importFromConfig($supplierInvoiceCfg['dueDate']);
		$fieldset->addElement($fldDueDate);

		// FULFILLMENT DATE
		$fldFulfillmentDate = new \Engine\Form\Input\Date($this->lang['invoiceFields']['fulfillmentDate'], 'invoiceData[fulfillmentDate]', $invoiceData['fulfillmentDate']);
		$fldFulfillmentDate->importFromConfig($supplierInvoiceCfg['fulfillmentDate']);
		$fieldset->addElement($fldFulfillmentDate);

		// ESTIMATED PAYMENT DATE
		$fldEstPayDate = new \Engine\Form\Input\Date($this->lang['invoiceFields']['estPayDate'], 'invoiceData[estPayDate]', $invoiceData['estPayDate']);
		$fldEstPayDate->importFromConfig($supplierInvoiceCfg['estPayDate']);
		$fieldset->addElement($fldEstPayDate);

		// FORM OF PAYMENT
		$fldFormOfPayement = new \App\Form\Input\Select_FormOfPayment($this->lang['invoiceFields']['fop'], 'invoiceData[formOfPayment]', $invoiceData['formOfPayment']);
		$fldFormOfPayement->importFromConfig($supplierInvoiceCfg['formOfPayment']);
		$fldFormOfPayement->showDefaultOption(true);
		$fieldset->addElement($fldFormOfPayement);

		// RESPONSIBLE USER
		$fldResponsibleUser = new \App\Form\Input\Autocomplete_User($this->lang['invoiceFields']['responsibleUser'], 'invoiceData[idUser]', $invoiceData['idUser']);
		$fldResponsibleUser->importFromConfig($supplierInvoiceCfg['idUser']);
		$fieldset->addElement($fldResponsibleUser);

		// SUPPLIER CAN BE BLOCKED
		$fldBlockable = new \Engine\Form\Input\Checkbox($this->lang['invoiceFields']['cantBlock'], 'invoiceData[blockable]', $invoiceData['blockable']);
		$fldBlockable->importFromConfig($supplierInvoiceCfg['blockable']);
		$fieldset->addElement($fldBlockable);

		//  CONFIRM INVOICE
		$fldConfirm = new \Engine\Form\Input\Checkbox($this->lang['invoiceFields']['confirm'], 'invoiceData[confirm]', $invoiceData['confirm']);
		if (!\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('Modules/Invoices/SupplierInvoices-statusUpdate')) {
			$fldConfirm->setDisabled(true);
		}
		$fieldset->addElement($fldConfirm);

		return $fieldset;
	}

	/**
	 * Render invoice rows
	 * @return \Engine\Form\Container\Fieldset
	 */
	public function getInvoiceRows()
	{
		$supplierInvoiceCfg =  \Entity\SupplierInvoice::loadCFG();

		$fieldset = \Engine\Form\Container\Fieldset::create();

		$matrix = new \Engine\Form\Input\Matrix();
		$matrix->setName('invoiceRows');
		$matrix->setStyle('startIndex', $this->output['currentPage'] * $this->output['resultsPerPage']);

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

		// add matrix columns
		$columnDescription =	new \Engine\Form\Input\Matrix\Cell($this->lang['invoiceColumns']['description']);
		$columnDescription->setName('description');
		$columnDescription->setStyle('width', '250');
		$row->addCell($columnDescription);

		// id invoice rows
		$columnDescription->addElement(\Engine\Form\Input\Hidden::create(null, 'idInvoiceRow')->setStyle('CSSClass', 'idInvoiceRow'));

		// mark new row
		$columnDescription->addElement(\Engine\Form\Input\Hidden::create(null, '_isNewRow'));

		$columnServiceData = 	new \Engine\Form\Input\Matrix\Cell($this->lang['invoiceColumns']['serviceData']);
		$columnServiceData->setStyle('width', '600');
		$columnServiceData->setName('serviceData');
		$row->addCell($columnServiceData);

		$columnMeasureUnit = 	new \Engine\Form\Input\Matrix\Cell($this->lang['invoiceColumns']['measureUnit']);
		$row->addCell($columnMeasureUnit);

		$columnQuantity = 		new \Engine\Form\Input\Matrix\Cell($this->lang['invoiceColumns']['quantity']);
		$columnQuantity->setName('quantity');
		$row->addCell($columnQuantity);

		$columnUnitPrice = 		new \Engine\Form\Input\Matrix\Cell($this->lang['invoiceColumns']['unitPrice']);
		$columnUnitPrice->setName('unitPrice');
		$row->addCell($columnUnitPrice);

		$columnPrice = 			new \Engine\Form\Input\Matrix\Cell($this->lang['invoiceColumns']['price']);
		$columnPrice->setName('baseValue');
		$columnVat = 			new \Engine\Form\Input\Matrix\Cell($this->lang['invoiceColumns']['vat']);
		$columnVat->setName('vatValue');
		$columnTotal = 			new \Engine\Form\Input\Matrix\Cell($this->lang['invoiceColumns']['total']);
		$columnTotal->setName('total');

		$row->addCell($columnPrice)->addCell($columnVat)->addCell($columnTotal);

		// ADD INPUTS FOR COLUMN DESCRIPTION ////////////////////////////////////////////////////////////////////////////////////
		$containerDescription = \Engine\Form\Container\Table::create();

		// services list
		$fldServicesList = new \App\Form\Input\Select_Service(null, 'service');
		$fldServicesList->setStyle('width', '200');
		$fldServicesList->showDefaultOption(true);
		$fldServicesList->setMandatory($supplierInvoiceCfg['_special']['rowServiceCodeMandatory']);
		$fldServicesList->onChange("
			MVC.toggleServiceDataInput(\$F(this), this.up('tbody.clone'));
			MVC.supplierInvoice.validateInvoiceRowsPrices(this.up('tbody.clone'));
			MVC.supplierInvoice.recalculateInvoiceRowPrices(this.up('tbody.clone'), this);
		");
		$containerDescription->addElement($fldServicesList);

		// description
		$fldRowDescription = new \Engine\Form\Input\Textarea(null, 'description');
		$fldRowDescription->setStyle('width', '200');
		$containerDescription->addElement($fldRowDescription);

		// add container to column
		$columnDescription->addContainer($containerDescription);

		/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// ADD INPUTS FOR COLUMN SERVICE DATA ///////////////////////////////////////////////////////////////////////////////////////////
		/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		$containerServiceData = \Engine\Form\Container\Vl::create();
		$this->populateContainer($containerServiceData);
		$columnServiceData->addContainer($containerServiceData);

		//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//////// ADD INPUT FOR MEASURE UNIT COLUMN //////////////////////////////////////////////////////////////////////////////////////
		//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		$fldMeasureUnit = new \Engine\Form\Input\Text(NULL, 'measureUnit');
		$fldMeasureUnit->setStyle('width', '55');
		$columnMeasureUnit->addElement($fldMeasureUnit);


		//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//////// ADD INPUT FOR QUANTITY COLUMN //////////////////////////////////////////////////////////////////////////////////////
		//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		$fldQuantity = new \Engine\Form\Input\Text(NULL, 'quantity');
		$fldQuantity->setStyle('width', '55');
		$fldQuantity->onChange("
			MVC.supplierInvoice.validateInvoiceRowsPrices(this.up('tbody.clone'));
			MVC.supplierInvoice.recalculateInvoiceRowPrices(this.up('tbody.clone'), this);
		");
		$columnQuantity->addElement($fldQuantity);

		//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//////// ADD INPUT FOR UNIT PRICE COLUMN //////////////////////////////////////////////////////////////////////////////////////
		//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		$fldUnitPrice = new \Engine\Form\Input\Text(NULL, 'unitPrice');
		$fldUnitPrice->setStyle('width', '120');
		$fldUnitPrice->onChange("
			MVC.supplierInvoice.validateInvoiceRowsPrices(this.up('tbody.clone'));
			MVC.supplierInvoice.recalculateInvoiceRowPrices(this.up('tbody.clone'), this);
		");
		$columnUnitPrice->addElement($fldUnitPrice);

		//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//////// ADD INPUT FOR PRICE COLUMN //////////////////////////////////////////////////////////////////////////////////////
		//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		$fldBaseValue = new \Engine\Form\Input\Text(NULL, 'baseValue');
		$fldBaseValue->setStyle('width', '120');
		$fldBaseValue->onChange("
			MVC.supplierInvoice.validateInvoiceRowsPrices(this.up('tbody.clone'));
			MVC.supplierInvoice.recalculateInvoiceRowPrices(this.up('tbody.clone'), this);
		");
		$columnPrice->addElement($fldBaseValue);

		//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//////// ADD INPUT FOR VAT COLUMN //////////////////////////////////////////////////////////////////////////////////////
		//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		$containerVat = \Engine\Form\Container\Vl::create();

		$fldVatQuota = new \Engine\Form\Input\Select(NULL, 'vatQuota');
		$fldVatQuota->onChange("MVC.supplierInvoice.recalculateInvoiceRowPrices(this.up('tbody.clone'), this);");
		$fldVatQuota->setStyle('width', '120');
		$containerVat->addElement($fldVatQuota);

		$fldVat = new \Engine\Form\Input\Text(NULL, 'vat');
		$fldVat->setStyle('width', '120');
		$fldVat->onChange("
			MVC.supplierInvoice.validateInvoiceRowsPrices(this.up('tbody.clone'));
			MVC.supplierInvoice.recalculateInvoiceRowPrices(this.up('tbody.clone'), this);
		");
		$containerVat->addElement($fldVat);

		$columnVat->addContainer($containerVat);

		//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//////// ADD INPUT FOR TOTAL COLUMN //////////////////////////////////////////////////////////////////////////////////////
		//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		$fldTotal = new \Engine\Form\Input\Text(NULL, 'total');
		$fldTotal->setStyle('width', '120');
		$fldTotal->onChange("
			MVC.supplierInvoice.validateInvoiceRowsPrices(this.up('tbody.clone'));
			MVC.supplierInvoice.recalculateInvoiceRowPrices(this.up('tbody.clone'), this);
		");
		$columnTotal->addElement($fldTotal);

		// ROW FOOTER ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		$rowFooter = new \Engine\Form\Input\Matrix\RowFooter();
		$matrix->addRow($rowFooter);

		// column comments
		$columnComments = new \Engine\Form\Input\Matrix\Cell();
		$columnComments->setName('comments');

		$colspan = 4;

		$columnComments->setStyle('colspan', $colspan);

		$containerComments = \Engine\Form\Container\Table::create();
		$containerComments->addElement(\Engine\Form\Input\Textarea::create($this->lang['invoiceFields']['comments'], 'invoiceData[comments]', $this->input['invoiceData']['comments']));
		$containerComments->addElement(\App\Form\Input\Remarks::create($this->lang['invoiceFields']['remarks'], 'invoiceData[remarks]', $this->input['invoiceData']['remarks'])->setRemarksType('supplierInvoice'));
		$columnComments->addContainer($containerComments);
		$rowFooter->addCell($columnComments);

		// COlUMN TOTAL LABEL
		$columnTotalLabel = new \Engine\Form\Input\Matrix\Cell();

		$containerTotalLabel = \Engine\Form\Container\Table::create();
		$containerTotalLabel->addElement(\Engine\Form\Input\Label::create()->setLabel($this->lang['invoiceFields']['total']));
		$columnTotalLabel->addContainer($containerTotalLabel);
		$rowFooter->addCell($columnTotalLabel);

		// COLUMN TOTAL PRICE
		$columnTotalPrice = new \Engine\Form\Input\Matrix\Cell(null, 'totalPrice');
		$columnTotalPrice->setDisabled(true);
		$columnTotalPrice->addElement(\Engine\Form\Input\Text::create(null, 'totalPrice', $this->input['invoiceData']['totalPrice'])->setStyle('width', '120'));
		$rowFooter->addCell($columnTotalPrice);

		// COLUMN TOTAL VAT
		$columnTotalVat = new \Engine\Form\Input\Matrix\Cell(null, 'totalVat');
		$columnTotalVat->setDisabled(true);
		$columnTotalVat->addElement(\Engine\Form\Input\Text::create(null, 'totalVat', $this->input['invoiceData']['totalVat'])->setStyle('width', '120'));
		$rowFooter->addCell($columnTotalVat);

		// COLUMN TOTAL
		$columnTotalInvoice = new \Engine\Form\Input\Matrix\Cell(null, 'totalInvoice');
		$containerTotalInvoice = \Engine\Form\Container\Vl::create();
		$containerTotalInvoice->setStyle('width', '120');
		$containerTotalInvoice->addElement(\Engine\Form\Input\Text::create(null, 'total', $this->input['invoiceData']['totalInvoice'])->setDisabled(true));

		$invoiceCurrency = \App\Form\Input\Select_Currency::create(null, 'invoiceData[currency]', $this->input['invoiceData']['currency']);

		$containerTotalInvoice->addElement($invoiceCurrency);
		$columnTotalInvoice->addContainer($containerTotalInvoice);
		$columnTotalInvoice->setDisabled(true);
		$rowFooter->addCell($columnTotalInvoice);

		// SET MATRIX URL
		$matrix->setUrl(\Engine\Mvc\Dispatcher::getInstance()->getAppUrl($this->controller->getModule(), "generateInvoiceRow", [
			'view' => 			$this->getViewAction(),
			'idInvoice' =>		$this->output['idInvoice'],
			'generator' => 		'getInvoiceRows_row',
			'clonesCount' =>	1,
			'orderData' =>		$this->input['orderData'],
		]));


		// SET MATRIX VALUE
		$matrix->setValue($this->input['invoiceRows']);
		// $matrix->setDisabledRows(array_keys($this->input['invoiceRows'])); // this disables all rows
		$matrix->setDisabledRows(array_keys(array_filter($this->input['invoiceRows'], function($row) {
			return (bool)$row['idBalance'];
		})));

		$supplierInvoicesVats = $this->input['supplierInvoicesVats'];
		$invoiceIsBalanced = $this->input['invoiceIsBalanced'];
		$matrix->setRenderRowCallback(function(\Engine\Form\Input\Matrix\Row $row, $rowIndex, $rowValues) use($supplierInvoicesVats, $invoiceIsBalanced) {
			/* @var $fldVatQuota \Engine\Form\Input\Select */
			$fldVatQuota = $row->findElementByName('vatQuota');
			if ($fldVatQuota) {
				$fldVatQuota->setStyle('extraCSSClass', '');

				if ($supplierInvoicesVats[$rowValues['service']]) {
					$vatPossibleValues = $supplierInvoicesVats[$rowValues['service']]['list'];
					$fldVatQuota->setPossibleValues(array_combine(array_keys($vatPossibleValues), array_keys($vatPossibleValues)));

					$fldVatQuota->setValue($rowValues['vatQuota']);
				}
				else {
					$fldVatQuota->setStyle('extraCSSClass', 'shouldBeInvisible');
				}
			}
		});

		$fieldset->addElement($matrix);

		// 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?)
		$storageKey = sprintf("%s.%s.%s", __CLASS__, CURRENT_ID_USER, $this->controller->getModule().'_'.$this->getViewAction().'_matrix');
		$matrix->setSaveHandler(function($matrix) use ($storageKey) {
			\Engine\Storage\General::getInstance('persistent')->set($storageKey, $matrix);
		});

		return $fieldset;
	}

	public function getInvoiceRows_row($index, $values, $totalNumberOfRows)
	{
		$matrix = \Engine\Storage\General::getInstance('persistent')->get(sprintf("%s.%s.%s", __CLASS__, CURRENT_ID_USER, $this->controller->getModule().'_'.$this->getViewAction().'_matrix'));

		if (!$matrix) {
			throw new \Exception("Matrix not found");
		}

		$matrixIndexStorageKey = sprintf("%s.%s.%s", __CLASS__, CURRENT_ID_USER, $this->controller->getModule().'_'.$this->getViewAction().'_index');
		$lastUsedIndex = \Engine\Storage\General::getInstance('session')->get($matrixIndexStorageKey);

		if ($lastUsedIndex) {
			$totalNumberOfRows = $lastUsedIndex;
		}

		if ($totalNumberOfRows > $index ) {
			$index = $totalNumberOfRows + 1;
		}

		// save index
		$matrixIndexStorageKey = sprintf("%s.%s.%s", __CLASS__, CURRENT_ID_USER, $this->controller->getModule().'_'.$this->getViewAction().'_index');
		\Engine\Storage\General::getInstance('session')->set($matrixIndexStorageKey, $index);

		return $matrix->getRow('Engine\Form\Input\Matrix\Row')->setIndex($index)->setValue($values)->setStyle('class_body', 'clone')->render();
	}

	private function populateContainer(\Engine\Form\Container\Vl $containerServiceData)
	{
		foreach ($this->input['supplierInvoiceFields'] as $fieldName) {
			switch ($fieldName) {
				case 'rowType':
					$fldRowType = new \Engine\Form\Input\Select($this->lang['serviceData']['rowType'], 'rowType');
					$rowTypesList = [];
					foreach (['price', 'advance', 'discount', 'tax', 'penalty'] as $rowType) {
						$rowTypesList[$rowType] = $this->globalLang['rowType'][$rowType];
					}
					$fldRowType->setPossibleValues($rowTypesList);
					$fldRowType->showDefaultOption(true);
					$containerServiceData->addElement($fldRowType);

				break;

				case 'passenger':
					$fldPassenger = new \App\Form\Input\Autocomplete_Customer($this->lang['serviceData']['passenger'], 'passenger');
					$fldPassenger->setStyle('buttons', false);
					$containerServiceData->addElement($fldPassenger);
				break;

				case 'checkIn':
					$fldCheckIn = new \Engine\Form\Input\Date($this->lang['serviceData']['checkIn'], 'checkIn');
					$containerServiceData->addElement($fldCheckIn);
				break;

				case 'checkOut':
				    $fldCheckOut = new \Engine\Form\Input\Date($this->lang['serviceData']['checkOut'], 'checkOut');
				    $containerServiceData->addElement($fldCheckOut);
				    break;

				case 'reservationCode':
					$fldReservationCode = new \Engine\Form\Input\Text($this->lang['serviceData']['reservationCode'], 'reservationCode');
					$containerServiceData->addElement($fldReservationCode);
				break;

				case 'reservationNumber':
					$fldReservationNumber = new \Engine\Form\Input\Text($this->lang['serviceData']['reservationNumber'], 'reservationNumber');
					$containerServiceData->addElement($fldReservationNumber);
				break;

				case 'reservationId':
					$fldReservationId = new \Engine\Form\Input\Text($this->lang['serviceData']['reservationId'], 'reservationId');
					$containerServiceData->addElement($fldReservationId);

				break;

				case 'idService':
					$fldIdService = new \Engine\Form\Input\Text($this->lang['serviceData']['idService'], 'idService');
					$fldIdService->setValidatorParam('type', 'digits');
					$containerServiceData->addElement($fldIdService);
				break;

				case 'extResId' :
					$fldExtResId = new \Engine\Form\Input\Text($this->lang['serviceData']['extResId'], 'extResId');
					$containerServiceData->addElement($fldExtResId);
				break;

				case 'extResDate':
					$fldExtResDate = new \Engine\Form\Input\Date($this->lang['serviceData']['extResDate'], 'extResDate');
					$containerServiceData->addElement($fldExtResDate);
				break;

				case 'confirmationNumber' :
					$fldConfirmationNumber = new \Engine\Form\Input\Text($this->lang['serviceData']['confirmationNumber'], 'confirmationNumber');
					$containerServiceData->addElement($fldConfirmationNumber);
				break;

				case 'contractNumber' :
					$fldContract = new \Engine\Form\Input\Text($this->lang['serviceData']['contract'], 'contractNumber');
					$containerServiceData->addElement($fldContract);
				break;

				case 'supplierService':
					$fldSupplierService = new \App\Form\Input\Autocomplete_SupplierProduct($this->lang['serviceData']['supplierService'], 'supplierService');
					$fldSupplierService->setStyle('buttons', false);
					$containerServiceData->addElement($fldSupplierService);
				break;

				case 'location':
					$fldLocation = new \App\Form\Input\Autocomplete_CountryCity($this->lang['serviceData']['location'], 'location');
					$fldLocation->setStyle('buttons', false);
					$containerServiceData->addElement($fldLocation);
				break;

				case 'ticketNo':
					$fldTicket = new \Engine\Form\Input\Text($this->lang['serviceData']['ticket'], 'ticketNo');
					$containerServiceData->addElement($fldTicket);
				break;

				default :
					throw new \Exception(sprintf("Don't know how to interpret '%s' in supplierInvoiceFields", $fieldName));
			}
		}
	}

	public function getPluginExtraFields()
	{
		$container = \Engine\Form\Container\Simple::create();

		// call plugins to hook up into this form and add their own fields /////////////////////////////////////////
		\Engine\Plugins\Manager::getInstance()->executeEvent('Modules/Invoices/SupplierInvoices/Management/PluginExtraFields', [
			'view' => 					$this,
			'container' => 				$container,
			'pluginsExtraInfo' => 		$this->input['pluginsExtraInfo'],
		]);

		return $container;
	}
}