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

class ServiceDetails extends \App\Amadeus\StructureParser\Parser\ServiceDetails
{
	public function getRelations()
	{
		$index = 		$this->transaction->getIndex();

		if ($index and $index->distribuiteTransaction) {
			$details = $this->getRelations_RFD_distribuited();
			if($details){
				return $details;
			}
		}

		$details = $this->getRelations_RFD();
		if($details){
			return $details;
		}
	}

	/**
	 * Get the list of related documents, distribuited over all the related parents
	 * @return \App\Amadeus\StructureParser\Types\Relations
	 */
	protected function getRelations_RFD_distribuited()
	{
		$index = 	$this->transaction->getIndex();

		// $relations = $this->getRelations_RFD();
		$relations = new \App\Amadeus\StructureParser\Types\Relations();
		$rel = new \App\Amadeus\StructureParser\Types\Relation();

		$reference = \Entity\AmadeusService::select($index->referenceTransaction);
		if ($reference->recordExists()) {
			$rel->docNumber = 	$reference->docNumber;
			$rel->docDate = 	$reference->docDate;
			$rel->relationType = 'refund';
			$relations->relations[] = $rel;
		}

		return $relations;
	}

	/**
	 * Get the list of documents
	 * @return \App\Amadeus\StructureParser\Types\Relations
	 */
	protected function getRelations_RFD()
	{
		$parsedStructure = 	$this->transaction->getParsedStructure();
		if(count($parsedStructure['I'])>1){
			$this->transaction->addLog(__METHOD__.": This reservation has more than one passenger, picking the first one as 'owner'");
		}

		$I = $parsedStructure['I'][0];

		$relations = new \App\Amadeus\StructureParser\Types\Relations();

		if($I['T']['TKTNBR_']){
			foreach($I['T']['TKTNBR_'] as $TKT){
				$rel = new \App\Amadeus\StructureParser\Types\Relation();
				$rel->docNumber = 	$TKT;
				$rel->docDate = 	$parsedStructure['RFD']['DOCDATE'];
				$rel->relationType = 'refund';
				$relations->relations[] = $rel;

			}
		}elseif($I['R']['RFDDATE']){
			$rel = new \App\Amadeus\StructureParser\Types\Relation();
			$rel->docNumber = 	$I['R']['RFDNBR_TKTNBR'];
			$rel->docDate = 	$parsedStructure['RFD']['DOCDATE'];
			$rel->relationType = 'refund';
			$relations->relations[] = $rel;
		}

		return $relations;
	}
}
