<?php

namespace Modules\Admin\QcRules;

class View_Utils_FormAdmin extends \App\Mvc\View_Utils_FormAbstract
{

	/**
	 * Creates the form for qc rule insert/update.
	 * @see \App\Mvc\View_Utils_FormAbstract::getForm()
	 */
	public function getForm()
	{

		// INITIALIZATIONS ------------------------------------------------------------------------
		// entity cfg
		$cfg=\Entity\QcRule::loadCFG();
		// global cfgs
		$CFG = \Engine\Loader_Cfg::getInstance()->getGlobal();
		// qc rules global configs
		$qcRulesCfg = $CFG['qcRules']['entities'];
		$entity = $this->values['entity'];

		// FORM FIELDS FOR ADDING AND EDITING SUPPLIERS ///////////////////////////////////////////
		$form = \Engine\Form\General::create();
		$form->setStyle('width', 300)->setStyle('labelWidth', 25);

		// GENERAL --------------------------------------------------------------------------------
		// fieldset
		$fieldset = \Engine\Form\Container\Fieldset::create($this->lang['form']['fieldsetGeneral']);
		$form->addContainer($fieldset);

		$form->addElement(new \Engine\Form\Input\Hidden('', 'entityChanged', 0));

		// rule entity
		$fld = new \Engine\Form\Input\Select($this->lang['formFields']['entity'], 'entity', $entity);
		$fld->setMandatory(true);
		$fld->setTooltip($this->lang['formFields']['entityDescr']);
		if ($this->controller->getAction()=='update') {
			$fld->setDisabled(true);
			// this is done only on update because the entity value is overwritten on insert (the entity type select won't work correctly on submit for insert)
			$form->addElement(new \Engine\Form\Input\Hidden('', 'entity', $this->values['entity']));
		}
		$possibleVals = [];
		foreach($qcRulesCfg as $ent=>$entDet) {
			if ($qcRulesCfg[$ent]) {
				$possibleVals[$ent] = $this->globalLang['QcRules']['entities'][$ent];
			}
		}
		$fld->setPossibleValues($possibleVals);
		$fld->onChange("$('{$this->submitButtonName}').value=0;$('entityChanged').value='1';this.up('form').fire('form:doSubmit')");
		$fieldset->addElement($fld);

		// rule is active
		$fld = new \Engine\Form\Input\Checkbox($this->lang['formFields']['active'], 'active', $this->values['active']);
		$fieldset->addElement($fld);

		// rule name
		$fld = new \Engine\Form\Input\Text($this->lang['formFields']['name'], 'name', $this->values['name']);
		$fld->setMandatory($cfg['name']['mandatory']);
		$fieldset->addElement($fld);

		// FILTERS --------------------------------------------------------------------------------
		if ($entity) {
			// fieldset
			$filtersFieldset = \Engine\Form\Container\Fieldset::create($this->lang['form']['fieldsetFilters']);
			$form->addContainer($filtersFieldset);

			// add some info
			$fldsetInfo=new \Engine\Form\Input\Label();
			$fldsetInfo->setDetails($this->lang['form']['fieldsetFiltersDescr']);
			$fldsetInfo->setStyle("noLabel", true);
			$filtersFieldset->addElement($fldsetInfo);

			$this->attachFieldsToForm($filtersFieldset, 'filters');

		}

		// RESTRICTIONS ---------------------------------------------------------------------------
		if ($entity) {
			// fieldset
			$restrFieldset = \Engine\Form\Container\Fieldset::create($this->lang['form']['fieldsetRestr']);
			$form->addContainer($restrFieldset);

			// add some info
			$fldsetInfo=new \Engine\Form\Input\Label();
			$fldsetInfo->setDetails($this->lang['form']['fieldsetRestrDescr']);
			$fldsetInfo->setStyle("noLabel", true);
			$restrFieldset->addElement($fldsetInfo);

			$this->attachFieldsToForm($restrFieldset, 'restrictions');

		}

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

		return $form;

	}


	/**
	 * Adds the current fields to the form.
	 * @param \Engine\Form\Container\GeneralAbstract $mainFieldset - the form container that will hold all filters fields
	 */
	private function attachFieldsToForm(\Engine\Form\Container\GeneralAbstract $mainFieldset, $formRqVarName)
	{

		// INITIALIZATIONS ------------------------------------------------------------------------
		// global cfgs
		$CFG = \Engine\Loader_Cfg::getInstance()->getGlobal();
		// qc rules global configs
		$qcRulesCfg = $CFG['qcRules']['entities'];
		$entity = $this->values['entity'];
		$entityCfg = $qcRulesCfg[$entity];

		if ($formRqVarName=='filters') {
			$fieldsetLabel = $this->lang['form']['filterLabel'];
		} else {
			$fieldsetLabel = $this->lang['form']['restrLabel'];
		}

		// GO THROUGH EACH FILTER AND ADD IT AS A NEW FIELDSET ------------------------------------
		$counter = 0;
		foreach($entityCfg['filters'] as $field=>$filterDetails) {

			$filterName = $this->globalLang['QcRules']['filters'][$entity][$field]?$this->globalLang['QcRules']['filters'][$entity][$field]:$field;
			$filterFieldset = \Engine\Form\Container\Fieldset::create(++$counter.". {$fieldsetLabel}: {$filterName}");
			$mainFieldset->addContainer($filterFieldset);

			// ADD OPERATION FIELD ----------------------------------------------------------------
			$fldOp = new \Engine\Form\Input\Select($this->lang['formFields']['operation'], "{$formRqVarName}[{$field}][operation]", $this->values[$formRqVarName][$field]['operation']);
			$posVals = [''=>$this->lang['formFields']['operationNoVal']];
			foreach ($filterDetails['operations'] as $op) {
				$posVals[$op] = $this->globalLang['QcRules']['operations'][$op];
			}
			$fldOp->setPossibleValues($posVals);
			$filterFieldset->addElement($fldOp);

			// ADD THE VALUE FIELD ----------------------------------------------------------------
			// the service filter for the serviceRemarks field
			if ($filterDetails['fieldType']=='serviceRemark') {
				$fldServiceCode = new \App\Form\Input\Select_Service($this->lang['formFields']['serviceType'], "{$formRqVarName}[{$field}][serviceCode]", $this->values[$formRqVarName][$field]['serviceCode']);
				$fldServiceCode->showDefaultOption();
				$fldServiceCode->setMultipleSelector();
				$fldServiceCode->setTooltip($this->lang['formFields']['serviceRemarkServTypeDescr']);
				$filterFieldset->addElement($fldServiceCode);
			}

			// the remark var name (usually for remarks related fields)
			if ($filterDetails['fieldType']=='remark' or $filterDetails['fieldType']=='serviceRemark') {
				$fldRmVar = new \Engine\Form\Input\Text($this->lang['formFields']['rmVar'], "{$formRqVarName}[{$field}][remarkVar]", $this->values[$formRqVarName][$field]['remarkVar']);
				$fldRmVar->setTooltip($this->lang['formFields']['rmVarDescr']);
				$fldRmVar->setMandatory();
				$filterFieldset->addElement($fldRmVar);
			}

			// add specific validators (type+length) for remarks fields
			if ($filterDetails['fieldType']=='remark' or $filterDetails['fieldType']=='serviceRemark') {
				$fldValidatorType = new \Engine\Form\Input\Select($this->lang['formFields']['validatorType'], "{$formRqVarName}[{$field}][validatorType]", $this->values[$formRqVarName][$field]['validatorType']);
				$fldValidatorType->setPossibleValues( [
					''			=> $this->lang['formFields']['validatorType_text'],
					'alnum'		=> $this->lang['formFields']['validatorType_alnum'],
					'alpha'	=> $this->lang['formFields']['validatorType_alpha'],
					'float'		=> $this->lang['formFields']['validatorType_float'],
					'int'		=> $this->lang['formFields']['validatorType_int'],
					'digits'	=> $this->lang['formFields']['validatorType_digits'],

				] );
				$filterFieldset->addElement($fldValidatorType);

				$fldValidatorLengthMin = new \Engine\Form\Input\Text($this->lang['formFields']['validatorLengthMin'], "{$formRqVarName}[{$field}][validatorLengthMin]", $this->values[$formRqVarName][$field]['validatorLengthMin']);
				$filterFieldset->addElement($fldValidatorLengthMin);
				$fldValidatorLengthMax = new \Engine\Form\Input\Text($this->lang['formFields']['validatorLengthMax'], "{$formRqVarName}[{$field}][validatorLengthMax]", $this->values[$formRqVarName][$field]['validatorLengthMax']);
				$filterFieldset->addElement($fldValidatorLengthMax);

			}

			// determine the value type
			if ($filterDetails['fieldType']) {

				$fldVal = null;

				switch ($filterDetails['fieldType']) {
					case 'corporate':
						$fldVal = new \App\Form\Input\Autocomplete_Corporate();
					break;
					case 'corporates':
						$fldVal = new \App\Form\Input\Cloned_AutocompleteCorporate();
					break;
					case 'corporateSegment':
						$fldVal = new \App\Form\Input\Select_CorporateSegment();
						$fldVal->showDefaultOption();
					break;
					case 'corporateTrust':
						$fldVal = new \App\Form\Input\Autocomplete_CorporateTrust();
					break;
					case 'customer':
						$fldVal = new \App\Form\Input\Autocomplete_Customer();
					break;
					case 'customerSegment':
						$fldVal = new \App\Form\Input\Select_CustomerSegment();
					break;
					case 'currency':
						$fldVal = new \App\Form\Input\Select_Currency();
					break;
					case 'service':
						$fldVal = new \App\Form\Input\Select_Service();
						$fldVal->setMultipleSelector(true);
					break;
					case 'orderExtSystem':
						$fldVal = new \App\Form\Input\Select_OrdersExternalSystem();
						$fldVal->showDefaultOption();
					break;
					case 'user':
						$fldVal = new \App\Form\Input\Autocomplete_User();
					break;
					case 'office':
						$fldVal = new \App\Form\Input\Autocomplete_Office();
					break;
					case 'department':
						$fldVal = new \App\Form\Input\Autocomplete_Department();
					break;
					case 'country':
						$fldVal = new \App\Form\Input\Autocomplete_Country();
					break;
					case 'remark': case 'serviceRemark':
						$fldVal = new \Engine\Form\Input\Cloned_Text();
					break;
					case 'countryCriterion':
						$fldVal = new \App\Form\Input\Select_CountryCriterion();
						$fldVal->showDefaultOption();
					break;
					case 'currencyType':
						$fldVal = new \App\Form\Input\Select_CurrencyType();
						$fldVal->showDefaultOption();
					break;
					case 'formOfPayment':
						$fldVal = new \App\Form\Input\Select_FormOfPayment();
					break;
					case 'offerCalculation':
						$fldVal = new \App\Form\Input\Select_OfferCalculation();
						$fldVal->showDefaultOption();
					break;
					case 'offerFormOfPayment':
						$fldVal = new \App\Form\Input\Select_OfferFormOfPayment();
						$fldVal->showDefaultOption();
					break;
					case 'offerFormOfCashing':
						$fldVal = new \App\Form\Input\Select_OfferFormOfCashing();
						$fldVal->showDefaultOption();
					break;
					case 'docSeries':
						$fldVal = new \App\Form\Input\Select_DocumentSeries();
					break;
					case 'docType':
						$fldVal = new \App\Form\Input\Select_DocumentType();
						$fldVal->setPivot($filterDetails['pivot']);
					break;
					case 'agencyBankAccount':
						$fldVal = new \App\Form\Input\Select_AgencyBankAccount();
					break;
					case 'text':
						$fldVal = new \Engine\Form\Input\Text();
					break;
					case 'suppliers':
						$fldVal = new \App\Form\Input\Cloned_AutocompleteSupplier();
					break;
					case 'orderServicesType':
						$fldVal = new \App\Form\Input\Select_OrderServicesType();
					break;
					case 'orderType':
						$fldVal = new \App\Form\Input\Select_OrderType();
					break;
 					case 'orderCode':
 						$fldVal = null;
 					break;
					case 'miceProjects':
						$fldVal = new \App\Form\Input\Cloned_AutocompleteMiceProject();
					break;
 					default:
						throw new \Exception("The QC filter type `{$filterDetails['fieldType']}` is not valid.");
				}

				// fldVal is used for all cases except order code, where we do not need to select a value when selecting an option
				if ($fldVal) {
					$fldVal->setLabel($this->lang['formFields']['value']);
					$fldVal->setName("{$formRqVarName}[{$field}][value]");
					$fldVal->setValue($this->values[$formRqVarName][$field]['value']);
					$fldVal->setMandatory();
					$filterFieldset->addElement($fldVal);

					// SET THE VISIBILITY OF THE FIELDS DEPENDING ON THE OPERATION ------------------------
					$hideFieldsByOp = [ 'anyValue'=>[], 'equal' => [$fldVal], 'notEqual'=> [$fldVal], 'contains'=> [$fldVal], 'notContains'=> [$fldVal], 'hasOnly'=> [$fldVal] ];
					if ($filterDetails['fieldType']=='remark') {
						$hideFieldsByOp['anyValue'] = [$fldRmVar, $fldValidatorType, $fldValidatorLengthMin, $fldValidatorLengthMax];
						$hideFieldsByOp['equal'][] = $fldRmVar;
						$hideFieldsByOp['notEqual'][] = $fldRmVar;
					}
					if ($filterDetails['fieldType']=='serviceRemark') {
						$hideFieldsByOp['anyValue'] = [ $fldRmVar, $fldServiceCode, $fldValidatorType, $fldValidatorLengthMin, $fldValidatorLengthMax];
						$hideFieldsByOp['contains'][] = $fldRmVar; $hideFieldsByOp['contains'][] = $fldServiceCode;
						$hideFieldsByOp['hasOnly'][] = $fldRmVar; $hideFieldsByOp['hasOnly'][] = $fldServiceCode;
						$hideFieldsByOp['notContains'][] = $fldRmVar; $hideFieldsByOp['notContains'][] = $fldServiceCode;
					}
					$fldOp->setControlledElements($hideFieldsByOp, 'hide');
				}
			}

		} // end foreach filters

	}

}
