<?php

namespace Modules\Partners\Corporates\Profile;

class View_Utils_FormAdmin extends \App\Mvc\View_Utils_FormAbstract
{

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\View_Utils_FormAbstract::getForm()
	 */
	public function getForm()
	{
		$_LANG = \App\Loader_Lang::getInstance()->getGlobal();
		$CFG = \Engine\Loader_Cfg::getInstance()->getGlobal();

		// load the configurations for this form
		$form=\Engine\Form\General::create();

		$form->setStyle('width', 300)->setStyle('labelWidth', 30);

		// GROUPS /////////////////////////////////////////////////////////////////////////////////

		// Groups fieldset
		$groupsFieldset = \Engine\Form\Container\Fieldset::create($this->lang['index']['fieldsets']['groups']);
		$form->addContainer($groupsFieldset);

		$groups = \App\Config\CorporateGroups::getInstance()->getAll();
		if ($groups) {
			foreach ($groups as $idGroup=>$groupDetails) {
				if ($groupDetails['groupElements']) {
					$groupElement = new \Engine\Form\Input\Select($groupDetails['groupName'], "idGroupElements[{$idGroup}]", $this->values['idGroupElements']);
					$groupElement->setPossibleValues($groupDetails['groupElements']);
					$groupElement->showDefaultOption(true);
					$groupsFieldset->addElement($groupElement);
				}
			}
		}

		// INVOICE PREFS //////////////////////////////////////////////////////////////////////////
		$fieldset = \Engine\Form\Container\Fieldset::create($this->lang['index']['invoicePreferences']['basicSection']['title']);
		$form->addContainer($fieldset);

		// the invoiceDescriptionsSchemas selector
		$t = \App\Config\InvoiceRowsDescription::getInstance()->getSchemesName();
		$defaultT= \App\Config\InvoiceRowsDescription::getInstance()->getDefaultItem();
		$d = '_none_';
		foreach($t as $v){
			$values[$v] = $v;
			if($v == $defaultT) $d = $v;
		}

		$input_invoiceDescriptionsSchemas = new \Engine\Form\Input\Select(
			$this->lang['index']['invoicePreferences']['invoiceDescriptionsSchemas']['label'],
			"invoicePreferences[invoiceDescriptionsSchemas]",
			$this->values['invoicePreferences']['invoiceDescriptionsSchemas']
		);
		$input_invoiceDescriptionsSchemas->setDetails(
				$this->lang['index']['invoicePreferences']['invoiceDescriptionsSchemas']['details_1']."<br/>".
				sprintf($this->lang['index']['invoicePreferences']['invoiceDescriptionsSchemas']['details_2'], $d));
		$input_invoiceDescriptionsSchemas->setPossibleValues($values);
		$input_invoiceDescriptionsSchemas->showDefaultOption(true);
		$fieldset->addElement($input_invoiceDescriptionsSchemas);


		// the invoice currency selector
		$input_invoiceCurrency = new \App\Form\Input\Select_Currency($this->lang['index']['invoicePreferences']['invoiceCurreny']['label'], 'invoicePreferences[invoiceCurrency]', $this->values['invoicePreferences']['invoiceCurrency']);
		$input_invoiceCurrency->showDefaultOption(true);
		$input_invoiceCurrency->setDetails($this->lang['index']['invoicePreferences']['invoiceCurreny']['details']);
		$fieldset->addElement($input_invoiceCurrency);

		// invoice currency exchange type selector
		$input_invoiceCurrencyType = new \App\Form\Input\Select_CurrencyType($this->lang['index']['invoicePreferences']['invoiceCurrencyType']['label'], 'invoicePreferences[invoiceCurrencyType]', $this->values['invoicePreferences']['invoiceCurrencyType']);
		$input_invoiceCurrencyType->showDefaultOption(true);
		$input_invoiceCurrencyType->setDetails($this->lang['index']['invoicePreferences']['invoiceCurrencyType']['details']);
		$fieldset->addElement($input_invoiceCurrencyType);

		// the bankAccount selector
		$values = [];
		// get list of agency bank account
		$agencyBankAccountObj = new \App\EntityList\AgencyBankAccounts();
		$agencyBankAccountObj->setColumns(['deleted', 'defaultAccount', 'idBank', 'idBankOffice', 'account', 'currency']);
		$agencyBankAccountArray = $agencyBankAccountObj->getExecution();

		foreach ($agencyBankAccountArray as $agencyBankAccountInfo) {
			if ($agencyBankAccountInfo['currency']) {
				$values[$agencyBankAccountInfo['id']] = sprintf("%s - %s (%s)", $agencyBankAccountInfo['account'], $agencyBankAccountInfo['currency'], \Entity\Bank::select($agencyBankAccountInfo['idBank'])->name);
			}
			else {
				$values[$agencyBankAccountInfo['id']] = sprintf("%s (%s)", $agencyBankAccountInfo['account'], \Entity\Bank::select($agencyBankAccountInfo['idBank'])->name);
			}
		}

		$input_agencyBankAccount = new \Engine\Form\Input\Select($this->lang['index']['invoicePreferences']['agencyBankAccount']['label'], "invoicePreferences[agencyBankAccount]", $this->values['invoicePreferences']['agencyBankAccount']);
		$input_agencyBankAccount->setDetails($this->lang['index']['invoicePreferences']['agencyBankAccount']['details']);
		$input_agencyBankAccount->setPossibleValues($values);
		$input_agencyBankAccount->showDefaultOption(true);
		$fieldset->addElement($input_agencyBankAccount);

		// round invoice option
		$fld_roundInvoice = new \Engine\Form\Input\Radio($this->lang['index']['invoicePreferences']['roundInvoice']['label'], 'invoicePreferences[roundInvoice]', $this->values['invoicePreferences']['roundInvoice']);
		$fld_roundInvoice->setDetails($this->lang['index']['invoicePreferences']['roundInvoice']['details']);
		$fld_roundInvoice->setPossibleValues(["2" => $this->lang['index']['invoicePreferences']['appDefault'], "0" => $_LANG['no'], "1" => $_LANG['yes'], ]);
		$fieldset->addElement($fld_roundInvoice);

		// invoice series
		$fld_invoiceSeries = new \App\Form\Input\Select_DocumentSeries($this->lang['index']['invoicePreferences']['invoiceSeries']['label'], 'invoicePreferences[invoiceSeries]', $this->values['invoicePreferences']['invoiceSeries']);
		$fld_invoiceSeries->setDetails($this->lang['index']['invoicePreferences']['invoiceSeries']['details']);

		// 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);
			}
		) ;
		$fld_invoiceSeries->setDocTypesFilter($invoiceDocsList);
		$fld_invoiceSeries->showDefaultOption();
		$fieldset->addElement($fld_invoiceSeries);


		// CREDIT LIMIT SETUP /////////////////////////////////////////////////////////////////////
		$fieldset = \Engine\Form\Container\Fieldset::create($this->lang['index']['creditLimits']['title']);
		$form->addContainer($fieldset);

		// credit limit block
		$input_blockLimit = new \Engine\Form\Input\Text($this->lang['index']['blockLimit']['label'], 'creditLimitBlock', $this->values['creditLimitBlock']);
		$customHtml = ' '.\App\Config\Currencies::getInstance()->getDefaultCurrency();
		if ($CFG['corporateCreditLimit']['blockInvoicingActive']) {
		    $customHtml .= sprintf(' - <i>%s</i>', $this->lang['index']['blockLimit']['custDescr1']);
		} else {
		    $customHtml .= sprintf(' - <i>%s</i>', $this->lang['index']['blockLimit']['custDescr2']);
		}
		$input_blockLimit->setCustomHTML($customHtml);
		$input_blockLimit->setStyle('width', 100);
		$input_blockLimit->addEvent('onChange', "var b=this.value; var a=$('creditLimitAlert').value; var p=(b>0?(a/b*100):0).toFixed(2); $('creditLimitAlertPercent').value=p;");
		$fieldset->addElement($input_blockLimit);

		// credit limit alert
		$input_alertLimit = new \Engine\Form\Input\Text($this->lang['index']['alertLimit']['label'], 'creditLimitAlert', $this->values['creditLimitAlert']);
		$input_alertLimit->setCustomHTML(sprintf(" %s", \App\Config\Currencies::getInstance()->getDefaultCurrency()));
		$input_alertLimit->setStyle('width', 100);
		$input_alertLimit->addEvent('onChange', "var b=$('creditLimitBlock').value; var a=this.value; var p=(b>0?(a/b*100):0).toFixed(2); $('creditLimitAlertPercent').value=p;");
		$fieldset->addElement($input_alertLimit);

		// alert limit percent
		$input_alertLimitPc = new \Engine\Form\Input\Text($this->lang['index']['alertLimitPercent']['label'], 'creditLimitAlertPercent', $this->values['creditLimitAlertPercent']);
		$input_alertLimitPc->setCustomHTML('%');
		$input_alertLimitPc->setStyle('width', 100);
		$input_alertLimitPc->addEvent('onChange', "var b=$('creditLimitBlock').value; var p=this.value; var a=(b*p/100).toFixed(0); $('creditLimitAlert').value=a;");
		$input_alertLimitPc->setTooltip($this->lang['index']['alertLimitPercent']['tooltip']);
		$fieldset->addElement($input_alertLimitPc);

		$input_sendEmails = new \Engine\Form\Input\Checkbox($this->lang['index']['sendEmails']['label'], 'sendEmails', $this->values['sendEmails']);
		$input_sendEmails->setCustomHTML($this->lang['index']['sendEmails']['description']);
		$fieldset->addElement($input_sendEmails);

		// email template for alert
		$input_emailAlertTemplate = new \Engine\Form\Input\Select($this->lang['index']['emailAlertTemplate']['label'], "emailAlertTemplate", $this->values['emailAlertTemplate']);
		$input_emailAlertTemplate->setPossibleValues($this->values['emailTemplates']);
		$input_emailAlertTemplate->showDefaultOption(true);
		$input_emailAlertTemplate->setDetails($this->lang['index']['emailAlertTemplate']['details']);
		$fieldset->addElement($input_emailAlertTemplate);

		// email template for block
		$input_emailBlockTemplate = new \Engine\Form\Input\Select($this->lang['index']['emailBlockTemplate']['label'], "emailBlockTemplate", $this->values['emailBlockTemplate']);
		$input_emailBlockTemplate->setPossibleValues($this->values['emailTemplates']);
		$input_emailBlockTemplate->showDefaultOption(true);
		$input_emailBlockTemplate->setDetails($this->lang['index']['emailBlockTemplate']['details']);
		$fieldset->addElement($input_emailBlockTemplate);

		// sender email for alert
		$input_emailSendingUser = new \App\Form\Input\Autocomplete_User($this->lang['index']['idSendingUser']['label'], 'idSendingUser', $this->values['idSendingUser']);
		$input_emailSendingUser->setDetails($this->lang['index']['idSendingUser']['details']);
		$fieldset->addElement($input_emailSendingUser);

		// recipients for email
		$input_emailRecipients = new \Engine\Form\Input\Cloned_Autocomplete($this->lang['index']['recipients']['label'], 'idRecipients', $this->values['idRecipients']);
		$url = \Engine\Mvc\Dispatcher::getInstance()->getAppUrl('Modules/RemoteData/AutocompleteFieldData', '', ['class'=>'ContactPersonCorporate']);
		$input_emailRecipients->setUrl($url);
		$input_emailRecipients->setFilters('idCompany', $this->values['id']);
		$input_emailRecipients->setMandatory();
		$input_emailRecipients->setDetails($this->lang['index']['idRecipients']['details']);
		$fieldset->addElement($input_emailRecipients);

		// bcc for alert
		$input_emailBccUsers = new \App\Form\Input\Cloned_AutocompleteUser($this->lang['index']['idUsersBcc']['label'], 'idUsersBcc', $this->values['idUsersBcc']);
		$input_emailBccUsers->setDetails($this->lang['index']['idUsersBcc']['details']);
		$fieldset->addElement($input_emailBccUsers);

		$input_sendEmails->setControlledElements([true => [$input_emailAlertTemplate, $input_emailBlockTemplate, $input_emailSendingUser, $input_emailRecipients, $input_emailBccUsers]],'hide');


		// AUTO-COMPENSATION //////////////////////////////////////////////////////////////////////
		// the fieldset
		$autoCompFieldset = \Engine\Form\Container\Fieldset::create($this->lang['index']['fieldsets']['autoComp'] );
		$form->addContainer($autoCompFieldset);

		// compensate type
		$input_autoCompensateType = new \Engine\Form\Input\Select($this->lang['index']['autoCompensateType']['label'], "autoCompensateType", $this->values['autoCompensateType']);
		$input_autoCompensateType->setPossibleValues( [
			'onlyExactCreditNotes' => $this->lang['index']['autoCompensateType']['onlyExactCreditNotes'],
			'bulk' => $this->lang['index']['autoCompensateType']['bulk'],
		] );
		$input_autoCompensateType->showDefaultOption(true);
		$input_autoCompensateType->setDetails($this->lang['index']['autoCompensateType']['details']);
		$input_autoCompensateType->setTooltip($this->lang['index']['autoCompensateType']['tooltip']);
		$autoCompFieldset->addElement($input_autoCompensateType);


		// DEFAULT TEMPLATES //////////////////////////////////////////////////////////////////////
		$docs = \App\Config\IssueDocuments::getInstance()->getInvoiceDocsList();

		if ($docs) {
			$fieldset = \Engine\Form\Container\Fieldset::create($this->lang['index']['invoicePreferences']['defaultDocumentTemplate']['title']);
			$form->addContainer($fieldset);

			// extract documents templates
			$docTemplateObj = new \App\EntityList\DocumentTemplates();
			$docTemplateObj->setColumns(['tpls.name', 'tpls.docType', 'tpls.active']);
			$docTemplateObj->setOrderBy('tpls.docType', 'ASC');
			$docTemplateObj->setOrderBy('tpls.name', 'ASC');
			$docTemplateArray = $docTemplateObj->exportRecords();

			$tmplts = [];

			if ($docTemplateArray) {
				foreach ($docTemplateArray as $docTemplateInfos) {
					$tmplts[$docTemplateInfos['id']] = $docTemplateInfos;
				}
			}

			foreach ($docs as $docType=>$docName) {
				$values = [];

				foreach ($tmplts as $id => $t) {
					if ($t['docType'] == $docType) {
						$values[$id] = ($t['active'])? $t['name'] : $t['name']." ".$this->lang['index']['invoicePreferences']['documentTemplate']['inactive'];
					}
				}


				$input_defaultDocumentTemplate = new \Engine\Form\Input\Select($docName, "invoicePreferences[defaultDocumentTemplate][{$docType}]", $this->values['invoicePreferences']['defaultDocumentTemplate'][$docType]);
				$input_defaultDocumentTemplate->setPossibleValues($values);
				$input_defaultDocumentTemplate->showDefaultOption();
				$fieldset->addElement($input_defaultDocumentTemplate);
			}
		}

		// DEFAULT HIDDEN ROWS ON INVOICE /////////////////////////////////////////////////////////
		$fieldset = \Engine\Form\Container\Fieldset::create($this->lang['index']['fieldsets']['hiddenRows']);
		$fieldset->setCollapsible(true);
		$fieldset->setCollapsed(true);
		$form->addContainer($fieldset);

		$fld = new \Engine\Form\Input\Label();
		$fld->setStyle('noLabel', true);
		$fld->setDetails($this->lang['index']['hiddenRows']['description']);
		$fieldset->addElement($fld);

		foreach (\App\Config\Services_Basic::getInstance()->getListLinear() as $serviceCode=>$serviceDetails) {

			$fld = new \Engine\Form\Input\ElementWithElements( $serviceDetails['name'] . ($serviceDetails['group'] ? ' (' . $serviceDetails['group']['name'] . ')' : '') );

			$fld->setStyle('width', '500');

			$serviceHideRowsDiscFld = new \Engine\Form\Input\Select($serviceDetails['name'] . ($serviceDetails['group'] ? ' (' . $serviceDetails['group']['name'] . ')' : ''), "hideInvoiceRowsComponents[{$serviceCode}][discount]", $this->values['hideInvoiceRowsComponents'][$serviceCode]['discount']);
			$serviceHideRowsDiscFld->showDefaultOption(true);
			$serviceHideRowsDiscFld->setPossibleValues(['hidden'=>$this->lang['index']['options']['hidden'], 'visible'=>$this->lang['index']['options']['visible']]);
			$serviceHideRowsDiscFld->setCustomHTML('&nbsp; &nbsp; '.$this->lang['index']['labels']['discount'].':', 'pre');

			$serviceHideRowsSfFld = new \Engine\Form\Input\Select($serviceDetails['name'] . ($serviceDetails['group'] ? ' (' . $serviceDetails['group']['name'] . ')' : ''), "hideInvoiceRowsComponents[{$serviceCode}][serviceFee]", $this->values['hideInvoiceRowsComponents'][$serviceCode]['serviceFee']);
			$serviceHideRowsSfFld->showDefaultOption(true);
			$serviceHideRowsSfFld->setPossibleValues(['hidden'=>$this->lang['index']['options']['hidden'], 'visible'=>$this->lang['index']['options']['visible']]);
			$serviceHideRowsSfFld->setCustomHTML('&nbsp; &nbsp; '.$this->lang['index']['labels']['serviceFee'].':', 'pre');

			$serviceHideRowsTaxFld = new \Engine\Form\Input\Select($serviceDetails['name'] . ($serviceDetails['group'] ? ' (' . $serviceDetails['group']['name'] . ')' : ''), "hideInvoiceRowsComponents[{$serviceCode}][tax]", $this->values['hideInvoiceRowsComponents'][$serviceCode]['tax']);;
			$serviceHideRowsTaxFld->showDefaultOption(true);
			$serviceHideRowsTaxFld->setPossibleValues(['hidden'=>$this->lang['index']['options']['hidden'], 'visible'=>$this->lang['index']['options']['visible']]);
			$serviceHideRowsTaxFld->setCustomHTML($this->lang['index']['labels']['tax'].':', 'pre');

			$fld->addElement($serviceHideRowsDiscFld, 'main');
			$fld->addElement($serviceHideRowsSfFld, 'main');
			$fld->addElement($serviceHideRowsTaxFld, 'main');
			$fld->setStyle('renderMode', 'inline');

			$fieldset->addElement($fld);
		}


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

		return $form;
	}

}