<?php
namespace Entity;

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

	/**
	 * Check insert action
	 */
	protected function check_insert()
	{
		// get current fields details
		$fields = $this->entity->getFields();

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

		// get global cfg
		$CFG = \Engine\Loader_Cfg::getInstance()->getGlobal();

		// CHECK THAT SELECTED OFFICE IS THE SAME AS THE ONE FROM SESSION /////////////////////////
		if (!\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('cashBookManDocsAnyOffice')) {
			if ($fields['idOffice'] != CURRENT_ID_OFFICE) {
				$currentMessages->addWarningCode('insert_onlyOwnOffice', 'idUser');
			}
		}

		// ID OFFICE
		if ($fields['idOffice']) {
			$office = \Entity\Office::select($fields['idOffice']);

			if (!$office->recordExists() or $office->deleted) {
				$currentMessages->addWarningCode('officeIdInvalid', 'idUser');
			}
		}

		// ID USER
		if ($fields['idUser']) {
			$user = \Entity\User::select($fields['idUser']);
			if (!$user->recordExists() or $user->deleted) {
				$currentMessages->addWarningCode('userIdInvalid', 'idUser');
			}
			elseif ($user->idOffice != $fields['idOffice']) {
				$currentMessages->addWarningCode('insert_responsibleUserBadOffice', 'idUser');
			}
		}

		// CHECK THAT TYPE IS CORRECT /////////////////////////////////////////////////////////////
		if ($fields['category'] and $fields['type']) {
			if (!$CFG['cashBook']['documentTypes'][$fields['category']][$fields['type']]['active']) {
				$currentMessages->addWarningCode('docTypeInvalid', 'type');
			}
		}

		// AGENCY BANK ACCOUNT ////////////////////////////////////////////////////////////////////
		if ($fields['idAgencyBankAcount']) {
			$ba = \Entity\AgencyBankAccount::select($fields['idAgencyBankAcount']);
			if (!$ba->recordExists()) {
				$currentMessages->addErrorCode('invalidAgencyBankAccId', 'idAgencyBankAcount');
			} elseif ($ba->deleted) {
				$currentMessages->addWarningCode('agencyBankAccDeleted', 'idAgencyBankAcount');
			}
		}

		// CHECK THAT DOCUMENT DATE IS AFTER LAST CLOSE DATE ///////////////////////////////////////
		if ($fields['idOffice'] and $fields['date']) {
			$lastCloseDate = \Cashbook::getLastClosedBalanceDate($fields['idOffice']);
			if ($lastCloseDate and $fields['date'] <= $lastCloseDate) {
				$currentMessages->addWarningCode('docDateAfterLastCloseDate', 'date', $lastCloseDate);
			}
		}

	}

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

		// current entity id
		$currentEntityId = $this->entity->getId();

		// lock records(if it is the case)
		$cashBookDocument = \Entity\CashBookDocument::selectForUpdate($currentEntityId);

		if (!$cashBookDocument->recordExists()) {
			$currentMessages->addErrorCode('update_invalidId');
		}
		elseif ($cashBookDocument->deleted) {
			$currentMessages->addWarningCode('update_deleted');
		}
		elseif ($cashBookDocument->blockTime) {
			$currentMessages->addWarningCode('delete_cantDeleteBlockedDoc');
		}
	}

	/**
	 * Check fields for update
	 */
	protected function check_update()
	{
		// get current fields details
		$fields = $this->entity->getFields();

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

		// config
		$CFG = \Engine\Loader_Cfg::getInstance()->getGlobal();

		$cashBookDocument = \Entity\CashBookDocument::selectForUpdate($this->entity->getId());

		// if document is issued, you can only update "extraInfo"
		if ($cashBookDocument->issueTime) {
			foreach($fields as $fld=>$val) {
				if ($fld!='extraInfo') {
					$currentMessages->addErrorCode('update_issuedDocIsLimited');
				}
			}
		}

		// CHECK THAT USER AND OFFICE ARE CORRECTLY LINKED /////////////////////////////////////////
		if (!\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('cashBookManDocsAnyOffice') and $cashBookDocument->idOffice != CURRENT_ID_OFFICE) {
			$currentMessages->addWarningCode('update_responsibleOffNotCurrOff', 'idUser');
		}

		// CHECK THAT 'idUser' IS VALID
		if ($fields['idUser']) {
			$user = \Entity\User::selectForUpdate($fields['idUser']);
			if (!$user->recordExists() or $user->deleted) {
				$currentMessages->addWarningCode('userIdInvalid', 'idUser');
			} elseif ($user->idOffice != $cashBookDocument->idOffice) {
				$currentMessages->addWarningCode('update_responsibleUserBadOffice', 'idUser');
			}
		}

		// CHECK THAT TYPE IS CORRECT
		if ($fields['type']) {
			if (!$CFG['cashBook']['documentTypes'][$cashBookDocument->category][$fields['type']]['active']) {
				$currentMessages->addWarningCode('docTypeInvalid', 'type');
			}
		}

		// AGENCY BANK ACCOUNT ////////////////////////////////////////////////////////////////////
		if ($fields['idAgencyBankAcount']) {
			$ba = \Entity\AgencyBankAccount::select($fields['idAgencyBankAcount']);
			if (!$ba->recordExists()) {
				$currentMessages->addErrorCode('invalidAgencyBankAccId', 'idAgencyBankAcount');
			} elseif ($ba->deleted) {
				$currentMessages->addWarningCode('agencyBankAccDeleted', 'idAgencyBankAcount');
			}
		}


		// CHECK THAT DOCUMENT DATE IS AFTER LAST CLOSED DATE -------------------------------------
		if ($fields['date']) {
			$lastClosedDate = \Cashbook::getLastClosedBalanceDate($cashBookDocument->idOffice);
			if ($lastClosedDate and $fields['date'] <= $lastClosedDate) {
				$currentMessages->addWarningCode('docDateAfterLastClosedDate', 'date', \Engine\DateTime::isoToStd($lastClosedDate));
			}
		}
	}

	protected function isAvailable_delete()
	{
		// current entity id
		$currentEntityId = $this->entity->getId();

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

		// check if task category is not already deleted
		$cashBookDocument = \Entity\CashBookDocument::selectForUpdate($currentEntityId);

		if (!$cashBookDocument->recordExists()) {
			$currentMessages->addErrorCode('delete_idNotValid');
			return;
		}
		elseif ($cashBookDocument->deleted) {
			$currentMessages->addWarningCode('delete_idDeleted');
			return;
		}

		// check that document is not issued
		if (!\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('Modules/Invoices/CashBook/Documents-void')) {
			$currentMessages->addWarningCode('delete_cantDelete' );
			return;
		}


		// check that document is not issued
		if (!\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('Modules/Invoices/CashBook/Documents-voidIssued')) {
			if ($cashBookDocument->issueTime) {
				$currentMessages->addWarningCode('delete_issuedDocIsBlocked' );
				return;
			}
		}

		if ($cashBookDocument->blockTime) {
			$currentMessages->addWarningCode('delete_cantDeleteBlockedDoc');
			return;
		}

		if (!\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('cashBookManDocsAnyOffice') and $cashBookDocument->idOffice != CURRENT_ID_OFFICE) {
			$currentMessages->addWarningCode('delete_notSameOffice');
			return;
		}

		// check if document is included in a closed balance
		$lastClosedDate = \Cashbook::getLastClosedBalanceDate($cashBookDocument->idOffice);
		if ($lastClosedDate and $cashBookDocument->date <= $lastClosedDate) {
			$currentMessages->addWarningCode('delete_docIncludedInBalance');
			return;
		}

	}

	protected function isAccessible_block()
	{
		// current collected messages
		$currentMessages = $this->entity->getMessages();

		// CHECK THAT SELECTED OFFICE IS THE SAME AS THE ONE FROM SESSION /////////////////////////
		if (!\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('Modules/Invoices/CashBook/Documents-block')) {
			$currentMessages->addWarningCode('noAccessToOption');
		}

	}

	protected function isAvailable_block()
	{
		// current collected messages
		$currentMessages = $this->entity->getMessages();

		// cash book document
		$cashBookDocument = \Entity\CashBookDocument::selectForUpdate($this->entity->getId());

		// CHECK IF DOCUMENT IS ALREADY BLOCKED /////////////////////////////////////////////////////
		if ($cashBookDocument->blockTime) {
			$currentMessages->addWarningCode('block_alreadyBlocked');
		}
	}


	protected function isAccessible_unblock()
	{
		// current collected messages
		$currentMessages = $this->entity->getMessages();

		// CHECK THAT SELECTED OFFICE IS THE SAME AS THE ONE FROM SESSION /////////////////////////
		if (!\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('Modules/Invoices/CashBook/Documents-block')) {
			$currentMessages->addWarningCode('noAccessToOption');
		}

	}


	protected function isAvailable_unblock()
	{
		// current collected messages
		$currentMessages = $this->entity->getMessages();

		// cash book document
		$cashBookDocument = \Entity\CashBookDocument::selectForUpdate($this->entity->getId());

		// CHECK IF DOCUMENT IS ALREADY UNBLOCKED
		if (!$cashBookDocument->blockTime) {
			$currentMessages->addWarningCode('block_notBlocked');
		}
	}
}