<?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: %id%, %invoiceNumber%.
 *
 */
class InvoiceLabel
{

	/**
	 * @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\Invoice') {
			$invoice = $params['ref'];
		}
		// invoice id
		elseif ( is_numeric($params['ref']) and $params['ref']>0 ) {
			$invoice = \Entity\Invoice::select($params['ref']);
			if (!$invoice->recordExists()) {
				return $defaultOutput;
			}
		}
		// something invalid
		else {
			return $defaultOutput;
		}

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

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

		}
		else {
			$replaceArray = [];
			$replaceArray['%id%']=$invoice->getId();
			$replaceArray['%invoiceNumber%']=$invoice->invoiceNumber;
			$replaceArray['%invoiceDateStd%']=\Engine\DateTime::isoToStd($invoice->invoiceDate);

			if ($params['hideLink'])
				return str_replace(array_keys($replaceArray), array_values($replaceArray), $params['format']);
			else {
				$defaultOutput = str_replace(array_keys($replaceArray), array_values($replaceArray), $params['format']);
				return sprintf("<span class=\"remoteLoadLink\" onclick=\"RemoteLoad.loadEntity(this, '%s', '%s');\">%s</span>",
					'invoice',
					$invoice->getId(),
					$defaultOutput);
			}
		}
	}

}