<?php
namespace Modules\Orders\ImportedOrders\ServicesList;

class View_ViewOrderRenderImportedOrder
{
	/**
	 * Render importedOrder object
	 * @param \App\ImportedOrder\Order $importedOrderObj
	 * @param Array $importedServicesList
	 * @return String
	 */
	public function renderImportedOrder(\App\ImportedOrder\Order $importedOrderObj, $importedServicesList)
	{

		$smarty = \Engine\Smarty\SmartyMultiton::getInstance();

		// temporary store all internal smarty vars. render_prepare() will overwrite some of the existing variables
		$tplVars = $smarty->getTemplateVars();

		$smarty->addTemplateDir( __DIR__.'/_tpl/');

		// set template name
		$templateName = 'viewOrderRenderImportedOrder.tpl';

		// send to Smary some variables
		$smarty->assign('passengersList', $this->extractPassengersList($importedOrderObj));
		$smarty->assign('corporatesList', $this->extractCorporatesList($importedOrderObj));
		$smarty->assign('servicesList',	$this->extractServicesList($importedOrderObj, $importedServicesList));
		$smarty->assign('importedOrderObj', $importedOrderObj);

		$smarty->registerPlugin('modifier', "next", function($arr) { return next($arr); } );

		$idExternalSystem = \Entity\ExtResSystem::getSystemIdByCode($importedOrderObj->externalSystemCode);
		$externalSystemName = \Entity\ExtResSystem::select($idExternalSystem)->name;
		$smarty->assign('systemName', $externalSystemName);

		// extract lang
		\App\Loader_Lang::getInstance()->loadSection('Modules/Orders/ImportedOrders/ServicesList');
		$_LANG = \App\Loader_Lang::getInstance()->getSection('Modules/Orders/ImportedOrders/ServicesList');

		$smarty->assign('lang', $_LANG);

		// generates the smarty output
		$result = $smarty->fetch($templateName);

		// re-assigns all saved smarty vars
		$smarty->clearAllAssign();
		foreach($tplVars as $k=>$v){
			$smarty->assign($k, $v);
		}

		return $result;
	}

	/**
	 * Extract passengers list
	 * @param \App\ImportedOrder\Order $importedOrder
	 * @return Array
	 */
	private function extractPassengersList(\App\ImportedOrder\Order $importedOrder)
	{
		$passengersList = [];

		$passengerIndex = 0;

		// extract id system
		$idSystem = \Entity\ExtResSystem::getSystemIdByCode($importedOrder->externalSystemCode);

		$ownerPassengerObj = $importedOrder->ownerPassenger;

		if ($importedOrder->passengers) {
			foreach ($importedOrder->passengers as $paxObj) {
				$passengerIndex++;

				$passengersList[$passengerIndex] = [
					'object' => $paxObj,
				];

				$passengersList[$passengerIndex]['ownerPax'] = false;

				if ($ownerPassengerObj and $ownerPassengerObj === $paxObj) {
					$passengersList[$passengerIndex]['ownerPax'] = true;
				}

				// extract passenger type
				$paxType = $paxObj->type;
				if ($paxType) {
					$passengersList[$passengerIndex]['type']['codeSystem'] = 	$paxObj->type->codeSystem;
					$passengersList[$passengerIndex]['type']['codeTina'] = 		$paxType->getMatchedId($idSystem);
				}

				// extract passenger title
				if ($paxObj->title) {
					$passengersList[$passengerIndex]['title']['codeTina'] = 	$paxObj->title->codeTina;
				}

				// get passports
				if ($paxObj->passports) {
					foreach ($paxObj->passports as $passport) {
						$passengersList[$passengerIndex]['passports'][] = $passport->number;
					}
				}

				// get fb cards
				if ($paxObj->fbCard) {
					$passengersList[$passengerIndex]['fbCard'] = $paxObj->fbCard->number;
				}
			}
		}

		return $passengersList;
	}

	/**
	 * Extract corporates list
	 * @param \App\ImportedOrder\Order $importedOrder
	 */
	private function extractCorporatesList(\App\ImportedOrder\Order $importedOrder)
	{
		$corporatesList = [];

		// extract id system
		$idSystem = \Entity\ExtResSystem::getSystemIdByCode($importedOrder->externalSystemCode);

		$ownerCorporateObj = $importedOrder->ownerCorporate;

		$corporateIndex = 0;
		foreach ((array)$importedOrder->corporates as $corporateDetails) {
			$corporateIndex++;

			$corporatesList[$corporateIndex]['ownerCorp'] = false;

			if ($ownerCorporateObj and $ownerCorporateObj === $corporateDetails) {
				$corporatesList[$corporateIndex]['ownerCorp'] = true;
			}

			$corporatesList[$corporateIndex]['idSystem'] = 			$corporateDetails->idSystem;
			$corporatesList[$corporateIndex]['fullNameStandard'] = 	trim($corporateDetails->prefixStandard.' '.$corporateDetails->nameStandard.' '.$corporateDetails->suffixStandard);
			$corporatesList[$corporateIndex]['fullNameLocal'] = 	trim($corporateDetails->prefixLocal.' '.$corporateDetails->nameLocal.' '.$corporateDetails->suffixLocal);

			// details fiscalCode and vatCertificateNumber
			$corporatesList[$corporateIndex]['details']['fiscalCode'] = $corporateDetails->fiscalCode;
			$corporatesList[$corporateIndex]['details']['vatCertificateNumber'] = $corporateDetails->vatCertificateNumber;

			// contact details
			$corporatesList[$corporateIndex]['contacts']['email'] = 			$corporateDetails->email;
			$corporatesList[$corporateIndex]['contacts']['telephone'] = 		$corporateDetails->telephone;
			$corporatesList[$corporateIndex]['contacts']['registryAddress'] = 	$corporateDetails->registryAddress;

			if ($corporateDetails->getMatchedId($idSystem)) {
				$corporatesList[$corporateIndex]['idCorporateTina'] = $corporateDetails->getMatchedId($idSystem);
			}
		}

		return $corporatesList;
	}

	/**
	 * Extract passenger index
	 * @param \App\ImportedOrder\Order $importedOrder
	 * @param \App\ImportedOrder\Passenger $paxObj
	 */
	private function getPassengerIndex(\App\ImportedOrder\Order $importedOrder, \App\ImportedOrder\Passenger $paxObj)
	{
		$passengersList = $this->extractPassengersList($importedOrder);
		foreach ($passengersList as $paxIndex => $passenger) {
			if ($paxObj === $passenger['object']) {
				return $paxIndex;
			}
		}

		return false;
	}

	/**
	 * Extract servicesList
	 * @param \App\ImportedOrder\Order $importedOrder
	 * @param Array $importedServicesList
	 * @return Array
	 */
	private function extractServicesList(\App\ImportedOrder\Order $importedOrder, $importedServicesList)
	{
		global $CFG;
		$servicesList = [];

		$serviceIndex = 0;

		// extract id system
		$idSystem = \Entity\ExtResSystem::getSystemIdByCode($importedOrder->externalSystemCode);

		foreach ($importedOrder->services as $service) {
			$serviceIndex++;
			$servicesList[$serviceIndex] = [
				'object' => $service,
			];


			// imported service id
			$serviceDetails = \Entity\ImportedService::getDetailsByServiceExtSys($service->idSystem, $idSystem, true);
			if ($serviceDetails) {
				$servicesList[$serviceIndex]['idImportedService'] = $serviceDetails['id'];
			}

			// imported service id
			if ($service->idReissuedService) {
				$servicesList[$serviceIndex]['reissuedService'] = \Entity\ImportedService::getDetailsByServiceExtSys($service->idReissuedService, $idSystem, true);
			}


			// passengers
			foreach ((array)$service->passengers as $paxObj) {
				$passengerIndex =  $this->getPassengerIndex($importedOrder, $paxObj);
				$servicesList[$serviceIndex]['paxIndexList'][] = $passengerIndex;
			}

			// code system
			if ($service->serviceType) {
				$tinaCode = $service->serviceType->getMatchedId($idSystem);
				$servicesList[$serviceIndex]['serviceType']['codeSystem'] = $service->serviceType->codeSystem;
				$servicesList[$serviceIndex]['serviceType']['codeTina'] = 	$service->serviceType->codeTina;
				$servicesList[$serviceIndex]['serviceType']['name'] = 		$service->serviceType->name;
				$servicesList[$serviceIndex]['serviceType']['matchedTinaCode']  = $tinaCode;
				$servicesList[$serviceIndex]['serviceType']['isTicketing']		= ($tinaCode==$CFG['travel']['ticketing'] ? true : false);
			}

			// departure date time
			if ($service->departureDateTime) {
				$servicesList[$serviceIndex]['departureDateTime']['dateStart'] = 	$service->departureDateTime->getMatchedDate();
				$servicesList[$serviceIndex]['departureDateTime']['dateDetails'] = 	$service->departureDateTime->dateDetails;
				$servicesList[$serviceIndex]['departureDateTime']['timeDetails'] = 	$service->departureDateTime->timeDetails;
			}

			if ($service->destinationDateTime) {
				$servicesList[$serviceIndex]['destinationDateTime']['dateStart'] = 	$service->destinationDateTime->getMatchedDate();
				$servicesList[$serviceIndex]['destinationDateTime']['dateDetails'] = $service->destinationDateTime->dateDetails;
				$servicesList[$serviceIndex]['destinationDateTime']['timeDetails'] = $service->destinationDateTime->timeDetails;
			}

			// destination
			$destinationPlace = $service->destinationPlace;

			if ($destinationPlace) {
				$servicesList[$serviceIndex]['destinationPlace'] = $destinationPlace->getMatchedId($idSystem);

				$stationObj = $destinationPlace->station;
				$cityObj 	= null;
				$countryObj = null;

				if ($stationObj) {
					$cityObj = $stationObj->city;
				}

				if ($cityObj) {
					$countryObj = $cityObj->country;
				}

				$servicesList[$serviceIndex]['destinationPlace']['stationCode3'] = $stationObj->code3??null;
				$servicesList[$serviceIndex]['destinationPlace']['stationName'] =  $stationObj->name??null;
				if ($stationObj and $stationObj->getMatchedId($idSystem)) {
					$servicesList[$serviceIndex]['destinationPlace']['stationMatched'] = $stationObj->getMatchedId($idSystem);
				}

				$servicesList[$serviceIndex]['destinationPlace']['countryCode2'] = $countryObj->code2??null;
				$servicesList[$serviceIndex]['destinationPlace']['countryName'] = $countryObj->name??null;
				if ($countryObj and $countryObj->getMatchedId($idSystem)) {
					$servicesList[$serviceIndex]['destinationPlace']['countryMatched'] = $countryObj->getMatchedId($idSystem);
				}

				$servicesList[$serviceIndex]['destinationPlace']['cityCode3'] = $cityObj->code3??null;
				$servicesList[$serviceIndex]['destinationPlace']['cityName'] = $cityObj->name??null;

				if ($cityObj and $cityObj->getMatchedId($idSystem)) {
					$servicesList[$serviceIndex]['destinationPlace']['cityMatched'] = $cityObj->getMatchedId($idSystem);
				}
			}

			// process status
			$serviceInformations = $this->getProcessStatus($service->idSystem, $importedServicesList);

			if ($serviceInformations) {
				$servicesList[$serviceIndex]['status'] = $serviceInformations;
			}

			// chosen offer
			$chosenOffer = $service->chosenOffer;
			if ($chosenOffer) {
				$totalCurrency = $chosenOffer->totalCurrency?$chosenOffer->totalCurrency:'EUR';

				// get supplier
				$supplierObj = $chosenOffer->supplier;
				if ($supplierObj) {
					if ($supplierObj->getMatchedId($idSystem)) {
						$servicesList[$serviceIndex]['chosenOffer']['supplier']['idTina'] = $supplierObj->getMatchedId($idSystem);
					}
					$servicesList[$serviceIndex]['chosenOffer']['supplier']['idSystem'] = $supplierObj->idSystem;
					$servicesList[$serviceIndex]['chosenOffer']['supplier']['name']	= $supplierObj->name;
				}

				$servicesList[$serviceIndex]['chosenOffer']['totalValue'] = 			$chosenOffer->getTotalValue($totalCurrency);
				$servicesList[$serviceIndex]['chosenOffer']['totalCurrency'] = 			$totalCurrency;

				$servicesList[$serviceIndex]['chosenOffer']['servicePrice']['servicePriceTotal'] = 		$chosenOffer->servicePriceTotal;
				$servicesList[$serviceIndex]['chosenOffer']['servicePrice']['servicePriceVat'] = 		$chosenOffer->servicePriceVat;
				$servicesList[$serviceIndex]['chosenOffer']['servicePrice']['servicePriceCurrency'] = 	$chosenOffer->servicePriceCurrency;

				$servicesList[$serviceIndex]['chosenOffer']['commission']['commissionTotal'] = 		$chosenOffer->commissionTotal;
				$servicesList[$serviceIndex]['chosenOffer']['commission']['commissionCurrency'] = 	$chosenOffer->commissionCurrency;
				$servicesList[$serviceIndex]['chosenOffer']['commission']['commissionable'] = 		$chosenOffer->commissionable;

				$servicesList[$serviceIndex]['chosenOffer']['discount']['discountTotal'] = 			$chosenOffer->discountTotal;
				$servicesList[$serviceIndex]['chosenOffer']['discount']['discountCurrency'] = 		$chosenOffer->discountCurrency;

				$servicesList[$serviceIndex]['chosenOffer']['serviceFee']['serviceFeeTotal'] = 		$chosenOffer->serviceFeeTotal;
				$servicesList[$serviceIndex]['chosenOffer']['serviceFee']['serviceFeeCurrency'] = 	$chosenOffer->serviceFeeCurrency;

				$servicesList[$serviceIndex]['chosenOffer']['tax']['taxTotal'] = 					$chosenOffer->taxTotal;
				$servicesList[$serviceIndex]['chosenOffer']['tax']['taxVat'] = 						$chosenOffer->taxVat;
				$servicesList[$serviceIndex]['chosenOffer']['tax']['taxCurrency'] = 				$chosenOffer->taxCurrency;

				$servicesList[$serviceIndex]['chosenOffer']['confirmationNumber'] = 				$chosenOffer->confirmationNumber;
				$servicesList[$serviceIndex]['chosenOffer']['cancellationPolicy'] =					$chosenOffer->cancellationPolicy;
				$servicesList[$serviceIndex]['chosenOffer']['idSystem'] =							$chosenOffer->idSystem;
				$servicesList[$serviceIndex]['chosenOffer']['date']	=								$chosenOffer->date;

				$servicesList[$serviceIndex]['chosenOffer']['supplierProduct'] =					$chosenOffer->supplierProduct->name??null;
				$servicesList[$serviceIndex]['chosenOffer']['formOfPayment'] =						$chosenOffer->formOfPayment;

				// tickets list
				if ($chosenOffer->ticketNumbers) {
					foreach ($chosenOffer->ticketNumbers as $ticketDetails) {
						$servicesList[$serviceIndex]['tickets'][] = [
							'number' => 	$ticketDetails['number'],
							'paxIndex' => 	$this->getPassengerIndex($importedOrder, $ticketDetails['passenger']),
							'date' =>		$chosenOffer->ticketDate,
						];
					}
				}

			}

		}

		return $servicesList;
	}


	/**
	 * Extract process status from service external system id
	 * @param String $idServiceExtSys
	 * @param Array $importedServicesList
	 */
	private function getProcessStatus($idServiceExtSys, $importedServicesList)
	{
		if (array_key_exists($idServiceExtSys, $importedServicesList)) {
			return $importedServicesList[$idServiceExtSys];
		}
		else{
			return false;
		}
	}
}