<?php
namespace App\Smarty\Functions;

/**
 * Display invoice details in various ways.
 * The parameter 'ref' is mandatory and it represents the invoice id or an Invoice instantiation object.
 * The 'default' parameter indicates what the function will output in case no data is retrieved.
 * The parameter 'assign' represents the variable that will store the Invoice object after instantiation.
 * The parameter 'format' represents the format of the function output - this may include HTML format and some variables.
 * The parameter 'hideLink' indicates that the entity will not display a link for the entityRemoteDetails.
 * Available variables:
 */
class ImportedServiceLabel
{

	/**
	 * @param Array $params
	 * @return String
	 */
	static public function create($params, $smarty)
	{
		// CHECK INPUT ----------------------------------------------------------------------------
		$defaultOutput = '';
		if ($params['default']) {
			$defaultOutput = $params['default'];
		}

		// GET INVOICE DETAILS --------------------------------------------------------------------
		// Invoice object reference
		if (is_object($params['ref']) and get_class($params['ref'])=='Entity\ImportedService') {
			$service = $params['ref'];
		}
		// invoice id
		elseif ( is_numeric($params['ref']) and $params['ref']>0 ) {
			$service = \Entity\ImportedService::select($params['ref']);
			if (!$service->recordExists()) {
				return $defaultOutput;
			}
		}
		// something invalid
		else {
			return $defaultOutput;
		}

		// STORE INVOICE DETAILS IN AN OUTPUT PARAMETER ($params['assign']) -----------------------
		if ($params['assign']) {
			$smarty->assign($params['assign'], $service);
			return '';
		}

		// CHECK OUTPUT FORMAT --------------------------------------------------------------------
		if (!$params['format']) {
			if ($params['hideLink'])
				return ($service->getId()?sprintf("#%s", $service->getId()):$defaultOutput);
			else {
				return sprintf("<span class=\"remoteLoadLink\" onclick=\"RemoteLoad.loadEntity(this, '%s', '%s');\">%s</span>",
					'importedService',
					$service->getId(),
					($service->getId()?sprintf("#%s", $service->getId()):$defaultOutput));
			}


		}
		else {
			$replaceArray = [];
			$replaceArray['%idServiceExtSys%'] = $service->idServiceExtSys;
			$replaceArray['%offerConfirmationNumber%'] = $service->offerConfirmationNumber;
			$replaceArray['%offerExternalSystemReservationId%'] = $service->offerExternalSystemReservationId;
			$replaceArray['%offerExternalSystemReservationDate%'] = $service->offerExternalSystemReservationDate;
			return str_replace(array_keys($replaceArray), array_values($replaceArray), $params['format']);
		}
	}

}