<?php
namespace Entity;

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

	/**
	 * Check user access to use insert operation
	 */
	protected function isAccessible_insert()
	{
		// current collected messages
		$currentMessages = $this->entity->getMessages();

		// check user access
		if (!\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption("Modules/Partners/Corporates-profile")) {
			$currentMessages->addWarningCode('noAccessToOption');
		}

	}

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

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

		if ($fields['idCorporate']) {

			$corporateEnt = \Entity\Corporate::select($fields['idCorporate']);

			if (!$corporateEnt->recordExists()) {
				$currentMessages->addErrorCode('invalidId');
			}
			elseif ($corporateEnt->deleted) {
				$currentMessages->addWarningCode('corporateDeleted');
			} elseif ($corporateEnt->locked) {
				$currentMessages->addWarningCode('corporateBlocked');
			} elseif ($corporateEnt->idRealCorporate) {
				$currentMessages->addWarningCode('corporateDuplicate');
			}
		}

		// check weekdays and month days values
		if (is_array($fields['weekDays']) and array_diff($fields['weekDays'], range(0,6))) {
			$currentMessages->addWarningCode('invalidWeekDays');
		}

		if (is_array($fields['monthDays']) and array_diff($fields['monthDays'], range(1,31))) {
			$currentMessages->addWarningCode('invalidMonthDays');
		}

		// check profile code
		if ($fields['profileCode'] and !\App\Config\CorporateCollectionProfiles::getInstance()->check($fields['profileCode'])) {
			$currentMessages->addErrorCode('invalidProfileCode');
		}

		// check receivers
		if ($fields['to']) {
			foreach (explode(';', $fields['to']) as $toAddr) {
				if (!\Engine\Validator::set(trim($toAddr))->isEmail()) {
					$currentMessages->addWarningCode('invalidEmailTo');
				}
			}
		}
		if ($fields['bcc']) {
			foreach (explode(';', $fields['bcc']) as $bccAddr) {
				if (!\Engine\Validator::set(trim($bccAddr))->isEmail()) {
					$currentMessages->addWarningCode('invalidEmailBcc');
				}
			}
		}

	}


	/**
	 * Check if user has access to update corporate
	 */
	protected function isAccessible_update()
	{
		// current collected messages
		$currentMessages = $this->entity->getMessages();

		// check user access
		if (!\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('Modules/Partners/Corporates-profile')) {
			$currentMessages->addWarningCode('noAccessToOption');
		}

	}

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

		$corporateCollection = \Entity\CorporateCollection::selectForUpdate($this->entity->getId());

		// check if corporate exists and is not deleted
		$corporateEnt = \Entity\Corporate::selectForUpdate($corporateCollection->idCorporate);

		if ($corporateEnt->deleted) {
			$currentMessages->addWarningCode('corporateDeleted');
		} elseif ($corporateEnt->locked) {
			$currentMessages->addWarningCode('corporateBlocked');
		} elseif ($corporateEnt->idRealCorporate) {
			$currentMessages->addWarningCode('corporateDuplicate');
		}
	}

	/**
	 * Check fields for updating action
	 */
	protected function check_update()
	{
		// current collected messages
		$currentMessages = $this->entity->getMessages();

		// current fields details
		$fields = $this->entity->getFields();

		// check weekdays and month days values
		if (key_exists("weekDays", $fields) and array_diff($fields['weekDays'], range(0,6))) {
			$currentMessages->addWarningCode('invalidWeekDays');
		}

		if (key_exists("monthDays", $fields) and array_diff($fields['monthDays'], range(1,31))) {
			$currentMessages->addWarningCode('invalidMonthDays');
		}

		if ($fields['to']) {
			foreach (explode(';', $fields['to']) as $toAddr) {
				if (!\Engine\Validator::set(trim($toAddr))->isEmail()) {
					$currentMessages->addWarningCode('invalidEmailTo');
				}
			}
		}

		if ($fields['bcc']) {
			foreach (explode(';', $fields['bcc']) as $bccAddr) {
				if (!\Engine\Validator::set(trim($bccAddr))->isEmail()) {
					$currentMessages->addWarningCode('invalidEmailBcc');
				}
			}
		}
	}

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

		// check user access
		if (!\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('Modules/Partners/Corporates-profile')) {
			$currentMessages->addWarningCode('noAccessToOption');
		}

	}

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

		// check if corporate exists and is not deleted
		$corporateCollection = \Entity\CorporateCollection::selectForUpdate($this->entity->getId());

		if (!$corporateCollection->recordExists()) {
			$currentMessages->addErrorCode('invalidId');
		}
	}

	/**
	 *
	 */
	protected function isAvailable_sendEmail()
	{
		$currentMessages = $this->entity->getMessages();

		// check if corporate exists and is not deleted
		$corporateEnt = \Entity\Corporate::select($this->entity->getId());

		if ($corporateEnt->deleted) {
			$currentMessages->addWarningCode('corporateDeleted');
		}
		elseif ($corporateEnt->locked) {
			$currentMessages->addWarningCode('corporateBlocked');
		}
		elseif ($corporateEnt->idRealCorporate) {
			$currentMessages->addWarningCode('corporateDuplicate');
		}

	}

	protected function check_sendEmail()
	{
		$currentMessages = $this->entity->getMessages();
		$fields = $this->entity->getFields();

		// check if corporate exists and is not deleted
		$corporateCollection = \Entity\CorporateCollection::selectForUpdate($this->entity->getId());

		// the analyzer isn't valid
		if (!$fields['analyzer'] or !($fields['analyzer'] instanceof \App\ClientCollection\Corporate\Analyzer)) {
			throw new \Exception('You must set the `analyzer` object in CorporateCollection::sendEmail.');
		}
		if ($fields['analyzer']->getIdCorporate() != $this->entity->getId()) {
			$currentMessages->addErrorCode('sendEmail_analyzerCorpDiffers');
		}

		if (!$fields['analyzer']->getOverdueInvoices() and !$fields['analyzer']->getDueInDaysInvoices()) {
			$currentMessages->addWarningCode('sendEmail_noInvoices');
		}

		// the emailData object isn't valid
		if (!$fields['emailData'] or !($fields['emailData'] instanceof \App\ClientCollection\Corporate\EmailData)) {
			throw new \Exception('You must set the `emailData` object in CorporateCollection::sendEmail.');
		}
		if ($fields['emailData']->getIdCorporate() != $this->entity->getId()) {
			$currentMessages->addErrorCode('sendEmail_emailDataCorpDiffers');
		}
		$fields['emailData']->getData(); // this is executed only to store the data internally and to determine the error messages (if any)
		if ($fields['emailData']->getMessages()->hasErrorOrWarning()) {
			$currentMessages->addMessageCollector($fields['emailData']->getMessages());
		}

		if (!in_array($fields['executionType'], ['cronJob', 'manual'])) {
			$currentMessages->addErrorCode('sendEmail_wrongExecutionType');
		}

		// must check nextSendDatetime when the company has a custom profile set
		if ($fields['executionType'] == 'cronJob' and $corporateCollection->recordExists() and DATETIME < $corporateCollection->nextSendDatetime) {
			$currentMessages->addWarningCode('sendEmail_timeIsNotRight');
		}

		// check that either th company or the profile has all datetime details set
		if ($fields['executionType'] == 'cronJob' and $corporateCollection->recordExists()) {

			$profileDetails = \App\Config\CorporateCollectionProfiles::getInstance()->get($corporateCollection->profileCode);

			if (!$corporateCollection->weekDays and !$profileDetails['weekDays']) {
				$currentMessages->addWarningCode('sendEmail_noWeekDaysSet');
			}
			if (!$corporateCollection->monthDays and !$profileDetails['monthDays']) {
				$currentMessages->addWarningCode('sendEmail_noMonthDaysSet');
			}
			if (!$corporateCollection->sendTime and !$profileDetails['time']) {
				$currentMessages->addWarningCode('sendEmail_noTimeSet');
			}

		}

	}

}