<?php
namespace Entity;

class GdsProfileTemplate 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;


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


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

		// CHECK EVERY POSSIBLE VALUES THAT $var MAY HAVE -----------------------------------------
		switch ($var) {

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

			case 'fieldsDetails':
			case 'staticFieldsDetails':
			case 'dynamicFieldsDetails': {
				if (!$this->fields[$var]) {
					global $DBTGdsProfileFields, $DBTGdsProfileTemplatesFields;
					$db = \DB::getInstance();

					$sql = "
						SELECT f.id, f.category, f.label, f.description, f.type, f.inputType,
							f.possibleValues, f.validator, f.remarkVar, f.tagSabre, tf.mandatory
						FROM `{$DBTGdsProfileTemplatesFields}` AS tf
							INNER JOIN `{$DBTGdsProfileFields}` AS f ON tf.idProfileField=f.id
						WHERE tf.idProfileTemplate=?
							AND f.deleted=0
					";

					$fieldsDetails = $db->GetAssoc($sql, [$this->id]);
					if ($db->ErrorNo()) {
						throw new \DBException('SQL error while getting some GDS profile templates.');
					}

					foreach ($fieldsDetails as $idField=>$fieldDet) {
						$possibleValues = unserialize($fieldDet['possibleValues']);
						$validator 		= unserialize($fieldDet['validator']);

						$fieldsDetails[$idField]['possibleValues'] = ($possibleValues?:null);
						$fieldsDetails[$idField]['validator'] = ($validator?:null);
					}

					$this->fields['fieldsDetails'] = $fieldsDetails;
					$this->fields['staticFieldsDetails'] = array_filter(array_map(function($elm) {
						if ($elm['type']=='static') { return $elm; }
					}, $fieldsDetails));
					$this->fields['dynamicFieldsDetails'] = array_filter(array_map(function($elm) {
						if ($elm['type']=='dynamic') { return $elm; }
					}, $fieldsDetails));

				}
				return $this->fields[$var];
			}

			// 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 call '.__METHOD__.' only for insert/update operations.');
		}

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

			case 'category':
				if ($this->operation != 'insert') {
					throw new \Exception("The field `{$var}` can only be set for insert operation");
				}
				$this->fields[$var] = $value;
			break;

			case 'name': {
				$this->fields[$var]=$value;
				break;
			}

			case 'templateFields':
				if (!is_array($value)) {
					throw new \Exception('Profiles fields list can only be an array');
				}
				$this->fields[$var] = $value;
			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['templateFields']);

		return $saveData;
	}


	/**
	 * {@inheritDoc}
	 * @see \App\Entity\GeneralAbstract::save_postProcess()
	 */
	protected function save_postProcess(Array $saveData)
	{
		global $DBTGdsProfileTemplatesFields;

		// save template fields
		if ( $this->operation=='insert' or $this->operation=='delete' or ($this->operation=='update' && $this->fields['templateFields']) ) {

			// delete existing fields
			if (in_array($this->operation, ['delete', 'update'])) {
				$this->save_executeSql_delete($DBTGdsProfileTemplatesFields, 'idProfileTemplate', $this->id);
			}

			// associate new fields
			if (in_array($this->operation, ['insert', 'update'])) {
				foreach ($this->fields['templateFields'] as $idField=>$fieldDet) {
					$this->save_executeSql_insert($DBTGdsProfileTemplatesFields, ['idProfileTemplate'=>$this->id, 'idProfileField'=>$idField, 'mandatory'=>$fieldDet['mandatory']]);
				}
			}

		}

	}

}

