<?php
namespace Modules\Documents\Generate\Upload;

class Controller extends \App\Mvc\Controller\Form\PopupAbstract
{

	/**
	 * The id of the new inserting record.
	 * @var Int|String
	 */
	protected $insertIdRecord = null;

	/**
	 * The main "save form" action.
	 * @return string
	 */
	protected function actionIndex($R)
	{
		// collects messages
		$msgs = \App\MessagesCollector::create();

		$modelOutput = null;
		// SAVE THE FORM DATA /////////////////////////////////////////////////////////////////////
		if ($R[$this->formSubmitButtonName]) {
			$modelOutput = $this->processFormData($R, $msgs);
		}

		// instantiate the view
		$view = new View_Index($this);

		// get form data for this operation
		if (!$R[$this->formSubmitButtonName]) {
			$formData = $this->getDefaultFormData($R);
		} else {
			$formData = $this->getSubmitFormData($R, $msgs);
		}

		// send data to the view
		$view->addInput('formData', $formData);
		$view->getMessagesCollector()->appendMessages($msgs);
		$view->addInput('formSubmitButtonName', $this->formSubmitButtonName);

		// redirect to document management
		if ($modelOutput) {
			$response = new \Engine\Mvc\Response\HtmlRedirect(\Engine\Mvc\Dispatcher::getInstance()->getAppUrl("Modules/Documents/Generate", "index", [
				'idDocument' => $this->insertIdRecord,
				'pivot' =>		$R['pivot'],
				'idPivot' => 	$R['idPivot']
			]));

			return $response;
		}

		// do some more stuff (if needed)
		$this->preRenderOperations($view, $formData);

		// render the view
		return new \Engine\Mvc\Response\Html($view->render());

	}

	/**
	 * Returns an array of data which is sent to the form in an identical format as the $_REQUEST.
	 * Is is used to fill in the default (previous) values of the form's fields.
	 * @param Array $R
	 */
	protected function getDefaultFormData($R)
	{
		$formData = [];

		$formData['idPivot'] = 			$R['idPivot'];
		$formData['pivot'] = 			$R['pivot'];

		$formData['documentDate'] = 	TODAY_ISO;

		return $formData;
	}


	/**
	 * It uses the $formData (values collected form the form to attempt to save the info in the
	 * database/files (external storage).
	 * @param Array $formData
	*/
	protected function processFormData(Array $R, \App\MessagesCollector $msgs)
	{
		// get pivot and id pivot
		$pivot = $R['pivot'];
		$idPivot = $R['idPivot'];

		// check user access to this pivot
		if (!$this->userHasAccessToUpload($pivot, $idPivot)) {
			$msgs->addWarning($this->lang['index']['msgs']['noAccess']);
			return false;
		}

		// check document type
		if (!$R['documentType']) {
			$msgs->addWarning($this->lang['index']['msgs']['noDocumentType']);
		}

		// check the uploaded file
		$uploadedFile = new \App\Form\UploadedFiles\File('uploadedFile');
		if (!$uploadedFile->hasValidFile()) {
			$msgs->addWarning($this->lang['index']['msgs']['invalidFile']);
		}


		if (!$msgs->hasErrorOrWarning()) {
			if ($pivot == 'cashBookDoc') {
				\Entity\Document::createMonthlyTables(\Entity\CashBookDocument::select($idPivot)->date);
			}

			if ($pivot == 'importedService') {
				\Entity\Document::createMonthlyTables(\Engine\DateTime::createFromIsoDatetime(\Entity\ImportedService::select($idPivot)->addTime)->formatDateIso());
			}

			if ($pivot == 'importedDocument') {
				\Entity\Document::createMonthlyTables(\Engine\DateTime::createFromIsoDatetime(\Entity\ImportedDocument::select($idPivot)->addTime)->formatDateIso());
			}

			try {
				\DB::startTransaction();

				$documentEntity = \Entity\Document::insert();
				$documentEntity->pivot = 				$pivot;
				$documentEntity->idPivot = 				$idPivot;
				$documentEntity->generation = 			'manual';
				$documentEntity->docType = 				$R['documentType'];
				$documentEntity->docNumber = 			$R['documentNumber'];
				$documentEntity->docDate =				$R['documentDate'];
				$documentEntity->idIssueUser =			CURRENT_ID_USER;
				$documentEntity->docContent = 			$uploadedFile->getContents();
				$fileFormat = 							strtolower(\Engine\File::getExtension($uploadedFile->getName()));
				$documentEntity->format = 				$fileFormat;

				// set document name
				if ($R['documentName']) {
					$documentEntity->docFile = $R['documentName'].'.'.$fileFormat;
				}
				else {
					$documentEntity->docFile = $uploadedFile->getName();
				}

				$documentEntity->comments = 			$R['comments'];
				$documentEntity->save();

				\DB::commitTransaction();

				foreach($documentEntity->getMessages()->getMessages() as $msg) {
					$msgs->addMessage($msg);
				}

				// get  the inserted document id
				$this->insertIdRecord = $documentEntity->getId();

				return true;
			}
			catch (\App\Entity\Exception $ex) {
				\DB::rollbackTransaction();
				$msgs->appendMessages($ex->getMessagesCollector());

				return false;
			}
		}

		return false;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Form\WindowAbstract::preRenderOperations()
	 */
	protected function preRenderOperations(\App\Mvc\ViewAbstract $view, array $formData)
	{
		$msgs = new \App\MessagesCollector();

		// get information from request
		$pivot = 			$formData['pivot'];
		$idPivot = 			$formData['idPivot'];

		// validate the input
		if (!$pivot) {
			$msgs->addWarning($this->lang['index']['msgs']['invalidPivot']);
		}

		// check pivot id
		if (!is_numeric($idPivot)) {
			$msgs->addWarning($this->lang['index']['msgs']['invalidIdPivot']);
		}

		// check user access to this pivot
		if (!$this->userHasAccessToUpload($pivot, $idPivot)) {
			$msgs->addWarning($this->lang['index']['msgs']['noAccess']);
		}

		// check if pivot is voided
		$documentPivotObject = new \Modules\Documents\Generate\DocumentPivot($pivot, $idPivot);
		if (!$msgs->hasErrorOrWarning() and $documentPivotObject->checkIfPivotIsVoided()) {
			$msgs->addInfo($this->lang['index']['msgs']['voidedPivot']);
		}

		// append to view
		$view->setOutputVar('pivot', $pivot);
		$view->setOutputVar('idPivot', $idPivot);
		$view->getMessagesCollector()->appendMessages($msgs);
	}

	/**
	 * Check if user has access to upload document
	 * @return boolean
	 */
	public function userHasAccessToUpload($pivot, $idPivot)
	{
		// check user access to this pivot
		if (
			($pivot == 'order' 				and !\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('reservationDocumentsManagement')) or
			($pivot == 'service' 			and !\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('serviceDocumentsManagement')) or
			($pivot == 'invoice' 			and !\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('invoiceDocumentsManagement')) or
			($pivot == 'cashing' 			and !\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('cashingDocumentsManagement')) or
			($pivot == 'cashBookDoc' 		and !\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('cashBookDocumentsManagement')) or
			($pivot == 'payment' 			and !\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('paymentDocumentsManagement')) or
			($pivot == 'importedService' 	and !\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('importedServiceDocumentsManagement')) or
			($pivot == 'importedDocument' 	and !\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('importedDocsDocumentsManagement')) or
			($pivot == 'balance' 			and !\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('balanceDocumentsManagement'))
		) {
			return false;
		}

		return true;
	}
}