<?php
namespace Modules\Documents\DocumentsList;

class Model extends \App\Mvc\Model_ListingAbstract
{
	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\Model_ListingAbstract::list_execute()
	 */
	public function list_execute(\App\Mvc\View\Listing\Members\Params $listingParams)
	{
		$filters=$listingParams->getFilters();

		// get the documents list
		$listObj = new \App\EntityList\Documents();

		$listObj->setColumns(['pivot', 'idPivot', 'docType', 'docNumber', 'docDate',
			'idTemplate', 'generation', 'docFile', 'emailSent', 'disableEmailSending'
		]);		$listObj->applyUserRestriction(true);

		// document date
		if ($filters['docDate']) {
			$listObj->setFilter('docDate', '>=', $filters['docDate']['start']);
			$listObj->setFilter('docDate', '<=', $filters['docDate']['end']);
		}

		// document pivot
		if ($filters['pivot']) {
			$listObj->setFilter('pivot', '=', $filters['pivot']);
		}

		// document number
		if ($filters['docNumber']) {
			$listObj->setFilter('docNumber', '=', $filters['docNumber']);
		}

		// document id
		if ($filters['idDoc']) {
			$listObj->setFilter('doc.id', '=', $filters['idDoc']);
		}

		// id pivot
		if ($filters['idPivot']) {
			$listObj->setFilter('idPivot', '=', $filters['idPivot']);
		}

		// document type
		if ($filters['docType']) {
			$listObj->setFilter('docType', '=', $filters['docType']);
		}

		// generation
		if ($filters['generation']) {
			$listObj->setFilter('generation', '=', $filters['generation']);
		}

		// document template
		if ($filters['docTemplate']) {
			$listObj->setFilter('idTemplate', '=', $filters['docTemplate']);
		}

		$listObj = $this->entityList_inheritListingParams($listingParams, $listObj);

		// these must be called in this specific order
		$documents = $listObj->exportRecords();
		$documentsCount = $listObj->getRecordsCount();

		$recordList = [];
		foreach ($documents as $doc) {
			$doc['fileSize'] = \Engine\File::formatBytes( \Entity\Document::select($doc['id'])->docFileSize );
			$recordList[] = $doc;
		}

		$this->recordsList = $recordList;
		$this->totalRecordsCount = $documentsCount;
	}

}