<?php
namespace Modules\Orders\MiceProjects;

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();

		$listObj = new \App\EntityList\MiceProjects();
		$listObj->setColumns(['name', 'startDate', 'endDate', 'code', 'idType', 'idResponsibleUser', 'cityId', 'countryCode', 'closed',  'addTime']);

		// FILTERS ////////////////////////////////////////////////////////////////////////////////
		if ($filters['name']) {
			$listObj->setFilter('name', 'LIKE', "%{$filters['name']}%");
		}

		if ($filters['type']['id']) {
			$listObj->setFilter('idType', '=', $filters['type']['id']);
		}

		if ($filters['corporation']['id']) {
			$listObj->setFilter('idCorporate', '=', $filters['corporation']['id']);
		}

		if ($filters['responsibleUser']['id']) {
			$listObj->setFilter('idResponsibleUser', '=', $filters['responsibleUser']['id']);
		}

		if ($filters['status'] == 'open') {
			$listObj->setFilter('closed', 'LIKE', false);
		}
		elseif ($filters['status'] == 'closed') {
			$listObj->setFilter('closed', 'LIKE', true);
		}

		if ($filters['location']['id']) {
			list($cntrCode, $cityId) = explode('|', $filters['location']['id']);
			if ($cityId) {
				$listObj->setFilter('cityId', '=', $cityId);
			}
			elseif ($cntrCode) {
				$listObj->setFilter('countryCode', '=', $cntrCode);
			}
		}

		if ($filters['period']['start']) {
			$listObj->setFilter('startDate', '>=', $filters['period']['start']);
		}
		if ($filters['period']['end']) {
			$listObj->setFilter('endDate', '<=', $filters['period']['end']);
		}

		if ($filters['projectId']) {
			$listObj->setFilter('micePrj.id', '=', $filters['projectId']);
		}

		if ($filters['projectCode']) {
			$listObj->setFilter('micePrj.code', '=', $filters['projectCode']);
		}

		///////////////////////////////////////////////////////////////////////////////////////////

		// ORDER BY START DATE ////////////////////////////////////////////////////////////////////
		if ($listingParams->getOrderColumn()=='estimatedPeriod') {
			$listObj->setOrderBy('startDate', $listingParams->getOrderDirection());
			$listObj->setLimit($listingParams->getResultsPerPage()*$listingParams->getCurrentPage(), $listingParams->getResultsPerPage());
		}
		else {
			$listObj = $this->entityList_inheritListingParams($listingParams, $listObj);
		}

		$this->recordsList = $listObj->exportRecords();
		$this->totalRecordsCount = $listObj->getRecordsCount();
	}
}