<?php
namespace App\Sabre\StructureParser\Structures\Train;

class Price extends \App\Sabre\StructureParser\Structures\Base\Price
{
	protected function _getData()
	{
		list($parsedStructure, $transactionType, $transactionIndexes, $internalAssociations) = $this->getTransactionDetails();

		$item = new \App\Sabre\StructureParser\Types\Price();

		$M3 = $parsedStructure['M3'][$transactionIndexes['km3']];

		list(, , $M5s, , $M2, , , ) = $this->determineM5M2($parsedStructure, $transactionType, $transactionIndexes, $internalAssociations);

		$currency = $this->determineCurrency($parsedStructure, $M5s, $M2, [], [$M3, ]);

		$item = $this->determineFormOfPayments($item, $M5s, $M2, [], $currency);

		if ($M5s) {
			$totalPassengers = count($this->transaction->passengers->passengers);
			$item->componentAddAndUpdateTotal(new \App\Utils\BaseParser\Structure\StructureParser\Types\PriceComponent(
				'supplier',
				'M5:baseFareAmount-commissionValue_',
				array_sum(array_map(function($M5) use ($totalPassengers) {
					$amount = $M5['baseFareAmount'] - $M5['commissionValue_'];
					if ($M5['priceType']=='PER') {
						return $totalPassengers * $amount;
					}
					return $amount;
				}, $M5s)),
				null,
				$currency
			));

			$commissionValue = array_sum(array_map(function($M5) use ($totalPassengers) {
				$amount = $M5['commissionValue_'];
				if ($M5['priceType']=='PER') {
					return $totalPassengers * $amount;
				}

				return $amount;
			}, $M5s));
			if ($commissionValue) {
				$item->componentAddAndUpdateTotal(new \App\Utils\BaseParser\Structure\StructureParser\Types\PriceComponent(
					'commission',
					'M5:commissionValue_',
					$commissionValue,
					null,
					$currency
				));
			}
		}

		$item = $this->internal_extract_serviceFee($item);
		$item = $this->internal_extract_discount($item);
		if (in_array(\App\Sabre\Config::getInstance()->get("importCommissionForService"), ['all', ])) {
			$item = $this->internal_extract_commission($item, $M5s, $M2);
		}

		return $item;
	}
}
