<?php
namespace Entity;

class Validator_CorporateContact extends \App\Entity\Utils\Extension_ValidateDefaultAbstract
{

	/**
	 * Validates the fields of the current entity for inserting
	 */
	protected function check_insert()
	{
		// get current fields details
		$fields = $this->entity->getFields();

		// current collected messages
		$currentMessages = $this->entity->getMessages();

		// CREATE STORAGE PATH /////////////////////////////////////////////////////////////////////
		if ($fields['filesWithContent'] or $fields['filesWithPath']) {
			if (!\Engine\Dir::create($this->entity->getFileStorageRoot())) {
				$currentMessages->addErrorCode('insert_contactFilePathErr');
			}
		}

		// CHECK FILES WITH CONTENT ////////////////////////////////////////////////////////////////
		if ($fields['filesWithContent']) {
			foreach ($fields['filesWithContent'] as $fileName => $fileContent) {
				// check if file content is completed
				if ($fileContent === NULL) {
					$currentMessages->addWarningCode('insert_fileContentIncorrect');
				}
				elseif (!$fileName) {
					$currentMessages->addWarningCode('insert_fileNameIncorrect');
				}
				elseif ($fileName != \Engine\File::cleanName($fileName)) {
					$currentMessages->addWarningCode('insert_fileNameInvalid');
				}
			}
		}

		// CHECK FILES WITH PATH ///////////////////////////////////////////////////////////////////
		if ($fields['filesWithPath']) {

			$checkFileName = new \App\Utils\RestrictUploadedFile();
			foreach ($fields['filesWithPath'] as $fileName => $filePath) {
				if (!$filePath) {
					$currentMessages->addWarningCode('insert_filePathIncorrect');
				}
				elseif (!$fileName) {
					$currentMessages->addWarningCode('insert_fileNameIncorrect');
				}
				elseif ($fileName != \Engine\File::cleanName($fileName)) {
					$currentMessages->addWarningCode('insert_fileNameInvalid');
				}
				else {
					try {
						$checkFileName->checkFileName($fileName);
					} catch (\App\MessagesException $e) {
						$currentMessages->addWarningCode('invalidUploadedFileFormat');
					}
				}
			}
		}

		// CHECK IF CORPORATE IS VALID /////////////////////////////////////////////////////////////
		$corporate = \Entity\Corporate::selectForUpdate($fields['idCorporate']);
		if (!$corporate->recordExists()) {
			$currentMessages->addErrorCode('insert_invalidCorpSelected');
		}
		elseif ($corporate->deleted) {
			$currentMessages->addWarningCode('insert_selectedCorpDeleted');
		}

		// CHECK CONTACT PERSON ////////////////////////////////////////////////////////////////////
		if ($fields['idContactPerson']) {
			$contactPerson = \Entity\ContactPerson::selectForUpdate($fields['idContactPerson']);
			if (!$contactPerson->recordExists()) {
				$currentMessages->addErrorCode('insert_invalidContactPersSelected');
			}
			elseif ($contactPerson->deleted) {
				$currentMessages->addWarningCode('insert_selectedContactPersDeleted');
			}
		}

		// CHECK DATE TIME /////////////////////////////////////////////////////////////////////////
		if (array_key_exists('contactDatetime', $fields) && !\Engine\Validator::set($fields['contactDatetime'])->isDatetime()) {
			$currentMessages->addWarningCode('noContactDate', 'contactDatetime');
		}

		// CHECK ID USER ///////////////////////////////////////////////////////////////////////////
		if ($fields['idUser'] and !\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('corporateContactChangeResp') and $fields['idUser'] != CURRENT_ID_USER) {
			$currentMessages->addWarningCode('noAccessToOption');
		}

		// CHECK ID USER IS CORRECT ////////////////////////////////////////////////////////////////
		if ($fields['idUser']) {
			$user = \Entity\User::select($fields['idUser']);

			if (!$user->recordExists()) {
				$currentMessages->addErrorCode('insert_invalidUserSelected');
			}
			elseif ($user->deleted) {
				$currentMessages->addWarningCode('insert_selectedUserDeleted');
			}
		}
	}

	/**
	 * Check if operation update can be done
	 */
	protected function isAvailable_update()
	{
		// current collected messages
		$currentMessages = $this->entity->getMessages();

		$corporateContact = \Entity\CorporateContact::selectForUpdate($this->entity->getId());

		if (!$corporateContact->recordExists()) {
			$currentMessages->addErrorCode('update_idInvalid');
		}
		elseif ($corporateContact->deleted) {
			$currentMessages->addWarningCode('update_idDeleted');
		}
	}

	/**
	 * Validates the fields of the current entity  for updating
	 */
	protected function check_update()
	{
		// get current fields details
		$fields = $this->entity->getFields();

		// current collected messages
		$currentMessages = $this->entity->getMessages();

		// CHECK ID CORPORATE ID //////////////////////////////////////////////////////////////////////
		if (array_key_exists('idCorporate', $fields)) {
			throw new \Exception("The field '{$fields['idCorporate']}' cannot be updated in the `".__CLASS__."` entity.");
		}

		if (array_key_exists('filesWithContent', $fields) or array_key_exists('filesWithPath', $fields)) {
			if (!\Engine\Dir::create($this->entity->getFileStorageRoot())) {
				$currentMessages->addErrorCode('insert_contractFilePathErr');
			}
		}

		// CHECK FILES WITH CONTENT ////////////////////////////////////////////////////////////////
		if (array_key_exists('filesWithContent', $fields)) {
			foreach ($fields['filesWithContent'] as $fileName => $fileContent) {
				// check if file content is completed
				if ($fileContent === NULL) {
					$currentMessages->addWarningCode('insert_fileContentIncorrect');
				}
				elseif (!$fileName) {
					$currentMessages->addWarningCode('insert_fileNameIncorrect');
				}
				elseif ($fileName != \Engine\File::cleanName($fileName)) {
					$currentMessages->addWarningCode('insert_fileNameInvalid');
				}
			}
		}

		// CHECK FILES WITH PATH ///////////////////////////////////////////////////////////////////
		if (array_key_exists('filesWithPath', $fields)) {

			$checkFileName = new \App\Utils\RestrictUploadedFile();
			foreach ($fields['filesWithPath'] as $fileName => $filePath) {
				if (!$filePath) {
					$currentMessages->addWarningCode('insert_filePathIncorrect');
				}
				elseif (!$fileName) {
					$currentMessages->addWarningCode('insert_fileNameIncorrect');
				}
				elseif ($fileName != \Engine\File::cleanName($fileName)) {
					$currentMessages->addWarningCode('insert_fileNameInvalid');
				}
				else {
					try {
						$checkFileName->checkFileName($fileName);
					} catch (\App\MessagesException $e) {
						$currentMessages->addWarningCode('invalidUploadedFileFormat');
					}
				}
			}
		}


		// CHECK CONTACT PERSONS
		if (array_key_exists('idContactPerson', $fields) and $fields['idContactPerson']) {
			$contactPerson = \Entity\ContactPerson::selectForUpdate($fields['idContactPerson']);

			if (!$contactPerson->recordExists()) {
				$currentMessages->addErrorCode('update_invalidContactPersonSelected');
			}
			elseif ($contactPerson->deleted) {
				$currentMessages->addErrorCode('update_selectedContactPersonDeleted');
			}
		}

		// CHECK DATE TIME /////////////////////////////////////////////////////////////////////////
		if (array_key_exists('contactDatetime', $fields) && !\Engine\Validator::set($fields['contactDatetime'])->isDatetime()) {
			$currentMessages->addWarningCode('noContactDate', 'contactDatetime');
		}

		// CHECK ID USER ACCESS TO EDIT IT /////////////////////////////////////////////////////
		if (array_key_exists('idUser', $fields)) {
			if (!\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('corporateContactChangeResp') and $fields['idUser'] != CURRENT_ID_USER) {
				$currentMessages->addWarningCode('noAccessToOption');
			}
		}

		// CHECK ID USER ///////////////////////////////////////////////////////////////////////////
		if (array_key_exists('idUser', $fields)) {
			$user = \Entity\User::select($fields['idUser']);
			if (!$user->recordExists()) {
				$currentMessages->addErrorCode('update_invalidIdUser');
			}
			elseif ($user->deleted) {
				$currentMessages->addWarningCode('update_idUserDeleted');
			}
		}
	}

	/**
	 * Check if operation delete can be done
	 */
	protected function isAvailable_delete()
	{
		// current collected messages
		$currentMessages = $this->entity->getMessages();

		$corporateContact = \Entity\CorporateContact::selectForUpdate($this->entity->getId());

		// check if record exists or is not deleted
		if (!$corporateContact->recordExists()) {
			$currentMessages->addErrorCode('delete_invalidId');
		}
		elseif ($corporateContact->deleted) {
			$currentMessages->addWarningCode('delete_corporateContactDeleted');
		}
	}

}