<?php
namespace App\Smarty\Functions;

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

	static public function create($params, $smarty)
	{

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

		// GET BANK ACCOUNT DETAILS --------------------------------------------------------------------
		// AgencyBankAcount object reference
		if (is_object($params['ref']) and get_class($params['ref'])=='Entity\AgencyBankAcount') {
			$bankAccount = $params['ref'];
		}
		// bank account id
		elseif ( is_numeric($params['ref']) and $params['ref']>0 ) {
			$bankAccount = \Entity\AgencyBankAccount::select($params['ref']);
			if (!$bankAccount->recordExists()) {
				return $defaultOutput;
			}
		}
		// something invalid
		else {
			return $defaultOutput;
		}

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

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

			$display = $bankAccount->account;

			if (!$display) {
				$display = $defaultOutput;
			}

			if ($params['hideLink']) {
				return $display;
			} else {
				//return "<span class=\"remoteLoadLink\" onclick=\"RemoteLoad.loadEntity(this, 'bankAccount', '{$bankAccount->getId()}');\">".$display."</span>";
				return $display;
			}

		}
		else {
			$replaceArray = [];
			$replaceArray['%account%']		= $bankAccount->account;
			if (strpos($params['format'], '%bankName%')!==false) {
				$replaceArray['%bankName%'] = $bankAccount->bank->name;
			}

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