<?php
namespace Modules\Documents\Generate\Email\EmailList;

class Controller extends \App\Mvc\Controller\Popup\PaginatedListing\ListingAbstract
{

	/**
	 * The list of columns which support ordering.
	 * @var array
	 */
	protected $listOrderingColumns = ['sendTime'];

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

		$this->actionsCfg['index'] =     	     	['checkSection' => false, 'checkOption' => false,];
		$this->actionsCfg['list'] =   	        	['authType' => 'easy', 'checkSection' => false, 'checkOption' => false,];
		$this->actionsCfg['listRecords'] = 			['authType' => 'easy', 'checkSection'=>false, 'checkOption'=>false];
		$this->actionsCfg['saveDynamicColumns'] = 	['authType' => 'easy', 'checkSection'=>false, 'checkOption'=>false];
		$this->actionsCfg['options'] =     			['authType' => 'easy', 'checkSection'=>false, 'checkOption'=>false];

		$this->actionsCfg['download'] = 			['checkSection' => false];
	}


	/**
	 * (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 'resendEmail': case 'sendEmail':
			break;
		}
		return true;
	}

	protected function loadListingParams($R)
	{
		$ret = parent::loadListingParams($R);

		if ($R['idDocument']) {
			$listingParams = $this->getListingParams();
			$filters = $listingParams->getFilters();

			$filters['idDocument'] = $R['idDocument'];
			$listingParams->setFilters($filters);
			$listingParams->save();
			$this->listingParams = $listingParams;
		}

		return $ret;
	}

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

	/**
	 * Download attached files
	 * @param Array $R
	 * @throws \Exception
	 * @return \Engine\Mvc\Response\FileDownload
	 */
	protected function actionDownload($R)
	{
		$model = new \Modules\Documents\Generate\Email\EmailList\Model();

		$response = new \Engine\Mvc\Response\FileDownload($model->getFileContent($R['idDocument'], $R['idFile']));
		$response->setFilename($model->getFileName($R['idDocument'], $R['idFile']));

		return $response;
	}

	/**
	 * {@inheritDoc}
	 * @see \App\Mvc\ControllerAbstract::verifyAccessToAction()
	 */
	protected function verifyAccessToAction($action, $R)
	{
		parent::verifyAccessToAction($action, $R);

		$documentEntity = \Entity\Document::select($R['idDocument']);
		$pivotDocumentObject = new \Modules\Documents\Generate\DocumentPivot($documentEntity->pivotCode, $documentEntity->idPivot);
		if (!$pivotDocumentObject->userHasAccessToGenerate()) {
			throw new \Engine\Mvc\ControllerException(sprintf("You do not have access to the module '%s'", $this->module), "auth_noSectionAccess");
		}
	}

}