<?php
namespace Modules\Partners\Corporates\Contracts;

class Controller extends \App\Mvc\Controller\Window\PaginatedListing\PaginatedEntityListing
{
	/**
	 * The list of columns which support ordering.
	 * @var array
	 */
	protected $listOrderingColumns = ['addTime'];


	protected $useSqlTransaction = true;

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing::initialize()
	 */
	protected function initialize()
	{
		parent::initialize();

		$this->actionsCfg['insert'] = 		 ['checkSection' => false,   'checkOption' => true];
		$this->actionsCfg['update'] = 		 ['checkSection' => false,   'checkOption' => true];
		$this->actionsCfg['delete'] = 		 ['checkSection' => false,   'checkOption' => true];
		$this->actionsCfg['block'] = 		 ['checkSection' => false,   'checkOption' => true];
		$this->actionsCfg['unblock'] = 		 ['checkSection' => false,   'checkOption' => 'Modules/Partners/Corporates/Contracts-block'];
		$this->actionsCfg['view'] = 		 ['checkSection' => false,   'checkOption' => false];
		$this->actionsCfg['download'] = 	 ['checkSection' => false,   'checkOption' => true];
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\ListingAbstract::optionDefineParams()
	 */
	protected function optionDefineParams(\App\Mvc\View\Utils\RowOptions\Option\Option $option, $selection)
	{

		switch($option->getId()){
			case 'insert':
				$option->determineOperationAvailability(\Entity\CorporateContract::insert());
			break;

			case 'update':
				foreach ($selection as $selectedItem) {
					if (!$option->determineOperationAvailability(\Entity\CorporateContract::update($selectedItem))) {
						break;
					}
				}
			break;

			case 'block':
				if (!\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('Modules/Partners/Corporates/Contracts-block')) {
					$option->setDisabled()->addMessage('warning', $this->globalLang['noAccessToOption']);
				}

				foreach ($selection as $selectedItem) {
					if (!\Entity\CorporateContract::select($selectedItem)->active) {
						$option->setDisabled();
						$option->addMessage('warning', $this->lang['index']['options']['reasons']['block']['alreadyBlocked']);
					}
				}
			break;

			case 'unblock':
				if (!\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('Modules/Partners/Corporates/Contracts-block')) {
					$option->setDisabled()->addMessage('warning', $this->globalLang['noAccessToOption']);
				}

				foreach ($selection as $selectedItem) {
					if (\Entity\CorporateContract::select($selectedItem)->active) {
						$option->setDisabled();
						$option->addMessage('warning', $this->lang['index']['options']['reasons']['unblock']['alreadyActive']);
					}
				}
			break;

			case 'delete':
				foreach ($selection as $selectedItem) {
					if (!$option->determineOperationAvailability(\Entity\CorporateContract::delete($selectedItem))) {
						break;
					}
				}
			break;

			case 'download':
				if (!\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('Modules/Partners/Corporates/Contracts-download')) {
					$option->setDisabled()->addMessage('warning', $this->globalLang['noAccessToOption']);
				}
				foreach ($selection as $selectedItem) {
					if (!\Entity\CorporateContract::select($selectedItem)->fileName) {
						$option->setDisabled();
						$option->addMessage('warning', $this->lang['index']['options']['reasons']['download']['noFile']);
						break;
					}
				}
			break;

			case 'view':
				foreach ($selection as $selectedItem) {
					if (!\Entity\CorporateContract::select($selection[0])->content) {
						$option->setDisabled();
						$option->addMessage('warning', $this->lang['index']['options']['reasons']['view']['noContent']);
						break;
					}
				}
			break;

			default:
				return false;
		}

		return true;

	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\ListingAbstract::optionGetEntityName()
	 */
	protected function optionGetEntityName($id)
	{
		return \Entity\CorporateContract::select($id)->contractNumber;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing::insert_getDefaultFormData()
	 */
	protected function insert_getDefaultFormData($R)
	{

		if ($R['corporate']) {
			$formData['idCorporate'] = $R['corporate'];
		}
		else {
			$formData = [];
		}

		return $formData;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedEntityListing::insert_createEntityObject()
	 */
	protected function insert_createEntityObject($formData)
	{
		$contract = \Entity\CorporateContract::insert($formData['id']);

		$uploadedFile = new \App\Form\UploadedFiles\File('document');

		$contract->active = 			1;
		$contract->idCorporate = 		$formData['idCorporate']['id'];
		if ($formData['serviceCode']) {
			$contract->serviceCode = 	$formData['serviceCode'];
		}
		if ($formData['responsibleUser']['id']) {
			$contract->idResponsibleUser= $formData['responsibleUser']['id'];
		}
		$contract->type = 				$formData['type'];
		$contract->content = 			$formData['content'];
		$contract->expireDate = 		$formData['expireDate'] ? $formData['expireDate'] : null;

		$contract->contractNumber = 	$formData['contractNumber'];
		$contract->contractDate = 		$formData['contractDate'] ? $formData['contractDate'] : null;
		if ($uploadedFile->hasValidFile()) {
			$contract->fileName = 		$uploadedFile->getName();
			$contract->fileContent = 	$uploadedFile->getContents();
		}

		return $contract;

	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing::update_getDefaultFormData()
	 */
	protected function update_getDefaultFormData($idEntity)
	{
		$contract = \Entity\CorporateContract::select($idEntity);

		$formData['idCorporate'] = 			$contract->idCorporate;
		$formData['serviceCode'] = 			$contract->serviceCode;
		$formData['contractNumber'] =		$contract->contractNumber;
		$formData['contractDate'] = 		$contract->contractDate;
		$formData['type'] = 				$contract->type;
		$formData['expireDate'] = 			$contract->expireDate;
		$formData['content'] = 				$contract->content;
		$formData['responsibleUser']['id']= $contract->idResponsibleUser;
		$formData['document'] = 			$contract->fileName;

		return $formData;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedEntityListing::update_createEntityObject()
	 */
	protected function update_createEntityObject($formData)
	{
		$contract = \Entity\CorporateContract::update($formData['id']);
		$contract->serviceCode =		$formData['serviceCode'];
		$contract->contractNumber =	    $formData['contractNumber'];
		$contract->contractDate =	    $formData['contractDate'] ? $formData['contractDate'] : null;
		$contract->type =	    		$formData['type'];
		$contract->expireDate =		    $formData['expireDate']? $formData['expireDate'] : null;
		$contract->idResponsibleUser =  $formData['responsibleUser']['id'];
		$contract->content =			$formData['content'];

		if ($formData['document_keepFile']) {
			$contract->deleteFile = 	0;
		}
		else {
			$contract->deleteFile = 1;
			$uploadedFile = new \App\Form\UploadedFiles\File('document');
			if ($uploadedFile->hasValidFile()) {
				$contract->fileName = $uploadedFile->getName();
				$contract->fileContent = $uploadedFile->getContents();
			} else {
				$contract->fileName = '';
				$contract->fileContent = null;
			}
		}
		return $contract;
	}


	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedEntityListing::delete_createEntityObject()
	 */
	protected function delete_createEntityObject($idRecord)
	{
		return \Entity\CorporateContract::delete($idRecord);
	}

	protected function actionView($R)
	{
		$msgs = \App\MessagesCollector::create();

		$contract = \Entity\CorporateContract::select($R['id']);

		$formData['contractNumber'] =	$contract->contractNumber;
		$formData['contractDate'] = 	$contract->contractDate;
		$formData['content'] = 			$contract->content;
		$formData['corporate'] = 		$contract->corporate->alias;
		$formData['service'] = 			$contract->serviceCode;

		// instantiate the view
		$view = new View_View($this);
		$view->addInput('formData', $formData);
		$view->setPageTitle(sprintf("%s %s / %s", $view->getPageTitle(), $contract->contractNumber, $contract->contractDate));
		$view->getMessagesCollector()->appendMessages($msgs);

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

	/**
	 * @param array $R
	 */
	protected function actionDownload($R)
	{
		try {
			$contract = \Entity\CorporateContract::select($R['id']);
			$fileContent = $contract->fileContent;
			$fileName = $contract->fileName;
		}
		catch (\Exception $ex) {
			throw new \Exception("The file couldn't be downloaded.");
		}

		$response = new \Engine\Mvc\Response\FileDownload($fileContent);
		$response->setFilename($fileName);
		return $response;
	}

	/**
	 * Executes the block/unblock operation on a list of records.
	 * @param array $recordsIds
	 * @param \App\MessagesCollector $msgs
	 * @param array $R
	 */
	protected function bulkActionBlock(array $recordsIds, \App\MessagesCollector $msgs, array $R)
	{
		$_LANG = \App\Loader_Lang::getInstance()->getGlobal();

		if (!\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('Modules/Partners/Corporates/Contracts-block')) {
			$msgs->addWarning($_LANG['noAccessToOption']);
		}

		if ($msgs->hasErrorOrWarning()) {
			throw new \App\MessagesException($msgs);
		}

		// loop selected records, delete them and remove from selection
		foreach($recordsIds as $id) {
			$contractUpdEnt = \Entity\CorporateContract::update($id);
			$contractUpdEnt->active = !\Entity\CorporateContract::select($id)->active;
			\App\Mvc\Controller\Helpers\EntityOperations::executeSave($contractUpdEnt, $msgs, $this->useSqlTransaction);
			$this->getListingSelection()->delete([$id]);
		}

	}

}
