<?php
namespace App\Amadeus\FileParser;

class Line_AB extends \App\Amadeus\FileParser\LineAbstract
{
	/**
	 * 4.149. AB Client Billing Address
	 * see page 367(409)
	 *
	 * DETAILS
	 */
	protected $structure = [
		[ 'name'=> 'MSGTAG',  'val' => 'AB',    'type' => 'AN',      'req' => 'M',  'len' => 2,],  // 1 : Message Tag (AB)
		[ 'name'=> 'BILLADDR',                  'type' => 'AN',      'req' => 'M',],               // 2 : Client Billing Address
		[ 'name'=> 'PSGASS',  'val' => ';P',    'type' => 'ASSOC',                ],
	];

	/**
	 * (non-PHPdoc)
	 * @see \App\Amadeus\FileParser\LineAbstract::isValid()
	 */
	public function isValid()
	{
		// use ['MSGTAG'] constant value to validate the whole line
		if (strpos($this->content, 'AB')===0 && strpos($this->content, 'ABS;')===false) {
			return $this;
		}

		return false;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Amadeus\FileParser\LineAbstract::handler_LineNotCompletlyProcessed()
	 */
	protected function handler_LineNotCompletlyProcessed($index, $content, $structIndex, $contentLength, $tree)
	{
		return $tree;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Amadeus\FileParser\LineAbstract::postParse()
	 */
	protected function postParse()
	{
		parent::postParse();

		if ($this->tree['BILLADDR']) {
			/**
			 * Ex: A1-STR.TIPOGRAFILOR NR11-15/CI-BUCURESTI
			 * Ex: AB A1-STR VULTURULUI 34/A2-COD POSTAL 440268 SATU MARE
			 *
			 * Remarks format taken from DAMA:1019(importing billing address from AMADEUS via new line (AB))
			 */
			$m = [];
			preg_match("/^[\s]*".
					"(CY-(?P<corporate>[^\/]*)(\/)?)?".
					"(NA-(?P<clientName>[^\/]*)(\/)?)?".
					"(A1-(?P<address>[^\/]*)(\/)?)?".
					"(A2-(?P<address2>[^\/]*)(\/)?)?".
					"(ZP-(?P<zipCode>[^\/]*)(\/)?)?".
					"(CI-(?P<city>[^\/]*)(\/)?)?".
					"(ST-(?P<state>[^\/]*)(\/)?)?".
					"(CO-(?P<country>[^\/]*)(\/)?)?".
					"$/i", $this->tree['BILLADDR'], $m);

			if ($m) {
				$this->tree['corporate'] = 	trim(($m['corporate']?:''));
				$this->tree['clientName'] = trim(($m['clientName']?:''));
				if ($m['address2']) {
					// cleanup the address field
					$repl = [
						'/[\s]*,[\s]*$/',
						'/^[\s]+/',
						'/[\s]+$/',
						'/[\s]{2,}/',
					];

					$this->tree['address'] = 	sprintf("%s, %s",
							preg_replace($repl, "", ($m['address']?:'')),
							preg_replace($repl, "", ($m['address2']?:'')) );
				}
				else {
					$this->tree['address'] = 	trim($m['address']??'');
				}
				$this->tree['zipCode'] = 	trim(($m['zipCode']?:''));
				$this->tree['city'] = 		trim(($m['city']?:''));
				$this->tree['state'] = 		trim(($m['state']?:''));
				$this->tree['country'] = 	trim(($m['country']?:''));
			}
			else {
				$this->tree['address'] = 	trim($this->tree['BILLADDR']);
			}
		}
	}
}
