<?php
namespace App\Amadeus\StructureParser\Structures\Car;

class Price extends \App\Amadeus\StructureParser\Parser\Price
{
	/**
	 * (non-PHPdoc)
	 * @see \App\Amadeus\StructureParser\Parser\Price::passenger()
	 */
	public function passenger()
	{
		if($this->CACHE[__METHOD__]) return $this->CACHE[__METHOD__];

		$parsedStructure = $this->transaction->getParsedStructure();
		$indexType = $this->transaction->getIndexType();
		$index = $this->transaction->getIndex();
		$U = $parsedStructure['U'][$index->segment];

		if($indexType=='U' && $U['_type']=='08'){
			$price = $this->passenger_U_08();
			if($price){
				$price->checkIntegrity($this->transaction);
				$this->CACHE[__METHOD__] = $price;
				return $price;
			}
		}

		if($indexType=='U' && $U['_type']=='09'){
			$price = $this->passenger_U_09();
			if($price){
				$price->checkIntegrity($this->transaction);
				$this->CACHE[__METHOD__] = $price;
				return $price;
			}
		}

		return null;
	}


	/**
	 * Get data from a specific line
	 */
	protected function passenger_U_08()
	{
		$parsedStructure = $this->transaction->getParsedStructure();
		$index = $this->transaction->getIndex();

		$item = new \App\Amadeus\StructureParser\Types\Price();
		$U = $parsedStructure['U'][$index->segment];

		if ($U) {
			$I = $parsedStructure['I'][$index->passenger];
			if (!$item->formOfPayment->hasData()) {
				$item = $this->internal_getFormOfPaymentFromRemarks($parsedStructure, $index, $item, $I, $this->getTransaction()->getServiceDetails()->getRemarks()->getProcessedRemarks());
			}
			if (!$item->formOfPayment->hasData()) {
				$item = $this->internal_getFormOfPaymentFromRIU($parsedStructure, $index, $item);
			}

			if (!$item->formOfPayment->hasData()) {
				$item = $this->internal_getFormOfPayment($parsedStructure, $index, $item, $I);
			}

			// extract supplier price
			$item->componentSet(new \App\Amadeus\StructureParser\Types\PriceComponent(
				'total',
				'U_08:FREE_:totalPrice',
				$U['FREE_']['totalPrice']['value'],
				null,
				$U['FREE_']['totalPrice']['currency']
			));

			$item->componentSet(new \App\Amadeus\StructureParser\Types\PriceComponent(
				'supplier',
				'U_08:total',
				$item->total,
				null,
				$item->totalCurrency
			));

			// if no supplier price or taxes are defined, try to extract them from remarks
			if (!$item->supplier && !$item->tax->getAmount()) {
				$item = $this->internal_passenger_extractSupplierPriceFromRemarks($item);
			}

			// extract serviceFee
			if (in_array(\App\Amadeus\Config::getInstance()->get("importServiceFeeForService"), ['all', ])) {
				$item = $this->internal_extractServiceFee($parsedStructure, $index, $item, $I, [$index->TSA], ['ignore_TFD_line'=>true]);
			}

			// extract discount
			if (in_array(\App\Amadeus\Config::getInstance()->get("importServiceFeeForService"), ['all',  ])) {
				$item = $this->internal_extractDiscount($parsedStructure, $index, $item, $I, [$index->TSA]);
			}

			// extract commission
			if (in_array(\App\Amadeus\Config::getInstance()->get("importCommissionForService"), ['all',  ])) {
				$item = $this->internal_extractCommission($item, $parsedStructure, $index, $I);
			}
		}

		$item = $this->internal_extractVAT($parsedStructure, $index, $item, null, []);

		$item = $this->sanitizePrice($item);

		return $item;
	}

	/**
	 * Get data from a specific line
	 * @throws \App\Amadeus\StructureParser\StructureException
	 */
	protected function passenger_U_09()
	{
		$parsedStructure = $this->transaction->getParsedStructure();
		$index = $this->transaction->getIndex();

		$item = null;
		$U = $parsedStructure['U'][$index->segment];

		if($U){
			$item = new \App\Amadeus\StructureParser\Types\Price();

			$I = $parsedStructure['I'][$index->passenger];
			$item = $this->internal_getFormOfPaymentFromRemarks($parsedStructure, $index, $item, $I, $this->getTransaction()->getServiceDetails()->getRemarks()->getProcessedRemarks());
			if (!$item->formOfPayment->hasData()) {
				$item = $this->internal_getFormOfPayment($parsedStructure, $index, $item, $I);
			}

			// extract supplier price
			if ($U['ESTTLRTE'] && $U['ESTTLRTE']['ESTTLAMT']) {											// @see 2011-01-17_111156_10.193.2.56__M_L_1701_14.AIR , RECLOC: 2OWO9B, client: HU/Morea
				$this->transaction->addLog(__METHOD__.": Using ESTTLRTE[ESTTLAMT] to determine the total price");
				$item->componentSet(new \App\Amadeus\StructureParser\Types\PriceComponent(
					'total',
					'U_09:ESTTLRTE:ESTTLAMT',
					$U['ESTTLRTE']['ESTTLAMT'],
					null,
					$U['ESTTLRTE']['ESCUCDE']
				));
			}
			elseif($U['ESTTLAMT']) {
				$this->transaction->addLog(__METHOD__.": Using ESTTLAMT to determine the total price");
				$item->componentSet(new \App\Amadeus\StructureParser\Types\PriceComponent(
					'total',
					'U_09:ESTTLAMT',
					$U['ESTTLAMT'],
					null,
					$U['ESCUCDE']
				));
			}
			elseif($U['RGOPT_']['dailyRate']) {							// @see RECLOC:Z89HRJ, folder: AIR-testcases, client: RO/AS?
				$this->transaction->addLog(__METHOD__.": Using RGOPT_[dailyRate] to determine the total price");
				$item->componentSet(new \App\Amadeus\StructureParser\Types\PriceComponent(
					'total',
					'U_09:RGOPT_:dailyRate',
					$U['RGOPT_']['dailyRate'] * \App\Amadeus\StructureParser\Helpers::countDays($U['PICKUP'], $U['DROP']),
					null,
					$U['RGOPT_']['dailyCurrency']
				));
			}
			elseif($U['RQOPT_']['format_']=='2.0') {							// @see RECLOC:Z89HRJ, folder: AIR-testcases, client: RO/AS?
				$this->transaction->addLog(__METHOD__.": Using RGQOPT_[dailyRate] to determine the total price");
				$item->componentSet(new \App\Amadeus\StructureParser\Types\PriceComponent(
					'total',
					'U_09:RQOPT_:totalRate',
					$U['RQOPT_']['totalRate'],
					null,
					$U['RQOPT_']['totalCurrency']
				));
			}
			elseif($U['RQOPT_']['format_']=='1.0') {							// @see RECLOC:Z89HRJ, folder: AIR-testcases, client: RO/AS?
				$this->transaction->addLog(__METHOD__.": Using RGQOPT_[dailyRate] to determine the total price");
				$item->componentSet(new \App\Amadeus\StructureParser\Types\PriceComponent(
					'total',
					'U_09:RQOPT_:dailyRate',
					$U['RQOPT_']['dailyRate'] * \App\Amadeus\StructureParser\Helpers::countDays($U['PICKUP'], $U['DROP']),
					null,
					$U['RQOPT_']['dailyCurrency']
				));
			}

			// extract taxes
			if ($U['TAXINFO']['TAXINCLU']=='N') {		// tax NOT included, add it to the total price
				if ($U['TAXINFO']['TAXPCENT']=='PERCENT') {		// percent
					$this->transaction->addLog(__METHOD__.": Tax not included in the total price ({$U['TAXINFO']['TAXVALUE']}%)");
					$item->tax->insert(new \App\Amadeus\StructureParser\Types\PriceTaxComponent($U['TAXINFO']['TAXVALUE']*$item->total/100, $item->totalCurrency, 'car:notIncluded'));
				}
				else {											// fixed amount
					$this->transaction->addLog(__METHOD__.": Tax not included in the total price ({$U['TAXINFO']['TAXVALUE']} {$item->totalCurrency})");
					$item->tax->insert(new \App\Amadeus\StructureParser\Types\PriceTaxComponent($U['TAXINFO']['TAXVALUE'], $item->totalCurrency, 'car:notIncluded'));
				}
			}
			elseif($U['TAXINFO']['TAXINCLU']=='I') {		// tax included, substract it from the total price
				/**
				 * I'm not sure in understood correctly, but it seems that TAXPCENT is always 'TAXPCENT', and so we should ignore paercent taxes, and assume all taxes as fixed values
				 * @see MAIL:[AMA] Car, U-CCR
				 */
				$this->transaction->addLog(__METHOD__.": Tax included in the total price ({$U['TAXINFO']['TAXVALUE']} {$item->totalCurrency})");
				$item->tax->insert(new \App\Amadeus\StructureParser\Types\PriceTaxComponent($U['TAXINFO']['TAXVALUE'], $item->totalCurrency, 'car:notIncluded'));
			}
			else {
				throw new \App\Amadeus\StructureParser\StructureException("Unknown value for the TAXINCLU tag");
			}

			$item->componentSet(new \App\Amadeus\StructureParser\Types\PriceComponent(
				'supplier',
				'U_09:total-tax',
				$item->total - $item->tax->getAmount(),
				null,
				$item->totalCurrency
			));


			// if no supplier price or taxes are defined, try to extract them from remarks
			if (!$item->supplier && !$item->tax->getAmount()) {
				$item = $this->internal_passenger_extractSupplierPriceFromRemarks($item);
			}

			// TODO: SURCINFO should be added or substracted to the supplier price?
		}

		$item = $this->internal_extractVAT($parsedStructure, $index, $item, null, []);

		// extract serviceFee
		if (in_array(\App\Amadeus\Config::getInstance()->get("importServiceFeeForService"), ['all', ])) {
			$item = $this->internal_extractServiceFee($parsedStructure, $index, $item, $I, [$index->TSA], ['ignore_TFD_line'=>true]);
		}

		// extract discount
		if (in_array(\App\Amadeus\Config::getInstance()->get("importServiceFeeForService"), ['all',  ])) {
			$item = $this->internal_extractDiscount($parsedStructure, $index, $item, $I, [$index->TSA]);
		}

		// extract commission
		if (in_array(\App\Amadeus\Config::getInstance()->get("importCommissionForService"), ['all',  ])) {
			$item = $this->internal_extractCommission($item, $parsedStructure, $index, $I);
		}

		$item = $this->sanitizePrice($item);

		return $item;
	}
}
