<?php
namespace App\Smarty\Functions;

/**
 * This label works on mvc listing
 *
 * Display supplier details in various ways.
 * The parameter 'ref' is mandatory and it represents the supplier id or an Supplier 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 Supplier object after instantiation.
 * The parameter 'format' represents the format of the function output - this may include HTML format and some variables.
 * Available variables: %alias%, %company%, %companyFull%.
 */
class SupplierLabel
{

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

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

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

		// CHECK OUTPUT FORMAT --------------------------------------------------------------------
		if (!$params['format']) {

			$display = '';
			if ($supp->alias) {
				$display = $supp->alias;
			}

			if (!$display) {
				$display = $defaultOutput;
			}
			// check if the user has access to the remote details option
			if (\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('Modules/Partners/Suppliers-remoteDetails') && !$params['hideLink']) {
				return sprintf("<span class=\"remoteLoadLink\" onclick=\"RemoteLoad.load(this, MVC.appUrl('RemoteData/InfoBox', '%s', { 'id': '%s'}), null); return false;\">%s</span>",
					'supplier',
					$supp->getId(),
					$display);
			}
			else {
				return $display;
			}

		}
		else {
			$replaceArray = [];
			$replaceArray['%alias%']=$supp->alias;
			$replaceArray['%company%']=$supp->company;
			$replaceArray['%companyFull%']=trim($supp->companyPrefix.' '.$supp->company.' '.$supp->companySuffix);

			return str_replace(array_keys($replaceArray), array_values($replaceArray), $params['format']);
		}
	}

}