<?php

namespace App\ImportedOrder;

/**
 * The class contains details about the service type (hotel, ticketing, etc).
 * @author Gabriel
 */
class ServiceType extends EntityAbstract
{

	/**
	 * The service code (from TINA).
	 * @var String
	 */
	public $codeTina;

	/**
	 * The service code (from the external system).
	 * @var String
	 */
	public $codeSystem;

	/**
	 * The service name.
	 * @var String
	 */
	public $name;


	/**
	 * (non-PHPdoc)
	 * @see \App\ImportedOrder\EntityAbstract::validateEntityFields()
	 */
	protected function validateEntityFields(\App\MessagesCollector $messagesCollector): void
	{

		if ($this->codeTina and !\App\Config\Services_Basic::getInstance()->checkService($this->codeTina)) {
			$messagesCollector->addInfo("The service code `{$this->codeTina}` is not valid.");
		}

	}

	/**
	 * Matches the entity by its fields - can also check for matches in the external
	 * systems associations (if $idExternalSystem is set).
	 * @param Int $idExternalSystem - if set, it is attempted to match the user by the manual associations;
	 * @return Int - the entity id, if matched; 0/blank if no entity was matched
	 */
	public function getMatchedId($idExternalSystem)
	{
		$matchedServiceCodeSystem = null;
		// get service code as matched from
		if ($idExternalSystem and $this->codeSystem) {
			$matchedServiceCodeSystem = \App\Config\ImportedOrders_Matches::getInstance()->getServiceType($idExternalSystem, $this->codeSystem);
		}

		$ret = null;

		// if we have both direct and matched codes
		if ($this->codeTina and $matchedServiceCodeSystem) {
			if ($this->codeTina==$matchedServiceCodeSystem) {
				$ret = $this->codeTina;
			}
			else {
				$ret = '';
			}
		}
		// if we have only one of the codes - return it
		elseif ($matchedServiceCodeSystem) {
			$ret = $matchedServiceCodeSystem;
		}
		elseif ($this->codeTina) {
			$ret = $this->codeTina;
		}
		else {
			// this should never happen. It wasn't originally treated at all
//			throw new \Exception("Cannot match serviceType. None of the variables are set.");
		}

		return $ret;
	}
}
