<?php

// TODO: la supplier product - daca nu se face matching-ul, sa pot sa il adaug preluand informatiile din sistemul extern

namespace Modules\Orders\Services;

class View_Utils_FormAdmin extends \App\Mvc\View_Utils_FormAbstract
{

	/**
	 * The list of imported corporates (by their index in the object) - it is used when managing passeners.
	 * @var array
	 */
	private $importedCorporatesList = [];


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

		// current service operation (insert/update)
		$serviceOperation = $this->values['operation'];

		// INITIALIZATIONS ////////////////////////////////////////////////////////////////////////
		$importedServiceObj = $this->getImportedServiceObj();

		// indicates if this is used on the order form
		$onOrderForm = $this->values['onOrderForm'];

		// checks how the departure and destination fields should be drawn (with or without station; mandatory/optional)
		$locCfg = $this->getLocationCfgs();

		// gets global cfgs
		$CFG = \Engine\Loader_Cfg::getInstance()->getGlobal();

		// load the configurations for the service entity
		$cfgServiceEnt = \Entity\Service::loadCFG();

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

		///////////////////////////////////////////////////////////////////////////////////////////
		// SERVICE DETAILS ////////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////////////////////////

		// the fieldset
		$fieldset1 = \Engine\Form\Container\Fieldset::create($this->lang['formFields']['fieldsetTitle']);
		$form->addContainer($fieldset1);

		// service(s) type
		$fld = new \App\Form\Input\Select_Service($this->lang['formFields']['typeService'], 'serviceCode', $this->values['serviceCode']);
		$fld->setMandatory(true);
		if ($serviceOperation=='insert' or $onOrderForm) {
			$fld->onChange("$('{$this->submitButtonName}').value=0;$('serviceCodeChanged').value=1;this.form.submit();");
		} else {
			$fld->setDisabled();
		}
		if (!$this->values['serviceCode']) {
			$fld->showDefaultOption(true);
		} else {
			$fld->showDefaultOption(false);
		}

		// cleanup inactive services TODO: this shuold not be done like this; the class Select_Service - should manage inactive/active services
		$servicesCodes = $fld->getPossibleValues();
		foreach($servicesCodes as $code1=>&$serviceDetails) {
			if (is_array($serviceDetails)) {
				foreach($serviceDetails as $code2=>$serviceName) {
					if (!\App\Config\ClientServices::getInstance()->isActive($code2)) {
						unset($servicesCodes[$code1][$code2]);
					}
				}
			} else {
				if (!\App\Config\ClientServices::getInstance()->isActive($code1)) {
					unset($servicesCodes[$code1]);
				}
			}
		}

		$fld->setPossibleValues($servicesCodes);

		$fieldset1->addElement($fld);

		// for zz services - add a text field
		if ($this->values['serviceCode']==$CFG['travel']['otherServiceCode']) {
			$fld = new \Engine\Form\Input\Text($this->lang['formFields']['serviceName'], 'serviceName', $this->values['serviceName']);
			$fieldset1->addElement($fld);
		}


		// SERVICE(S) ATTRIBUTES //////////////////////////////////////////////////////////////////
		$this->attachServiceAttributesFormFields($form, $this->values['serviceCode']);

		// OTHER SERVICE DETAILS //////////////////////////////////////////////////////////////////
		$servDurationTypeCfg = \App\Config\Services_Fields::getInstance()->getServiceFieldType($this->values['serviceCode'], 'durationType');

		// service period
		if ($servDurationTypeCfg!='daysTime') { // days/nights
			$fld = new \Engine\Form\Input\DateInterval($this->lang['formFields']['dateInterval'], 'dateInterval', $this->values['dateInterval']);
			$fld->setMandatory(true);
			$fld->setValidatorParam('correlateValues', true);
			$fieldset1->addElement($fld);
		}
		else { // days + hours
			$fld = new \Engine\Form\Input\Datetime($this->lang['formFields']['dateIntervalStart'], 'dateInterval[start]', $this->values['dateInterval']['start']);
			$fld->setMandatory(true);
			$fieldset1->addElement($fld);
			$fld = new \Engine\Form\Input\Datetime($this->lang['formFields']['dateIntervalEnd'], 'dateInterval[end]', $this->values['dateInterval']['end']);
			$fieldset1->addElement($fld);
		}

		// departure
		if ($locCfg['dept']['country'] or $locCfg['dept']['city'] or $locCfg['dept']['station']) {
			if ($locCfg['dept']['city'] and $locCfg['dept']['station']) {
				$fld = new \App\Form\Input\Autocomplete_CountryCityStation();
			} elseif ($locCfg['dept']['city']) {
				$fld = new \App\Form\Input\Autocomplete_CountryCity();
			} elseif ($locCfg['dept']['station']) {
				$fld = new \App\Form\Input\Autocomplete_Station();
			} elseif ($locCfg['dept']['country']) {
				$fld = new \App\Form\Input\Autocomplete_Country();
			}
			$fld->setLabel($this->lang['formFields']['departure']);
			$fld->setName('departure');
			$fld->setValue($this->values['departure']);
			$fld->setMandatory($locCfg['dept']['mandatory']);
			$fld->onPostSelect("refreshOfferLocation()");
			$fld->onPostCancel("refreshOfferLocation()");
			// set the tooltip
			if ($importedServiceObj) {
				$dept = $importedServiceObj->departurePlace;
				if ($dept and $dept->station) {
					$station = $dept->station->name ? : $dept->station->code3;
					$country = $city = '';
					if ($dept->station->city) {
						$city = $dept->station->city->name ? : $dept->station->city->code3;
						if ($dept->station->city->country) {
							$country = $dept->station->city->country->name ? : $dept->station->city->country->code2;
						}
					}
					$fld->setCustomHTML("&nbsp;<span class='italic grey'>[{$country} / {$city} / {$station}]</span>");
				}
			}
			$fieldset1->addElement($fld);
		}

		// destination
		if ($locCfg['dest']['country'] or $locCfg['dest']['city'] or $locCfg['dest']['station']) {
			if ($locCfg['dest']['city'] and $locCfg['dest']['station']) {
				$fld = new \App\Form\Input\Autocomplete_CountryCityStation();
			} elseif ($locCfg['dest']['city']) {
				$fld = new \App\Form\Input\Autocomplete_CountryCity();
			} elseif ($locCfg['dest']['station']) {
				$fld = new \App\Form\Input\Autocomplete_Station();
			} elseif ($locCfg['dest']['country']) {
				$fld = new \App\Form\Input\Autocomplete_Country();
			}
			$fld->setLabel($this->lang['formFields']['destination']);
			$fld->setName('destination');
			$fld->setValue($this->values['destination']);
			$fld->setMandatory($locCfg['dest']['mandatory']);
			$fld->onPostSelect("refreshOfferLocation();");
			$fld->onPostCancel("refreshOfferLocation();");

			// set the tooltip
			if ($importedServiceObj) {
				$dest = $importedServiceObj->destinationPlace;
				if ($dest and $dest->station) {
					$station = $dest->station->name ? : $dest->station->code3;
					$country = $city = '';
					if ($dest->station->city) {
						$city = $dest->station->city->name ? : $dest->station->city->code3;
						if ($dest->station->city->country) {
							$country = $dest->station->city->country->name ? : $dest->station->city->country->code2;
						}
					}
					$fld->setCustomHTML("&nbsp;<span class='italic grey'>[{$country} / {$city} / {$station}]</span>");
				}
			}
			$fieldset1->addElement($fld);
		}

		// descriptipon
		if ($this->values['serviceCode']) {
			$descrVis = \App\Config\Services_Fields::getInstance()->getServiceFieldType($this->values['serviceCode'], 'description');
			if ($descrVis!='invisible') {
				$fld = new \Engine\Form\Input\Textarea($this->lang['formFields']['description'], 'description', $this->values['description']);
				$fld->setHeight(18);
				$fld->setMandatory($descrVis=='mandatory');
				$fieldset1->addElement($fld);
			}
		}

		// comments
		if ($this->values['serviceCode']) {
			$commVis = \App\Config\Services_Fields::getInstance()->getServiceFieldType($this->values['serviceCode'], 'comments');
			if ($commVis!='invisible') {
				$fld = new \Engine\Form\Input\Textarea($this->lang['formFields']['comments'], 'comments', $this->values['comments']);
				$fld->setHeight(18);
				$fld->setMandatory($commVis=='mandatory');
				$fieldset1->addElement($fld);
			}
		}

		// preferences
		if ($this->values['serviceCode']) {
			$prefVis = \App\Config\Services_Fields::getInstance()->getServiceFieldType($this->values['serviceCode'], 'preferences');
			if ($prefVis!='invisible') {
				$fld = new \Engine\Form\Input\Textarea($this->lang['formFields']['preferences'], 'preferences', $this->values['preferences']);
				$fld->setHeight(18);
				$fld->setMandatory($prefVis=='mandatory');
				$fieldset1->addElement($fld);
			}
		}

		// remarks
		$fld = new \App\Form\Input\Remarks($this->lang['formFields']['remarks'], 'remarks', $this->values['remarks']);
		$fld->setRemarksType('service');
		$fld->addGdsProfileButton($this->values['idOrder']);
		$fieldset1->addElement($fld);

		// responsible
		$fld = new \App\Form\Input\Autocomplete_User($this->lang['formFields']['responsible'], 'user', $this->values['user']);
		$fld->setMandatory(true);
		$fieldset1->addElement($fld);

		// agency cost center
		if ($this->values['serviceCode']) {
			$agCcVis = \App\Config\Services_Fields::getInstance()->getServiceFieldType($this->values['serviceCode'], 'agencyCostCenter');
			if ($agCcVis!='invisible') {
				$fld = new \App\Form\Input\Select_AgencyCostCenter($this->lang['formFields']['agencyCostCenter'], 'agencyCostCenter', $this->values['agencyCostCenter']);
				$fld->showDefaultOption(true);
				$fld->setMandatory($agCcVis=='mandatory');
				$fieldset1->addElement($fld);
			}
		}

		// est invoice date
		$fld = new \Engine\Form\Input\Date($this->lang['formFields']['estInvoiceDate'], 'estInvoiceDate', $this->values['estInvoiceDate']);
		$fld->importFromConfig($cfgServiceEnt['estInvoiceDate']);
		$fieldset1->addElement($fld);

		// est cash date
		$fld = new \Engine\Form\Input\Date($this->lang['formFields']['estCashDate'], 'estCashDate', $this->values['estCashDate']);
		$fld->importFromConfig($cfgServiceEnt['estCashDate']);
		$fieldset1->addElement($fld);


		// CORPORATES ASSOCIATIONS ////////////////////////////////////////////////////////////////
		$this->addCorporatesToForm($form);


		// PASSENGERS ASSOCIATIONS ////////////////////////////////////////////////////////////////
		$this->addPassengersToForm($form);

		///////////////////////////////////////////////////////////////////////////////////////////
		// SERVICE OFFER //////////////////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////////////////////////////////
		if ($serviceOperation=='insert' or $onOrderForm) {
			$this->addOfferToForm($form);
		}

		// mice project id
		$form->addElement(new \Engine\Form\Input\Hidden('', 'idMiceProject', $this->values['idMiceProject']));
		// linked to idService
		$form->addElement(new \Engine\Form\Input\Hidden('', 'linkedToIdService', $this->values['linkedToIdService']));
		// order id
		$form->addElement(new \Engine\Form\Input\Hidden('', 'idOrder', $this->values['idOrder']));
		// id imported service
		$form->addElement(new \Engine\Form\Input\Hidden('', 'idImportedService', $this->values['idImportedService']));
		// the list of imported services list
		if ($this->values['idImportedServicesList']) {
			foreach($this->values['idImportedServicesList'] as $thisIdImpServ) {
				$form->addElement(new \Engine\Form\Input\Hidden('', 'idImportedServicesList[]', $thisIdImpServ));
			}
		}
		// on order form flag - for service update
		$form->addElement(new \Engine\Form\Input\Hidden('', 'onOrderForm', $onOrderForm));
		// service id - for service update
		$form->addElement(new \Engine\Form\Input\Hidden('', 'idService', $this->values['idService']));

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


		// FORM RESTRICTIONS //////////////////////////////////////////////////////////////////////

		// the supplier product(s) must be filtered by the destination
		$destinationField = $form->findElementByName('destination');
		$serviceSuppProductField = $form->findElementByName('serviceSupplierProduct');
		$offerSuppProductField = $form->findElementByName('offerSupplierProduct');
		if ($serviceSuppProductField and $destinationField) {
			$serviceSuppProductField->setFilters('destinationPlaceCode', $destinationField);
			$serviceSuppProductField->setFilters('hideDuplicates', 1);
		}
		if ($offerSuppProductField and $destinationField) {
			$offerSuppProductField->setFilters('destinationPlaceCode', $destinationField);
			$offerSuppProductField->setFilters('hideDuplicates', 1);
		}


		// ADD EXTENSIONS INSIDE THE FORM /////////////////////////////////////////////////////////
		\Engine\Plugins\Manager::getInstance()->executeEvent('Modules/Orders/Services-FormAdmin', ['form'=>$form, 'idOrder'=>$this->values['idOrder'], 'idImportedService'=>$this->values['idImportedService']]);

		return $form;

	}



	/**
	 * Adds the service attributes fields for a service code into a form container.
	 * @param \Engine\Form\Container\GeneralAbstract $formContainer
	 * @param String $serviceCode
	 */
	private function attachServiceAttributesFormFields(\Engine\Form\Container\GeneralAbstract $formContainer, $serviceCode)
	{

		// if no service code - skip attributes fields
		if (!$serviceCode) {
			return ;
		}

		// initializations
		$servFields 	= \App\Config\Services_Fields::getInstance();
		$servAttrCfgObj = \App\Config\Services_GeneralAttributes::getInstance();
		$importedServiceObj = $this->getImportedServiceObj();

		// SERVICE CATEGORY -----------------------------------------------------------------------
		$servCatCfg = $servAttrCfgObj->getServiceCategory($serviceCode);
		$servCatFld = $servFields->getServiceFieldType($serviceCode, 'category');
		$servCatListType = $servFields->getServiceAttributeListType($serviceCode, 'category');

		// create the field depending on type
		if ($servCatFld!='invisible') {

			if ($servCatCfg['type'] == 'text') {
				$fld = new \Engine\Form\Input\Text($servCatCfg['fieldFinalName'], "serviceCategory", $this->values['serviceCategory']);
			}
			elseif ($servCatCfg['type'] == 'list' and $servCatListType == 'radio'){
				$fld = new \Engine\Form\Input\Radio($servCatCfg['fieldFinalName'], "serviceCategory", $this->values['serviceCategory']);
				$fld->setPossibleValues($servCatCfg['list']);
			}
			elseif ($servCatCfg['type'] == 'list' and $servCatListType == 'checkbox'){
				$fld = new \Engine\Form\Input\Checkboxes($servCatCfg['fieldFinalName'], "serviceCategory", $this->values['serviceCategory']);
				$fld->setPossibleValues($servCatCfg['list']);
			}

			// create tooltip for service categories
			if ($importedServiceObj and $importedServiceObj->categories and in_array($servCatCfg['type'], ['text', 'list'])) {
				$details = [];
				foreach($importedServiceObj->categories as $code=>$name) {
					if (!strcmp($code, $name)) {
						if ($name) $details[] = $name;
					} else {
						if ($code and $name) {
							$details[] = $code.'/'.$name;
						} elseif ($code) {
							$details[] = $code;
						} elseif ($name) {
							$details[] = $name;
						}
					}
				}
				if ($details) {
					$fld->setCustomHTML("&nbsp;<span class='italic grey'>[".implode(', ', $details)."]</span>");
				}
			}
			// set the mandatory flag and attach it to the form container
			if ($servCatFld == 'mandatory') {
				$fld->setMandatory();
			}
			$formContainer->addElement($fld);
		}

		// SERVICE PRODUCT TYPE -------------------------------------------------------------------
		$servPrTypeCfg = $servAttrCfgObj->getServiceProductType($serviceCode);
		$servPrTypeFld = $servFields->getServiceFieldType($serviceCode, 'productType');
		$servPrTypeListType = $servFields->getServiceAttributeListType($serviceCode, 'productType');

		if ($servPrTypeFld != 'invisible') {
			// create the field depending on type
			if ($servPrTypeCfg['type'] == 'text') {
				$fld = new \Engine\Form\Input\Text($servPrTypeCfg['fieldFinalName'], "serviceProductType", $this->values['serviceProductType']);
			}
			elseif ($servPrTypeCfg['type'] == 'list' and $servPrTypeListType == 'radio') {
				$fld = new \Engine\Form\Input\Radio($servPrTypeCfg['fieldFinalName'], "serviceProductType", $this->values['serviceProductType']);
				$fld->setPossibleValues($servPrTypeCfg['list']);
			}
			elseif ($servPrTypeCfg['type'] == 'list' and $servPrTypeListType == 'checkbox') {
				$fld = new \Engine\Form\Input\Checkboxes($servPrTypeCfg['fieldFinalName'], "serviceProductType", $this->values['serviceProductType']);
				$fld->setPossibleValues($servPrTypeCfg['list']);
			}
			// create tooltip for service product types
			if ($importedServiceObj and $importedServiceObj->productTypes and in_array($servPrTypeCfg['type'], ['text', 'list'])) {
				$details = [];
				foreach($importedServiceObj->productTypes as $code=>$name) {
					if (!strcmp($code, (string)$name)) {
						if ($name) $details[] = $name;
					} else {
						if ($code and $name) {
							$details[] = $code.'/'.$name;
						} elseif ($code) {
							$details[] = $code;
						} elseif ($name) {
							$details[] = $name;
						}
					}
				}
				if ($details) {
					$fld->setCustomHTML("&nbsp;<span class='italic grey'>[".implode(', ', $details)."]</span>");
				}
			}
			// set the mandatory flag and attach it to the form container
			if ( $servPrTypeFld=='mandatory') {
				$fld->setMandatory();
			}

			$formContainer->addElement($fld);
		}


		// SERVICE SOURCE -------------------------------------------------------------------------
		$servSrcCfg = $servAttrCfgObj->getServiceSource($serviceCode);
		$servSrcFld = $servFields->getServiceFieldType($serviceCode, 'serviceSource');
		$servSrcListType  = $servFields->getServiceAttributeListType($serviceCode, 'serviceSource');

		// create the field depending on type
		if ($servSrcFld != 'invisible') {
			if ($servSrcCfg['type'] == 'text') {
				$fld = new \Engine\Form\Input\Text($servSrcCfg['fieldFinalName'], "serviceSource", $this->values['serviceSource']);
			}
			elseif ($servSrcCfg['type'] == 'list' and $servSrcListType == 'radio') {
				$fld = new \Engine\Form\Input\Radio($servSrcCfg['fieldFinalName'], "serviceSource", $this->values['serviceSource']);
				$fld->setPossibleValues($servSrcCfg['list']);
			}
			elseif ($servSrcCfg['type'] == 'list' and $servSrcListType == 'checkbox') {
				$fld = new \Engine\Form\Input\Checkboxes($servSrcCfg['fieldFinalName'], "serviceSource", $this->values['serviceSource']);
				$fld->setPossibleValues($servSrcCfg['list']);
			}
			// set the mandatory flag and attach it to the form container
			if ($servSrcFld=='mandatory') {
				$fld->setMandatory();
			}

			$formContainer->addElement($fld);
		}


		// SERVICE MULTIPLIER ---------------------------------------------------------------------
		$servMulCfg = $servAttrCfgObj->getServiceMultiplier($serviceCode);
		$servMulFld = $servFields->getServiceFieldType($serviceCode, 'productMultiplier');

		if ($servMulFld != 'invisible') {
			if ($servMulCfg['type']=='value') {
				$fld = new \Engine\Form\Input\Text($servMulCfg['fieldFinalName'], "serviceMultiplier", $this->values['serviceMultiplier']);
			}
			elseif ($servMulCfg['type']=='list') {
				$fld = new \App\Form\Input\MultipliedText($servMulCfg['fieldFinalName'], "serviceMultiplier", $this->values['serviceMultiplier']);
				$fld->setMultiplier(count($servMulCfg['list']));
				$fld->setMultiplierLabelKeys(array_keys($servMulCfg['list']));
				$fld->setMultiplierLabels(array_values($servMulCfg['list']));
				$fld->setMultiplierLabelVisibility(true);
				$fld->setStyle('CSSClass', 'input-multipliedElementLabelTop');
			}
			// set the mandatory flag and attach it to the form container
			if ($servMulFld=='mandatory') {
				$fld->setMandatory();
			}

			// create tooltip for service product types
			if ($importedServiceObj and is_array($importedServiceObj->multipliers) and $servMulCfg['type']=='list') {
				$details = [];
				foreach($importedServiceObj->multipliers as $code=>$det) {
					$elem = null;
					if (!strcmp($code, (string)$det['name'])) {
						if ($code) $elem = $code;
					} else {
						if ($code and $det['name']) {
							$elem = $det['name'].'('.$code.')';
						} elseif ($code) {
							$elem = $code;
						} elseif ($det['name']) {
							$elem = $det['name'];
						}
					}
					if ($det['count'] and $elem) {
						$details[] = $det['count'].' &times; '.$elem;
					}
				}
				if ($details) {
					$fld->setCustomHTML("&nbsp;<span class='italic grey'>[".implode(', ', $details)."]</span>");
				}

			}

			// service update opeartion - might display a different message for multiplier based services/offers
			if ($this->values['operation']=='update' and !$this->values['onOrderForm']) {
				$serviceEnt = \Entity\Service::select($this->values['idService']);
				if ($serviceEnt->statusOp=='OK' or $serviceEnt->statusOp=='OF') {
					// multiplier offers
					if (in_array($serviceEnt->chosenOffer->offerType, ['mulBulkSimple', 'mulDetSimple'])) {
						if ($serviceEnt->statusFin=='NI') { // not invoiced
							$fld->addMessage('info', $this->lang['formFields']['info_mulDetInfo1']);
						} else { // partially / totally invoiced
							$fld->addMessage('info', $this->lang['formFields']['info_mulDetInfo2']);
						}
					}
					// non multiplier offer types
					else {
						if ($serviceEnt->statusFin=='NI') { // not invoiced
							$fld->addMessage('info', $this->lang['formFields']['info_mulDetInfo3']);
						} else { // partially / totally invoiced
							$fld->addMessage('info', $this->lang['formFields']['info_mulDetInfo4']);
						}
					}
				}
			}

			$formContainer->addElement($fld);
		}

		// SERVICE PRODUCT NAME -------------------------------------------------------------------
		$servPrNameCfg = $servAttrCfgObj->getServiceProductName($serviceCode);
		$servPrNameFld = $servFields->getServiceFieldType($serviceCode, 'productName');

		if ($servPrNameFld != 'invisible') {
			switch ($servPrNameCfg['type']) {
				case 'text': {
					$fld = new \Engine\Form\Input\Text($servPrNameCfg['fieldFinalName'], "serviceSupplierProduct[title]", $this->values['serviceSupplierProduct']['title']);
					break;
				}
				case 'autocomplete': case 'both': {
					$fld = new \App\Form\Input\Autocomplete_SupplierProduct($servPrNameCfg['fieldFinalName'], "serviceSupplierProduct", $this->values['serviceSupplierProduct']);
					if ($servPrNameCfg['type']=='both') {
						$fld->setClearOnCancel(false);
						$fld->setTooltip($this->lang['formFields']['serviceProductTooltip']);
					}
					$fld->onChange("updateSupplierProductDetails(selectedItem);refreshOfferLocation();");
					// add supplier product fields for easy insert
					if ($this->values['idImportedService'] and $this->getImportedServiceObj()) {
						$suppPrList = $this->getImportedServiceObj()->supplierProducts;
						if ($suppPrList) {
							$suppPrObj = reset($suppPrList);
							if ($suppPrObj) {
								$fld->populateInsertDefaultValuesFromImportedEntity($suppPrObj, \Entity\ImportedService::select($this->values['idImportedService'])->idSystem);
							}
						}
					} // TODO: should  automatically inherit like Autocomplete_ImportedOrderCustomer (right now it does not work fine if the fields have HTML entities: ", ', &)
					break;
				}
			}
			// set the mandatory flag and attach it to the form container
			if ($servPrNameCfg['type']=='text' or $servPrNameCfg['type']=='autocomplete' or $servPrNameCfg['type']=='both') {
				if ($servPrNameFld == 'mandatory') {
					$fld->setMandatory();
				}
				// set the tooltip
				if ($importedServiceObj) {
					$prList = $importedServiceObj->supplierProducts;
					if ($prList) {
						$suppPr = reset($prList);
						if ($suppPr and $suppPr->name) {
							$fld->setCustomHTML("&nbsp;<span class='italic grey'>[{$suppPr->name}]</span>");
						}
					}
				}
				$formContainer->addElement($fld);
			}
		}

	}


	/**
	 * Checks the services list (or only one) and indicates how the field should be rendered (city,
	 * station, city+station). It also indicates if the field should be mandatory or not.
	 * It outputs an associative array in a certain format (containing both departure and destination).
	 * @return Array
	 */
	private function getLocationCfgs()
	{

		// if no service code set
		if (!$this->values['serviceCode']) {
			return [];
		}

		$servFldsCfgObj = \App\Config\Services_Fields::getInstance();
		$locCfg = [];
		// check if the locations fields are visible
		// departure
		if ($servFldsCfgObj->getServiceFieldType($this->values['serviceCode'], 'departureCountry')!='invisible') {
			$locCfg['dept']['country'] = true;
		}
		if ($servFldsCfgObj->getServiceFieldType($this->values['serviceCode'], 'departureCity')!='invisible') {
			$locCfg['dept']['city'] = true;
		}
		if ($servFldsCfgObj->getServiceFieldType($this->values['serviceCode'], 'departureStation')!='invisible') {
			$locCfg['dept']['station'] = true;
		}
		// destination
		if ($servFldsCfgObj->getServiceFieldType($this->values['serviceCode'], 'destinationCountry')!='invisible') {
			$locCfg['dest']['country'] = true;
		}
		if ($servFldsCfgObj->getServiceFieldType($this->values['serviceCode'], 'destinationCity')!='invisible') {
			$locCfg['dest']['city'] = true;
		}
		if ($servFldsCfgObj->getServiceFieldType($this->values['serviceCode'], 'destinationStation')!='invisible') {
			$locCfg['dest']['station'] = true;
		}
		// check if the locations fields are mandatory
		if ($servFldsCfgObj->getServiceFieldType($this->values['serviceCode'], 'departureCountry')=='mandatory') {
			$locCfg['dept']['mandatory'] = true;
		}
		if ($servFldsCfgObj->getServiceFieldType($this->values['serviceCode'], 'destinationCountry')=='mandatory') {
			$locCfg['dest']['mandatory'] = true;
		}

		return $locCfg;
	}

	/**
	 * Adds offer fields to form.
	 * @param \Engine\Form\General $form
	 */
	private function addOfferToForm(\Engine\Form\General $form)
	{

		// current service code
		$serviceCode = $this->values['serviceCode'];

		// if no service code - completely hide the offer details
		if (!$serviceCode) {
			return ;
		}

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

		// offer section was set to be hidden (independently for new/existing order)
		if (!$this->values['idOrder'] and !$CFG['Orders']['Services']['defaultValues']['newOrder']['allowOfferDefinition'] and !$this->values['idImportedService']) {
			return ;
		}
		if ($this->values['idOrder'] and !$CFG['Orders']['Services']['defaultValues']['existingOrder']['allowOfferDefinition'] and !$this->values['idImportedService']) {
			return ;
		}

		// get imported service and offer details
		$impOffObj = null;
		if ($this->values['idImportedService']) {
			$impServEnt = \Entity\ImportedService::select($this->values['idImportedService']);
			$impServObj = $impServEnt->object;
			$impOffObj = $impServObj->chosenOffer;
		}

		// get sevice fields cfgs
		$servAttrCfgObj = \App\Config\Services_GeneralAttributes::getInstance();
		$servAttrFldObj = \App\Config\Services_Fields::getInstance();
		// get service ext res details
		$offConfCfg = \App\Config\Services_OfferFields::getInstance()->get($serviceCode);

		$offComponentsCfg = \App\Config\Services_OfferRowTypes::getInstance()->get($serviceCode);

		// the fieldset
		$fieldset = \Engine\Form\Container\Fieldset::create($this->lang['formFields']['offerFielsetTitle']);
		$fieldset->setCollapsible(true);
		$form->addContainer($fieldset);

		// package offer type
		if ($this->values['isPackage']) {
			$offPackageOfferModeFld = new \Engine\Form\Input\Select($this->lang['formFields']['packageOfferMode'], 'packageOfferMode', $this->values['packageOfferMode']);
			$offPackageOfferModeFld->setPossibleValues(['reference'=>$this->lang['formFields']['packageOfferMode_ref'], 'independent'=>$this->lang['formFields']['packageOfferMode_indep']]);
			$offPackageOfferModeFld->setTooltip($this->lang['formFields']['packageOfferModeTooltip']);
			$offPackageOfferModeFld->showDefaultOption();
			$offPackageOfferModeFld->setMandatory();
			$fieldset->addElement($offPackageOfferModeFld);
		}

		// offer operation
		$offOperationFld = new \Engine\Form\Input\Select($this->lang['formFields']['offerOperation'], 'offerOperation', $this->values['offerOperation']);
		$offOperationFld->setPossibleValues([
				''=> 						$this->lang['formFields']['defaultOfferOperation'],
				'insert' => 				$this->lang['formFields']['offerOperationInsert'],
				'insert+choose' => 			$this->lang['formFields']['offerOperationInsertAndChoose'],
				'insert+choose+confirm' => 	$this->lang['formFields']['offerOperationInsertAndChooseConfirm'],
			]
		);
		$fieldset->addElement($offOperationFld);

		// offer calculation
		$offCalcFld = new \App\Form\Input\Select_LocationCalculation($this->lang['formFields']['offerCalculation'], 'offerCalculation', $this->values['offerCalculation']);
		$offCalcFld->setServiceCode($this->values['serviceCode']);
		$offCalcFld->setMandatory(true);
		if (!$this->values['idImportedService']) {
			$offCalcFld->onChange("refreshOfferCurrencies();"); // the offer currencies are updated only if the service is manual (for imported service we expect that the currencies are already set)
		}
		$fieldset->addElement($offCalcFld);

		// supplier field
		$offSupplierFld = new \App\Form\Input\Autocomplete_Supplier($this->lang['formFields']['supplier'], 'offerSupplier', $this->values['offerSupplier']);
		$offSupplierFld->setMandatory(true);
		$offSupplierFld->setFilters('hideDuplicates', 1);
		// display tooltip
		if ($impOffObj and $impOffObj->supplier) {
			$impSuppObj = $impOffObj->supplier;
			$details = [];
			if ($impSuppObj->name) $details[] = $impSuppObj->name;
			if ($impSuppObj->idSystem) $details[] = $impSuppObj->idSystem;
			if ($impSuppObj->codes) {
				foreach($impSuppObj->codes as $code) {
					if ($code) $details[] = $code;
				}
			}
			if ($details) {
				$offSupplierFld->setCustomHTML("&nbsp;<span class='italic grey'>[".implode(', ', array_unique($details))."]</span>");
			}
		}
		$fieldset->addElement($offSupplierFld);

		// supplier product field
		$servPrNameCfg = $servAttrCfgObj->getServiceProductName($serviceCode);
		$servPrNameFld = $servAttrFldObj->getServiceFieldType($serviceCode, 'productName');
		if ($servPrNameFld!='invisible') {
			switch ($servPrNameCfg['type']) {
				case 'text': {
					$offSupplierProductFld = new \Engine\Form\Input\Text($servPrNameCfg['fieldFinalName'], 'offerSupplierProduct[title]', $this->values['offerSupplierProduct']['title']);
					break;
				}
				case 'autocomplete': case 'both': {
					$offSupplierProductFld = new \App\Form\Input\Autocomplete_SupplierProduct($this->lang['formFields']['supplierProduct'], 'offerSupplierProduct', $this->values['offerSupplierProduct']);
					if ($servPrNameCfg['type']=='both') {
						$offSupplierProductFld->setClearOnCancel(false);
					}
					break;
				}
			}
			// display tooltip
			if ($impOffObj and $impOffObj->supplierProduct) {
				$impSuppPrObj = $impOffObj->supplierProduct;
				$details = [];
				if ($impSuppPrObj->name) $details[] = $impSuppPrObj->name;
				if ($impSuppPrObj->idSystem) $details[] = $impSuppPrObj->idSystem;
				if ($impSuppPrObj->groupName) $details[] = $impSuppPrObj->groupName;
				if ($details) {
					$offSupplierProductFld->setCustomHTML("&nbsp;<span class='italic grey'>[".implode(', ', array_unique($details))."]</span>");
				}
			}
			if ($impOffObj and $impOffObj->supplierProduct) {
				$offSupplierProductFld->setCustomHTML("&nbsp;<span class='italic grey'>[{$impOffObj->supplierProduct->name}]</span>");
			}
			// add supplier product fields for easy insert
			if ($impOffObj and $impOffObj->supplierProduct and ($servPrNameCfg['type']=='autocomplete' or $servPrNameCfg['type']=='both')) {
				// get system id
				$offSupplierProductFld->populateInsertDefaultValuesFromImportedEntity($impOffObj->supplierProduct, \Entity\ImportedService::select($this->values['idImportedService'])->idSystem);
			}
			$fieldset->addElement($offSupplierProductFld);
		}

		// service price + ignore supp
		$offServicePriceFld = new \App\Form\Input\Price($this->lang['formFields']['servicePrice'], 'offerServicePrice', $this->values['offerServicePrice']);
		$offServicePriceFld->setTooltip($this->lang['formFields']['servicePriceTooltip']);

		$offServicePriceFld->setCustomHTML(sprintf("&nbsp;<a href='#;' class='link' onclick='getOfferProfile(%s)'>%s</a>", json_encode($offComponentsCfg), $this->lang['formFields']['refreshProfileBtn']));
		$fieldset->addElement($offServicePriceFld);

		// commission + commissionable
		$offCommissionFld = new \App\Form\Input\Price_ActiveOfferProfileCommission($this->lang['formFields']['commission'], 'offerCommission', $this->values['offerCommission']);
		$offCommissionFld->setTooltip($this->lang['formFields']['commissionTooltip']);
		$fieldset->addElement($offCommissionFld);

		// discount
		$offDiscountFld = new \App\Form\Input\Price_ActiveOfferProfile($this->lang['formFields']['discount'], 'offerDiscount', $this->values['offerDiscount']);
		$offDiscountFld->setTooltip($this->lang['formFields']['discountTooltip']);
		if (!$offComponentsCfg['discount']) {
			$offDiscountFld->setInvisible(true);
		}
		$fieldset->addElement($offDiscountFld);

		// service fee
		$offServiceFeeFld = new \App\Form\Input\Price_ActiveOfferProfile($this->lang['formFields']['serviceFee'], 'offerServiceFee', $this->values['offerServiceFee']);
		$offServiceFeeFld->setTooltip($this->lang['formFields']['serviceFeeTooltip']);
		if (!$offComponentsCfg['serviceFee']) {
			$offServiceFeeFld->setInvisible(true);
		}
		$fieldset->addElement($offServiceFeeFld);

		// taxes
		$offTaxFld = new \App\Form\Input\Price($this->lang['formFields']['taxes'], 'offerTax', $this->values['offerTax']);
		if (!$offComponentsCfg['tax']) {
			$offTaxFld->setInvisible(true);
		}
		$fieldset->addElement($offTaxFld);

		// total price
		$offTotalFld = new \App\Form\Input\Price($this->lang['formFields']['offerTotal'], 'offerTotal');
		$offTotalFld->setDisabled(true);
		$offTotalFld->setCustomHTML(sprintf("<a href='#;' class='link' onclick='refreshOfferTotal()'>%s</a>", $this->lang['formFields']['refreshTotalBtn']));
		$fieldset->addElement($offTotalFld);

		// ignore supplier on documents
		$offIgnoreSuppOnDocFld = new \Engine\Form\Input\Checkbox($this->lang['formFields']['ignoreSuppOnDocs'], 'offerIgnoreSupplierOnDocuments', $this->values['offerIgnoreSupplierOnDocuments']);
		$offIgnoreSuppOnDocFld->setCheckboxLabel($this->lang['formFields']['ignoreSuppOnDocsLabel']);
		$offIgnoreSuppOnDocFld->setTooltip($this->lang['formFields']['ignoreSuppOnDocsTooltip']);
		$fieldset->addElement($offIgnoreSuppOnDocFld);

		// currency type
		$offCurrTypeFld = new \App\Form\Input\Select_CurrencyType($this->lang['formFields']['currencyType'], 'offerCurrencyType', $this->values['offerCurrencyType']);
		$fieldset->addElement($offCurrTypeFld);

		// currency date
		$offCurrDateFld = new \Engine\Form\Input\Date($this->lang['formFields']['currencyDate'], 'offerCurrencyDate', $this->values['offerCurrencyDate']);
		$fieldset->addElement($offCurrDateFld);

		// offer currency
		$offTotalCurrFld = new \App\Form\Input\Select_Currency($this->lang['formFields']['offerCurrency'], 'offerTotalCurrency', $this->values['offerTotalCurrency']);
		$fieldset->addElement($offTotalCurrFld);

		// confirmation number
		if ($offConfCfg['confirmationNumber']!='invisible') {
			$offConfNoFld = new \Engine\Form\Input\Text($this->lang['formFields']['confirmationNumber'], 'offerConfirmationNumber', $this->values['offerConfirmationNumber']);
			if ($offConfCfg['confirmationNumber']=='mandatory') {
				$offConfNoFld->setMandatory();
			}
			$fieldset->addElement($offConfNoFld);
		}

		// ext res id
		if ($offConfCfg['externalSystemReservationId']!='invisible') {
			$offExtResIdFld = new \Engine\Form\Input\Text($this->lang['formFields']['extResId'], 'offerExternalSystemReservationId', $this->values['offerExternalSystemReservationId']);
			if ($offConfCfg['externalSystemReservationId']=='mandatory') {
				$offExtResIdFld->setMandatory();
			}
			$fieldset->addElement($offExtResIdFld);
		}

		// ext res date
		if ($offConfCfg['externalSystemReservationDate']!='invisible') {
			$offExtResDateFld = new \Engine\Form\Input\Date($this->lang['formFields']['extResDate'], 'offerExternalSystemReservationDate', $this->values['offerExternalSystemReservationDate']);
			if ($offConfCfg['externalSystemReservationDate']=='mandatory') {
				$offExtResDateFld->setMandatory();
			}
			$fieldset->addElement($offExtResDateFld);
		}

		// expire date
		$offExpireFld = new \Engine\Form\Input\Date($this->lang['formFields']['expireDate'], 'offerExpireDate', $this->values['offerExpireDate']);
		$fieldset->addElement($offExpireFld);

		// cancellation policy
		if ($offConfCfg['cancellationPolicy']!='invisible') {
			$offCancPolFld = new \Engine\Form\Input\Textarea($this->lang['formFields']['cancellationPolicy'], 'offerCancellationPolicy', $this->values['offerCancellationPolicy']);
			$offCancPolFld->setHeight(18);
			$offCancPolFld->setMandatory($offConfCfg['cancellationPolicy']=='mandatory');
			$fieldset->addElement($offCancPolFld);
		}

		// option date
		if ($offConfCfg['optionDate']!='invisible') {
			$offOptionDateFld = new \Engine\Form\Input\Date($this->lang['formFields']['optionDate'], 'offerOptionDate', $this->values['offerOptionDate']);
			if ($offConfCfg['optionDate']=='mandatory') {
				$offOptionDateFld->setMandatory();
			}
			$fieldset->addElement($offOptionDateFld);
		}

		// offer form of payment
		if ($offConfCfg['formOfPayment']!='invisible') {
			$offFopFld = new \App\Form\Input\Select_OfferFormOfPayment($this->lang['formFields']['offerPayment'], 'offerFormOfPayment', $this->values['offerFormOfPayment']);
			$offFopFld->showDefaultOption(true);
			$offFopFld->setMandatory($offConfCfg['formOfPayment']=='mandatory');
			$fieldset->addElement($offFopFld);
		}

		// offer form of cashing
		if ($offConfCfg['formOfCashing']!='invisible') {
			$offFocFld = new \App\Form\Input\Select_OfferFormOfCashing($this->lang['formFields']['offerCashing'], 'offerFormOfCashing', $this->values['offerFormOfCashing']);
			$offFocFld->showDefaultOption(true);
			$offFocFld->setMandatory($offConfCfg['formOfCashing']=='mandatory');
			$fieldset->addElement($offFocFld);
		}

		// show/hide fields
		$offerFields = [
				$offCalcFld, $offSupplierFld, $offServicePriceFld, $offCommissionFld, $offTotalFld,
				$offIgnoreSuppOnDocFld, $offCurrTypeFld, $offCurrDateFld, $offTotalCurrFld,
				$offExpireFld
		];
		if ($offComponentsCfg['discount']) {
			$offerFields[] = $offDiscountFld;
		}
		if ($offComponentsCfg['serviceFee']) {
			$offerFields[] = $offServiceFeeFld;
		}
		if ($offComponentsCfg['tax']) {
			$offerFields[] = $offTaxFld;
		}
		if ($offConfCfg['externalSystemReservationId']!='invisible') $offerFields[] = $offExtResIdFld;
		if ($offConfCfg['externalSystemReservationDate']!='invisible') $offerFields[] = $offExtResDateFld;
		if ($offConfCfg['confirmationNumber']!='invisible') $offerFields[] = $offConfNoFld;
		if ($offConfCfg['optionDate']!='invisible') $offerFields[] = $offOptionDateFld;
		if ($offConfCfg['cancellationPolicy']!='invisible') $offerFields[] = $offCancPolFld;
		if ($offConfCfg['formOfPayment']!='invisible') $offerFields[] = $offFopFld;
		if ($offConfCfg['formOfCashing']!='invisible') $offerFields[] = $offFocFld;
		if ($servPrNameFld!='invisible') $offerFields[] = $offSupplierProductFld;
		$offOperationFld->setControlledElements( ['insert'=>$offerFields, 'insert+choose'=>$offerFields, 'insert+choose+confirm'=>$offerFields], 'hide');

	}


	private function addCorporatesToForm(\Engine\Form\General $form)
	{

		// IF THE DISPLAYED PASSENGERS ARE THE ONES ON THE ORDER //////////////////////////////////
		if ($this->values['idImportedService'] and $this->values['importedCorporatesList']) {

			// get system id
			$impServEnt = \Entity\ImportedService::select($this->values['idImportedService']);
			$idSystem = $impServEnt->idSystem;

			// the fieldset
			$fieldset = \Engine\Form\Container\Fieldset::create($this->lang['formFields']['corporatesFieldset']);
			$fieldset->setCollapsed(false);
			$fieldset->setCollapsible(true);
			$form->addContainer($fieldset);

			// LOOP THROUGH EACH CORPORATE AND CREATE A FIELD -------------------------------------
			foreach($this->values['importedCorporatesList'] as $corpIdx=>$corpObj) {

				$corpFld = new \App\Form\Input\Autocomplete_ImportedOrderCorporate(sprintf($this->lang['formFields']['importedCorporate'], $corpIdx+1), "importedCorporate[{$corpIdx}]", $this->values['importedCorporate'][$corpIdx]);
				$corpFld->setImportedCorporate($corpObj);
				$corpFld->setIdSystem($idSystem);
				$corpFld->setExtraInfo('corpIdx', $corpIdx);

				$fieldset->addElement($corpFld);

				// store a reference to the corporate object so that it is used when managing passeners
				$this->importedCorporatesList[$corpIdx] = ['object'=>$corpObj, 'idField'=>$corpFld->elementId()];

			}

		}

	}

	private function addPassengersToForm(\Engine\Form\General $form)
	{

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

		// the fieldset
		$fieldset = \Engine\Form\Container\Fieldset::create($this->lang['formFields']['fieldsetPaxTitle']);
		$fieldset->setCollapsed(false);
		$fieldset->setCollapsible(true);
		$form->addContainer($fieldset);

		// IF THE DISPLAYED PASSENGERS ARE THE ONES ON THE ORDER //////////////////////////////////
		if (!$this->values['idImportedService']) {

			// the existing defined passengers fields
			if ($this->values['definedPaxFullList']) {
				$fld = new \Engine\Form\Input\Checkboxes($this->lang['formFields']['definedPax'], 'definedPax', $this->values['definedPax']);
				$fld->setMandatory(true);
				$fld->setTooltip($this->lang['formFields']['definedPaxTooltip']);
				$fld->setPossibleValues($this->values['definedPaxFullList']);
				$fieldset->addElement($fld);
			}

			// the existing undefined passengers
			$labels = [];
			foreach($CFG['generalData']['personTypes'] as $type) {
				$labels[$type] = $this->globalLang['generalData']['personTypesPl'][$type]."<b>/".(Int)$this->values['undefinedPaxFullList'][$type]."</b>";
			}
			$fld = new \App\Form\Input\MultipliedText($this->lang['formFields']['undefinedPax'], 'undefinedPax', $this->values['undefinedPax']);
			$fld->setValidatorParam('type', 'int');
			$fld->setValidatorParam('minValue', '0');
			$fld->setMultiplier(count($labels));
			$fld->setMultiplierLabelKeys(array_keys($labels));
			$fld->setMultiplierLabels(array_values($labels));
			$fld->setMultiplierLabelVisibility(true);
			$fld->setStyle('CSSClass', 'input-multipliedElementLabelTop');
			$fld->setTooltip($this->lang['formFields']['undefinedPaxTooltip']);
			$fieldset->addElement($fld);

			// new (defined) passengers
			$fld = new \App\Form\Input\Cloned_AutocompleteCustomer($this->lang['formFields']['newPax'], 'newCustomers', $this->values['newCustomers']);
			$fld->setTooltip($this->lang['formFields']['newPaxTooltip']);
			$fld->setFilters('hideDuplicates', 1);
			$fieldset->addElement($fld);

		}
		// IF THE DISPLAYED PASSENGERS ARE THE ONES FROM THE IMPORTED SERVICE /////////////////////
		else {

			$impServEnt = \Entity\ImportedService::select($this->values['idImportedService']);
			$impServObj = $impServEnt->object;

			$impOffObj = null;

			// get the chosen offer - to display the ticket numbers
			if ($impServObj and $impServObj->chosenOffer) {
				$impOffObj = $impServObj->chosenOffer;
			}

			if ($impServObj and $impServObj->passengers) {
				$psgIdx=0;
				foreach($impServObj->passengers as $importedPassengerObj) {

					$label = sprintf('%s #%s', $this->lang['formFields']['pax'], $psgIdx+1);
					if ($impOffObj) {
						$tktNo = $impOffObj->getPassengerTicket($importedPassengerObj);
						if ($tktNo) {
							$label .= "<br /><i>[{$tktNo}]</i>";
						}
					}

					$psgFld = new \App\Form\Input\Autocomplete_ImportedOrderCustomer($label, "importedPassenger[{$psgIdx}]");
					$psgFld->setMandatory(true);
					$psgFld->setValue($this->values['importedPassenger'][$psgIdx]);
					$psgFld->setTooltip($this->lang['formFields']['paxTooltip']);
					$psgFld->setFilters('hideDuplicates', 1);
					if ($this->values['importedPassenger'][$psgIdx]['insertType']) {
						$psgFld->setInsertType($this->values['importedPassenger'][$psgIdx]['insertType']);
					}
					$psgFld->setIdImportedService($this->values['idImportedService']);
					$psgFld->setPassengerIdx($psgIdx);

					$fieldset->addElement($psgFld);

					$psgIdx++;

				}
			}

		}

	}

	/**
	 * Returns the imported service object.
	 * @return \App\ImportedOrder\Service
	 */
	private function getImportedServiceObj()
	{
		if (!$this->values['idImportedService']) {
			return null;
		}
		$importedServiceEnt = \Entity\ImportedService::select($this->values['idImportedService']);
		if (!$importedServiceEnt->recordExists()) {
			return null;
		}
		return $importedServiceEnt->object;

	}


}



