<?php
namespace Modules\Documents\BulkDownload;

class Controller extends \App\Mvc\Controller\Form\PopupAbstract
{
	/**
	 *
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Form\WindowAbstract::getDefaultFormData()
	 */
	protected function getDefaultFormData($R)
	{
		$formData = [];
		$formData['ids'] = $R['ids'];
		$formData['pivot'] = $R['pivot'];
		return $formData;
	}

	/**
	 *
	 * {@inheritDoc}
	 * @see \App\Mvc\Controller\Form\WindowAbstract::processFormData()
	 */
	protected function processFormData(Array $R, \App\MessagesCollector $msgs)
	{

	}

	/**
	 * The main "save form" action.
	 * @return string
	 */
	protected function actionIndex($R)
	{
		if ($R[$this->formSubmitButtonName]) {

			try {
				if (!$R['ids']) {
					throw new \App\MessagesException(\App\MessagesCollector::create()->addError($this->lang['index']['msgs']['pivot']['noSelection']));
				}

				if (!$R['docTypes']) {
					throw new \App\MessagesException(\App\MessagesCollector::create()->addError($this->lang['index']['msgs']['pivot']['noDocTypesSelected']));
				}

				// Create archive
				$modelOutput = $this->createArchive($R);

				// file download
				$fileName = sprintf("documents_%s.zip", \Engine\DateTime::create()->format('Ymd'));
				$response = new \Engine\Mvc\Response\BigFileDownload($modelOutput);
				$response->body->setOption('deleteAfterSend', true);
				$response->body->setOption('debug', true); 				// Enable for troubleshooting
				$response->body->setOption('ignoreUserAbort', false); 	// Ensure cleanup happens even if client disconnects
				// $response->body->setOption('downloadMethod', 'fread:50kbps');

 				$response->setFilename($fileName);

				return $response;
			}
			catch (\App\MessagesException $e) {
				// collects messages
				$msgs = \App\MessagesCollector::create();
				$msgs->appendMessages($e->getMessagesCollector());

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

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

				// render the view
				return new \Engine\Mvc\Response\Html($view->render());
			}
		}
		else {
			return parent::actionIndex($R);
		}
	}

	/**
	 * Create archive
	 *
	 * @param array $R
	 * @return string
	 */
	private function createArchive(Array $R)
	{
		$documentIdList = [];

		foreach ($R['ids'] as $idPivot) {
			$documentPivotObject = new \Modules\Documents\Generate\DocumentPivot($R['pivot'], $idPivot);
			$documentsList = $documentPivotObject->getDocumentsList();

			// Group by document type
			$docs = [];
			foreach ($documentsList as $idDocument => $documentDetails) {
				// check if the current document is not a preview and the document type is from the selected list
				if (in_array($documentDetails['docType'], $R['docTypes']) && !$documentDetails['preview']) {
					$docs[$documentDetails['docType']] = $idDocument;
				}
			}

			foreach ($docs as $docId) {
				$documentIdList[] = $docId;
			}
		}

		if (!$documentIdList) {
			throw new \App\MessagesException(\App\MessagesCollector::create()->addError(sprintf($this->lang['index']['msgs']['pivot']['selected']['noDocuments'], $idPivot)));
		}

		$model = new Model($documentIdList);
		$zipPath = $model->createDocumentsArchive();

		return $zipPath;

	}

}