<?php
namespace App\Smarty\Functions;

/**
 * This label works on mvc listing
 * @author dcs
 *
 */
class SupplierInvoiceLabel
{

	/**
	 *
	 * @param Array $params
	 * @return String
	 */
	static public function create($params, $smarty)
	{

		// CHECK INPUT ----------------------------------------------------------------------------
		$defaultOutput = '';
		if ($params['default']) {
			$defaultOutput = $params['default'];
		}

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

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

		// CHECK OUTPUT FORMAT --------------------------------------------------------------------
		$title = "#".$suppInv->getId();

		if (!$params['format']) {
			return sprintf("<span class=\"remoteLoadLink\" onclick=\"RemoteLoad.loadEntity(this, '%s', '%s')\">%s</span>",
				'supplierInvoice',
				$suppInv->getId(),
				$title);
		}
		else {
			$replaceArray = [
				'%invoiceNumber%'	=> $suppInv->invoiceNumber,
				'%invoiceDate%' 	=> $suppInv->invoiceDate,
				'%invoiceDateStd%'	=> \Engine\DateTime::isoToStd($suppInv->invoiceDate),
			];

			$defaultOutput =  str_replace(array_keys($replaceArray), array_values($replaceArray), $params['format']);

			return sprintf("<span class=\"remoteLoadLink\" onclick=\"RemoteLoad.loadEntity(this, '%s', '%s');\">%s</span>",
				'supplierInvoice',
				$suppInv->getId(),
				$defaultOutput);
		}
	}

}