<?php

namespace Modules\Invoices\InvoiceUpdate;

class View_Index extends \App\Mvc\View_Window_GeneralAbstract
{

	/**
	 * The smarty tempalte file (with path).
	 * @var String
	 */
	protected $renderingTemplate = '';


	/**
	 * {@inheritDoc}
	 * @see \App\Mvc\ViewAbstract::render_smarty()
	 */
	protected function render_smarty($templateName=null)
	{

		$this->setMoreInputVars();

		return parent::render_smarty($templateName);
	}

	/**
	 * Adds more details to the view.
	 */
	private function setMoreInputVars() :void
	{

		$formData = $this->output['formData'];

		$inputs = [];

		$invoiceEnt = \Entity\Invoice::select($formData['id']);

		$invoiceCfgs = \Entity\Invoice::loadCFG();

		// indicates if the invoice is issued and will enable only certain fields if invoice is already issued
		$isIssued = (bool)$invoiceEnt->issueTime;

		// INVOICE HEADER /////////////////////////////////////////////////////////////////////////

		// invoice series
		$inputs['series'] = new \App\Form\Input\Select_DocumentSeries(null, 'idSeries', $formData['idSeries']);
		// get main doc types associated to "invoice" pivot
		$issueDocsCfgObj = \App\Config\IssueDocuments::getInstance();
		$invoiceDocsList = array_filter(
			array_keys($issueDocsCfgObj->getInvoiceDocsList()),
			function ($docType) use ($issueDocsCfgObj) {
				return $issueDocsCfgObj->isMainDocOnPivot($docType);
			}
		) ;
		$inputs['series']->setDocTypesFilter($invoiceDocsList);
		$inputs['series']->setIdUser(CURRENT_ID_USER);
		$inputs['series']->showDefaultOption();
		if ($invoiceCfgs['idInvoiceSeries']['invisible'] or $isIssued) {
			$inputs['series']->setDisabled();
			$inputs['series']->setValue($invoiceEnt->idInvoiceSeries);
		}
		$inputs['series']->setWidth(130);

		$inputs['invoiceDate'] = new \Engine\Form\Input\Date(null, 'invoiceDate', $formData['invoiceDate']);
		$inputs['invoiceDate']->setWidth(130);
		if ($isIssued) {
			$inputs['invoiceDate']->setDisabled();
			$inputs['invoiceDate']->setValue($invoiceEnt->invoiceDate);
		} else {
			$inputs['invoiceDate']->onChange('refreshInvoiceDueDate()');
		}


		$inputs['dueDate'] = new \Engine\Form\Input\Date(null, 'dueDate', $formData['dueDate']);
		if ($invoiceCfgs['dueDate']['invisible'] or !\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('Invoices-canChangeInvoiceDueDate')) {
			$inputs['dueDate']->setDisabled();
			$inputs['dueDate']->setValue($invoiceEnt->dueDate);
		}
		$inputs['dueDate']->setWidth(130);

		$inputs['fulfillmentDate'] = new \Engine\Form\Input\Date(null, 'fulfillmentDate', $formData['fulfillmentDate']);
		if ($invoiceCfgs['fulfillmentDate']['invisible'] or !\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('Invoices-canChangeInvoiceFulfillmentDate') )  {
			$inputs['fulfillmentDate']->setDisabled();
			$inputs['fulfillmentDate']->setValue($invoiceEnt->fulfillmentDate);
		}
		$inputs['fulfillmentDate']->setWidth(130);

		$inputs['temporary'] = new \Engine\Form\Input\Checkbox(null, 'temporary', $formData['temporary']);
		$inputs['temporary']->setDetails('<label for="temporary"><span id="temporaryInvoiceSpan" class="temporaryInvoice '.($formData['temporary']?'temporaryChecked':'').'">'.$this->lang['index']['headerFields']['tempLabel'].'</span></label>');

		if ($isIssued) {
			$inputs['temporary']->setDisabled();
		} else {
			$inputs['temporary']->onChange("
				if ($(this).checked) {
					$('temporaryInvoiceSpan').addClassName('temporaryChecked');
	 			} else {
					$('temporaryInvoiceSpan').removeClassName('temporaryChecked');
				}
			");
		}


		$inputs['formOfPayment'] = new \App\Form\Input\Select_FormOfPayment(null, 'formOfPayment', $formData['formOfPayment']);
		$inputs['formOfPayment']->setMandatory( \App\Config\FormsOfPayment::getInstance()->getMandatory() );
		$inputs['formOfPayment']->showDefaultOption();
		if ($invoiceCfgs['formOfPayment']['invisible']) {
			$inputs['formOfPayment']->setDisabled();
		}
		$inputs['formOfPayment']->setWidth(250);

		$inputs['bankAccount'] = new \App\Form\Input\Select_AgencyBankAccount(null, 'idBankAccount', $formData['idBankAccount']);
		$inputs['bankAccount']->showDefaultOption();
		if ($invoiceCfgs['idBankAccount']['invisible']) {
			$inputs['bankAccount']->setDisabled();
			$inputs['bankAccount']->setValue($invoiceEnt->idBankAccount);
		}
		$inputs['bankAccount']->setWidth(250);

		$inputs['user'] = new \App\Form\Input\Autocomplete_User(null, 'user', $formData['user']);
		$inputs['user']->setWidth(250);
		if (!\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('Invoices-canChangeRespUser') or $isIssued) {
			$inputs['user']->setDisabled();
			$inputs['user']->setValue($invoiceEnt->idUser);
		}

		$inputs['comments'] = new \Engine\Form\Input\Textarea(null, 'comments', $formData['comments']);
		if ($invoiceCfgs['comments']['invisible']) {
			$inputs['comments']->setDisabled();
		}
		$inputs['comments']->setWidth(200);

		$inputs['remarks'] = new \App\Form\Input\Remarks(null, 'remarks', $formData['remarks']);
		$inputs['remarks']->setRemarksType('invoice');
		$inputs['remarks']->setAutoExpand(false);
		if ($invoiceCfgs['remarks']['invisible']) {
			$inputs['remarks']->setDisabled();
		}
		$inputs['remarks']->setWidth(200);
		$inputs['remarks']->setHeight(62);

		$inputs['invoiceCurrency'] = new \App\Form\Input\Select_Currency(null, 'invoiceCurrency', $formData['invoiceCurrency']);
		if ($invoiceEnt->invoiceCurrencyBlocked) {
			$inputs['invoiceCurrency']->setDisabled();
			$inputs['invoiceCurrency']->setValue($invoiceEnt->currency);
		}

		$inputs['roundTotal'] = new \Engine\Form\Input\Checkbox(null, 'roundTotal', $formData['roundTotal']);
		$inputs['roundTotal']->setCheckboxLabel($this->lang['index']['roundingLabel']);
		if (!\App\Config\InvoiceRounding::getInstance()->isEnabled() or $isIssued) {
			$inputs['roundTotal']->setDisabled();
			$inputs['roundTotal']->setValue($invoiceEnt->roundTotal);
		}

		// invoice rows schemes
		$descrSchemes = \App\Config\InvoiceRowsDescription::getInstance()->getSchemesName();
		if (count($descrSchemes)>0) {
			$inputs['rowDescriptionScheme'] = new \App\Form\Input\Select_InvoiceRowDescriptionScheme(null, 'rowDescriptionScheme', $formData['rowDescriptionScheme']);
			$inputs['rowDescriptionScheme']->showDefaultOption();
			$inputs['rowDescriptionScheme']->setStyle('width', 250);
			if ($isIssued) {
				$inputs['rowDescriptionScheme']->setDisabled();
			}
		}

		// add new corporate on order
		$inputs['corporateInsert'] = new \App\Form\Input\Autocomplete_Corporate(null, 'idCorporateInsert', '');
		$inputs['corporateInsert']->setStyle('buttons', false);
		$inputs['corporateInsert']->setWidth(200);
		$inputs['corporateInsert']->onPostSelect("$('addClientOnOrder').value=1;$('mainForm').submit();");

		// add new customer on order
		$inputs['customerInsert'] = new \App\Form\Input\Autocomplete_Customer(null, 'idCustomerInsert', '');
		$inputs['customerInsert']->setStyle('buttons', false);
		$inputs['customerInsert']->setWidth(200);
		$inputs['customerInsert']->onPostSelect("$('addClientOnOrder').value=1;$('mainForm').submit();");

		// row grouping options
		$inputs['rowsGroupingOption'] = new \Engine\Form\Input\Select(null, 'rowsGroupingOption', $formData['rowsGroupingOption']);
		$inputs['rowsGroupingOption']->showDefaultOption();
		$inputs['rowsGroupingOption']->setWidth(92);
		if (!$isIssued) {
			$inputs['rowsGroupingOption']->setTooltip($this->lang['index']['rowsGroupingOption']['tooltip']);
			$options = [
				$this->lang['index']['rowsGroupingOption']['cat1'] => [
					'serviceId'					=> $this->lang['index']['rowsGroupingOption']['gr1'],
					'serviceType'				=> $this->lang['index']['rowsGroupingOption']['gr2'],
					'vatPercentAndVatQuota' 	=> $this->lang['index']['rowsGroupingOption']['gr3'],
					'serviceIdAndRowType'		=> $this->lang['index']['rowsGroupingOption']['gr4'],
				],
				$this->lang['index']['rowsGroupingOption']['cat2'] => [
					'resetGrouping'				=> $this->lang['index']['rowsGroupingOption']['rs1'],
					'resetRowsGroupingAndOrder' => $this->lang['index']['rowsGroupingOption']['rs2'],
				]
			];
			$inputs['rowsGroupingOption']->setPossibleValues($options);
		} else {
			$inputs['rowsGroupingOption']->setDisabled();
		}

		// INVOICE ROWS FIELDS ////////////////////////////////////////////////////////////////////
		$inputs['invoiceRows'] = [];
		$totals = ['val'=>0, 'vat'=>0, 'ttl'=>0];
		$firstServiceCode = null;
		$famIds = []; // this is used to display only one mode field (total/rest) per service finalization
		$rowIndexes = [];
		$currentRowIndex = 0;
		foreach ($invoiceEnt->rowsList as $idRow=>$invoiceRowDet) {

			$currentRowIndex++;
			$rowIndexes[$invoiceRowDet['id']] = $currentRowIndex;

			$invoiceRowEnt = \Entity\InvoiceRow::select($idRow);

			$inputs['invoiceRows'][$idRow] = [];

			// add description field
			$descriptionField = new \Engine\Form\Input\Textarea(null, "description[{$idRow}]", $formData['description'][$idRow]);
			$inputs['invoiceRows'][$idRow]['description'] = $descriptionField;

			// currency type
			$currencyTypeFld = new \App\Form\Input\Select_CurrencyType(null, "currencyType[{$idRow}]", $formData['currencyType'][$idRow]);
			$currencyTypeFld->setWidth(120);
			if ($invoiceRowEnt->rowCurrencyDetailsBlocked) {
				$currencyTypeFld->setDisabled();
				$currencyTypeFld->setValue($invoiceRowEnt->currencyType);
			} else {
				$currencyTypeFld->onChange("
					if ($('connectCurrencyDetails').checked) {
						cloneConnectedCurrencyTypes(this.value);
					}
				");
			}
			$inputs['invoiceRows'][$idRow]['currencyType'] = $currencyTypeFld;

			// currency date
			$currencyDateFld = new \Engine\Form\Input\Date(null, "currencyDate[{$idRow}]", $formData['currencyDate'][$idRow]);
			$currencyDateFld->setWidth(120);
			if ($invoiceRowEnt->rowCurrencyDetailsBlocked) {
				$currencyDateFld->setDisabled();
				$currencyDateFld->setValue($invoiceRowEnt->currencyDate);
			} else {
				$currencyDateFld->onChange("
					if ($('connectCurrencyDetails').checked) {
						cloneConnectedCurrencyDates(\$F('currencyDate_{$idRow}_'), \$F('currencyDate_{$idRow}__title'));
					}
				");
			}
			$inputs['invoiceRows'][$idRow]['currencyDate'] = $currencyDateFld;

			// finalize advance mode
			$idFinalization = $invoiceRowDet['extraInfo']['serviceAdvanceFinalizationId'];
			if ($invoiceRowDet['finalizeAdvanceMode'] and !$famIds[$idFinalization]) {
				$famFld = new \Engine\Form\Input\Select(null, "finalizeAdvanceMode[{$idRow}]", $formData['finalizeAdvanceMode'][$idRow]);
				$famFld->setPossibleValues(['total'=>$this->lang['index']['finalizeAdvMode']['total'], 'rest'=>$this->lang['index']['finalizeAdvMode']['rest']]);
				if ($invoiceRowEnt->rowCurrencyDetailsBlocked) {
					$famFld->setDisabled();
				}
				$inputs['invoiceRows'][$idRow]['finalizeAdvanceMode'] = $famFld;
				$famIds[ $idFinalization ] = true;
			}

			// measure unit
			$muFld = new \Engine\Form\Input\Text(null, "measureUnit[{$idRow}]", $formData['measureUnit'][$idRow]);
			$muFld->setWidth(40);
			$inputs['invoiceRows'][$idRow]['measureUnit'] = $muFld;

			// calculate totals
			$totals['val'] += $invoiceRowDet['pricePrintValue'];
			$totals['vat'] += $invoiceRowDet['vatPrintValue'];
			$totals['ttl'] += $invoiceRowDet['pricePrintValue'] + $invoiceRowDet['vatPrintValue'];

			// determine the first service code
			if (!$firstServiceCode) {
				$firstServiceCode = $invoiceRowDet['serviceCode'];
			}

			// row index
			$rowIndexFld = new \Engine\Form\Input\Text(null, "rowIndex[{$idRow}]", $formData['rowIndex'][$idRow]);
			$rowIndexFld->setStyle('width', '40');
			if ($isIssued) {
				$rowIndexFld->setDisabled();
				$rowIndexFld->setValue($invoiceRowDet['rowIndex']);
			} else {
				$rowIndexFld->addEvent('onFocus', 'element.select();initialIndex=this.value;');
			}
			$inputs['invoiceRows'][$idRow]['rowIndex'] = $rowIndexFld;

			// hidden on row index
			$hiddenOnRowIndexFld = new \Engine\Form\Input\Text(null, "hiddenOnRowIndex[{$idRow}]", $formData['hiddenOnRowIndex'][$idRow]);
			$hiddenOnRowIndexFld->setStyle('width', '40');
			if ($isIssued) {
				$hiddenOnRowIndexFld->setDisabled();
				if ($invoiceRowDet['hiddenOnRowId']) {
					$hiddenOnRowIndexFld->setValue($rowIndexes[$invoiceRowDet['hiddenOnRowId']]);
				}
			} else {
				$hiddenOnRowIndexFld->addEvent('onFocus', 'element.select()');
			}
			$inputs['invoiceRows'][$idRow]['hiddenOnRowIndex'] = $hiddenOnRowIndexFld;

		}

		$this->setOutputVar('totals', $totals);
		$this->setOutputVar('inputs', $inputs);
		$this->setOutputVar('firstServiceCode', $firstServiceCode);
		$this->setOutputVar('isIssued', $isIssued);
		$this->setOutputVar('invoiceCurrency', $invoiceEnt->currency);


	}

}

