<?php
namespace Modules\Documents\BulkDownload;

class Model extends \App\Mvc\ModelAbstract
{
	/**
	 * Archive documents list
	 * @var array
	 */
	protected $documentIdList;

	/**
	 * The class constructor - attaches main global vars.
	 */
	public function __construct($documentIdList)
	{
		$this->documentIdList = $documentIdList;
	}

	/**
	 * Create documents archive
	 * @param array $documentsIdList
	 * @return string
	 */
	public function createDocumentsArchive()
	{
		if (!$this->documentIdList) {
			throw new \App\MessagesException($this->lang['model']['msgs']['documentsList']['invalid']);
		}

		$uid = time();
		$pathDestination = 		\Engine\Dir::tempnam(sprintf('%s-%s', __CLASS__, $uid));
		$pathDestinationZip = 	\Engine\File::tempnam(sprintf('%s-%s.zip', __CLASS__, $uid));

		\Engine\Dir::create($pathDestination);

		// Get last generated document
		foreach ($this->documentIdList as $documentId) {
			$documentEntity = \Entity\Document::select($documentId);
			// Copy last generated document to temporary location
			\Engine\File::copy($documentEntity->docFileNameWithPath, $pathDestination.$documentEntity->docFile);
		}

		// zip archive
		$zip = new \App\Archive\Compress\Zip();
		$zip->open($pathDestination)
			->setCompressionLevel(\App\Archive\Compress\Zip::COMPRESS_MEDIUM)
			->compressTo($pathDestinationZip)
			->close();

		// Remove temporary folder used for archive
		\Engine\Dir::delete($pathDestination);

		return $pathDestinationZip;
	}

}