<?php
namespace App\Smarty\Functions;

/**
 * Display department details in various ways.
 * The parameter 'ref' is mandatory and it represents the department id or an Department 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 Department object after instantiation.
 * The parameter 'format' represents the format of the function output - this may include HTML format and some variables.
 * Available variables: %name%, %code%.
 */
class DepartmentLabel
{

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

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

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

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

		// CHECK OUTPUT FORMAT --------------------------------------------------------------------
		if (!$params['format']) {
			return $department->name ? $department->name : $defaultOutput;
		}
		else {
			$replaceArray = [];
			$replaceArray['%name%'] = $department->name;
			$replaceArray['%code%'] = $department->code;

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

}