<?php
namespace App\Sabre\Api\Soap\Operation;

/**
 * Create Sabre Profiles Object
 * @see https://developer.sabre.com/docs/soap_apis/profiles/profiles_management/Create_Profile_Objects
 *
 * @author Dan Baluta
 */
class ProfileCreate extends \App\Sabre\Api\Soap\Operation\GeneralAbstract
{
	use Util\CustomerTrait;
	use Util\CorporateTrait;

	protected $Service = 'EPS_EXT_ProfileCreateRQ';

	protected $Action = 'EPS_EXT_ProfileCreateRQ';

	protected $Version = '6.55';

	/**
	 * TVL, CRP
	 * @var string
	 */
	protected $ProfileTypeCode;


	public function __construct($ConversationId, $BinarySecurityToken, $ProfileTypeCode, $DomainID, \App\Entity\GeneralAbstract $entity)
	{
		$this->params = [];
		$this->params['ConversationId'] = $ConversationId;
		$this->params['BinarySecurityToken'] = $BinarySecurityToken;
		$this->params['DomainID'] = $DomainID;
		$this->params['entity']  = $entity;

		$this->params['gdsFields'] = [];
		$fieldsDetails = $entity->gdsProfileTemplate->staticFieldsDetails;
		$fieldsValues = $entity->gdsProfileFieldsValues;
		uasort($fieldsDetails, function($f1, $f2) {		// reorder alphabetically, maintain index
		    return strnatcmp($f1["label"], $f2["label"]);
		});

		foreach ($fieldsDetails as $idField=>$field) {
			if ($field['type']=="static" && array_key_exists($idField, $fieldsValues)) {
				$this->params['gdsFields'][] = [
				    'label' => $fieldsDetails[$idField]['label'],
					'tagSabre' => $fieldsDetails[$idField]['tagSabre'],
					'value' => $fieldsValues[$idField],
				];
			}
		}

		$this->ProfileTypeCode = $ProfileTypeCode;
	}

	protected function getRequestBody()
	{
		// TODO validateRequest()
		if (!$this->params['DomainID']) {
			throw new \Exception\Net\Ws\Client\Base("Sabre PCC is not set up.");
		}

		$Sabre_OTA_ProfileCreateRQ = new \Engine\SimpleXmlElement("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Sabre_OTA_ProfileCreateRQ
			xsi:schemaLocation=\"http://www.sabre.com/eps/schemas \schemas\Sabre_OTA_ProfileCreateRQ.xsd\"
			xmlns=\"http://www.sabre.com/eps/schemas\"
			xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"></Sabre_OTA_ProfileCreateRQ>");

		$Sabre_OTA_ProfileCreateRQ->addAttribute('Version', $this->Version);
		$Sabre_OTA_ProfileCreateRQ->addAttribute('TimeStamp', \Engine\DateTime::create()->format('Y-m-d\TH:i:s.0\Z'));
		$Sabre_OTA_ProfileCreateRQ->addAttribute('Target', 'Production');

		$Profile = $Sabre_OTA_ProfileCreateRQ->addChild('Profile');
		$Profile->addAttribute('CreateDateTime', \Engine\DateTime::create()->format('Y-m-d\TH:i:s.0\Z'));
		$Profile->addAttribute('UpdateDateTime', \Engine\DateTime::create()->format('Y-m-d\TH:i:s.0\Z'));
		$Profile->addAttribute('PrimaryLanguageIDCode', 'EN-US');

		$TPA_Identity = $Profile->addChild('TPA_Identity');
		$TPA_Identity->addAttribute('ClientCode', $this->ClientCode);
		$TPA_Identity->addAttribute('ClientContextCode', $this->ClientContextCode);
		$TPA_Identity->addAttribute('UniqueID', '*');
		$TPA_Identity->addAttribute('ProfileTypeCode', $this->ProfileTypeCode);
		$TPA_Identity->addAttribute('ProfileNameModifyIndicator', 'Y');
		$TPA_Identity->addAttribute('DomainID', $this->params['DomainID']);

		if ($this->ProfileTypeCode=='CRP') {
			$this->populateCorporateProfileFromEntity($Profile, $this->params['entity']);
		}
		elseif ($this->ProfileTypeCode=='TVL') {
			$this->populateCustomerProfileFromEntity($Profile, $this->params['entity']);
		}
		else {
			throw new \Exception("Invalid profile type: ".$this->ProfileTypeCode);
		}

		//debug($Sabre_OTA_ProfileCreateRQ->asPretty()); die;

		/*
		// Validate XML against XSD
		$msgs = \App\MessagesCollector::create();
		$msgs = $Sabre_OTA_ProfileCreateRQ->validateAgainstXsd(__DIR__.'/_xsd/Sabre_OTA_ProfileCreateRQ.xsd', $msgs);
		if ($msgs->hasErrorOrWarning()) {
			throw new \App\MessagesException($msgs);
		}
		*/

		return $Sabre_OTA_ProfileCreateRQ->asStr();
	}


	protected function validateResponse(\Engine\SimpleXmlElement $response)
	{
		if ((String)$response->Body->Sabre_OTA_ProfileCreateRS->ResponseMessage->Errors->ErrorMessage) {
			throw new \Exception\Net\Ws\Client\Base( (String)$response->Body->Sabre_OTA_ProfileCreateRS->ResponseMessage->Errors->ErrorMessage );
		}
	}

}
