<?php

namespace Entity;

// TODO: vezi smarty label function - replace "get_class($params['ref'])=='[class_name]'" with get_class($params['ref'])=='Entity\[class_name]'
// TODO: rename idOffice with idCorporateOffice

// TODO: should be broken down into two sections: for corporate and for supplier + one abstract class (the difference is the corporate office validation and saving); should be two tables in db; also check matching of contact persons

class ContactPerson extends \App\Entity\GeneralAbstract
{

	/**
	 * Indicate if the operations available for the current entity must be done inside a transaction or not.
	 * @var Boolean
	 */
	protected $saveInsideTransaction = true;

	protected $addAndUpdateDateTimeFormat = 'timestamp'; // TODO: to be eliminated after the table columns are renamed and replaced with datetime


	/**
	 * (non-PHPdoc)
	 * @see App\Entity.SelectAbstract::setTableName()
	 */
	protected function setTableName(): void
	{
		global $DBTContactPersons;
		$this->tableName = $DBTContactPersons;
	}

	/**
	 * (non-PHPdoc)
	 * @see App\Entity.SelectAbstract::getAttribute()
	 */
	protected function getAttribute($var)
	{

		// CHECK EVERY POSSIBLE VALUES THAT $var MAY HAVE -----------------------------------------
		switch ($var) {
			// name
			case 'name': {
				if (!isset($this->fields[$var])){
					$this->fields[$var] = \App\Smarty\Functions\NameFormat::renderStr((string)$this->fields['firstName'], (string)$this->fields['lastName']);
				}
				return $this->fields[$var];
			}

			// typeName (not cached)
			case 'typeName': {
				global $_LANG;
				return $_LANG['generalData']['companyType'][$this->fields['type']];
			}

			// title code
			case 'titleCode': {
				if (!isset($this->fields['titleCode'])) $this->fields['titleCode'] = $this->fields['title'];
				return $this->fields['titleCode'];
			}

			// title name(translated) (not cached)
			case 'titleName': {
				global $_LANG;
				return $_LANG['generalData']['personTitles'][$this->fields['title']];
			}

			// role name (translation) (not cached)
			case 'roleName': {
				if ($this->fields['role']) {
					global $_LANG;
					return $_LANG['generalData']['contactPersonsRoles'][$this->fields['role']];
				}
				else {
					return '';
				}
			}

			// company
			case 'company': {
				if ($this->fields['type'] == 'supplier') {
					return \Entity\Supplier::select($this->fields['idCompany'], $this->selectForUpdate);
				}
				else {
					return \Entity\Corporate::select($this->fields['idCompany'], $this->selectForUpdate);
				}
			}

			// corporate office
			case 'corporateOffice': {
				return \Entity\CorporateOffice::select($this->fields['idOffice'], $this->selectForUpdate);
			}

			// processed remarks
			case 'processedRemarks': {
				if (!is_array($this->fields['processedRemarks'])){
					$rm = new \App\Entity\Utils\Remarks_ContactPerson($this->id);
					$this->fields[$var] = $rm->getAll();
				}
				return $this->fields['processedRemarks'];
			}

			// addUser
			case 'addUser': {
				return User::select($this->fields['idAddUser'], $this->selectForUpdate);
			}

			// updateUser
			case 'updateUser': {
				return User::select($this->fields['idUpdateUser'], $this->selectForUpdate);
			}

			// the rest of the fields (most of them are just copied)
			default: {
				return parent::getAttribute($var);
			}

		}
	}

	/**
	 * (non-PHPdoc)
	 * @see App\Entity.GeneralAbstract::setAttribute()
	 */
	protected function setAttribute($var, $value)
	{
		// check that operation is okay
		if ($this->operation != 'insert' and $this->operation != 'update') {
			throw new \Exception('You can use __set magic method only with insert/update operation in `'.__CLASS__.'` class.');
		}

		// CHECK EACH POSSIBLE FIELD VALUE --------------------------------------------------------
		switch ($var) {

			// simple fields
			case 'title': case 'firstName': case 'lastName':
			case 'birthday': case 'idOffice': case 'department': case 'job': case 'role':
			case 'email': case 'telephone': case 'telephoneMobile': case 'fax': case 'comments':
			case '_exportToGds': {
				$this->fields[$var] = $value;
				break;
			}

			// type and idCompany
			case 'type': case 'idCompany': {
				if ($this->operation == 'update') {
					throw new \Exception('Cannot __set `type` and `idCompany` for contact persons update operation.');
				}
				else {
					$this->fields[$var] = $value;
				}
				break;
			}

			// remarks
			case 'remarks': {
				$this->fields['remarks'] = $value;
				$this->fields['processedRemarks'] = \App\Config\Remarks::process($value, 'contactPerson');
				break;
			}

			// the field is not valid
			default: {
				throw new \Exception("The field '$var' is not valid for the `".__CLASS__."` entity.");
			}
		}
	}

	/**
	 * (non-PHPdoc)
	 * @see App\Entity.GeneralAbstract::save_filterSaveData()
	 */
	protected function save_filterSaveData(Array $saveData)
	{
		unset($saveData['_exportToGds']);

		if (array_key_exists('remarks', $saveData)) {
			$saveData['processedRemarks'] = $this->getSerializedProcessedRemarks();
		}

		return $saveData;
	}

	/**
	 * {@inheritDoc}
	 * @see \App\Entity\GeneralAbstract::save_postProcess()
	 */
	protected function save_postProcess(Array $saveData)
	{
		// SAVE REMARKS FOR THIS CONTACT PERSON //////////////////////////////////////////////////
		if (($this->operation == 'insert' or $this->operation == 'update') and array_key_exists('remarks', $this->fields)) {
			try {
				$remarks = new \App\Entity\Utils\Remarks_ContactPerson($this->id);
				$remarks->save($this->fields['remarks']);
			} catch (\App\Entity\UtilsException $ex) {
				$this->messages->removeSuccess();
				$this->messages->addErrorCode('remarksSaveFail');
			}
		}
	}

	protected function save_finishOperation()
	{
		parent::save_finishOperation();

		// insert in GDS profiles queue to be exported
		if (in_array($this->operation, ['insert', 'update', 'delete', ])) {
			if ($this->fields['_exportToGds']) {
				$persEnt = self::selectForUpdate($this->id);
				if ($persEnt->type == 'corporate' && $persEnt->company->idGdsProfileTemplate) {
					$queueManager = \App\GdsProfile\QueueManager::getInstance();
					$queueManager->insertRow('corporate', $persEnt->idCompany);
				}
			}
		}
	}

}