<?php
namespace Modules\Partners\Suppliers\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/Suppliers/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\SupplierContract::insert());
			break;

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

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

				foreach ($selection as $selectedItem) {
					if (!\Entity\SupplierContract::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/Suppliers/Contracts-block')) {
					$option->setDisabled()->addMessage('warning', $this->globalLang['noAccessToOption']);
				}

				foreach ($selection as $selectedItem) {
					if (\Entity\SupplierContract::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\SupplierContract::delete($selectedItem))) {
						break;
					}
				}
			break;

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

				foreach ($selection as $selectedItem) {
					if (!\Entity\SupplierContract::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\SupplierContract::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\SupplierContract::select($id)->contractNumber;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedListing::insert_getDefaultFormData()
	 */
	protected function insert_getDefaultFormData($R)
	{
		if ($R['supplier']) {
			$formData['idSupplier'] = $R['supplier'];
		}
		else {
			$formData = [];
		}

		return $formData;
	}

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

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

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

		$contract->content = 			$formData['content'];
		$contract->contractNumber = 	$formData['contractNumber'];
		$contract->contractDate = 		$formData['contractDate'] ? $formData['contractDate'] : null;
		$contract->type =				$formData['type'];
		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\SupplierContract::select($idEntity);

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

		return $formData;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Controller\Window\PaginatedListing\PaginatedEntityListing::update_createEntityObject()
	 */
	protected function update_createEntityObject($formData)
	{
		$contract = \Entity\SupplierContract::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\SupplierContract::delete($idRecord);
	}

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

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

		$formData['contractNumber'] =	$contract->contractNumber;
		$formData['contractDate'] = 	$contract->contractDate;
		$formData['content'] = 			$contract->content;
		$formData['supplier'] = 		$contract->supplier->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\SupplierContract::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;
	}

	/**
	 *
	 * @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/Suppliers/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\SupplierContract::update($id);
			$contractUpdEnt->active = !\Entity\SupplierContract::select($id)->active;
			\App\Mvc\Controller\Helpers\EntityOperations::executeSave($contractUpdEnt, $msgs, $this->useSqlTransaction);
			$this->getListingSelection()->delete([$id]);
		}

	}
}
