<?php

namespace Modules\Partners\Corporates\Contracts;

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)
	{
		//global $DBTCorporates;

		$filters = $listingParams->getFilters();

		// get the corporates list
		$listObj = new \App\EntityList\CorporateContracts();
		$listObj->setColumns(['addTime', 'active', 'type', 'idCorporate', 'serviceCode', 'contractNumber',
				'contractDate', 'content', 'fileName', 'expireDate', 'idResponsibleUser'
		]);

		// corporate filter
		if ($filters['corporate']['id']) {
			$listObj->setFilter('idCorporate', 'LIKE', $filters['corporate']['id']);
		}

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

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

		// status filter
		if ($filters['status'] == 'active') {
			$listObj->setFilter('active', '=', '1');
		}
		elseif ($filters['status'] == 'inactive') {
			$listObj->setFilter('active', '=', '0');
		}

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

		// contractDate filter
		if ($filters['contractDate']['start'] && $filters['contractDate']['end']) {
			$listObj->setCustomFilter('contractDate >= ? AND contractDate <= ?', [$filters['contractDate']['start'], $filters['contractDate']['end']]);
		}
		elseif ($filters['contractDate']['start'] && !$filters['contractDate']['end']) {
			$listObj->setFilter('contractDate', '>=', $filters['contractDate']['start']);
		}
		elseif (!$filters['contractDate']['start'] && $filters['contractDate']['end']) {
			$listObj->setFilter('contractDate', '<=', $filters['contractDate']['end']);
		}

		// expireDate filter
		if ($filters['expireDate']['start'] && $filters['expireDate']['end']) {
			$listObj->setCustomFilter('expireDate >= ? AND expireDate <= ?', [$filters['expireDate']['start'], $filters['expireDate']['end']]);
		}
		elseif ($filters['expireDate']['start'] && !$filters['expireDate']['end']) {
			$listObj->setFilter('expireDate', '>=', $filters['expireDate']['start']);
		}
		elseif (!$filters['expireDate']['start'] && $filters['expireDate']['end']) {
			$listObj->setFilter('expireDate', '<=', $filters['expireDate']['end']);
		}

		// file filter
		if ($filters['file'] == 'withAttachment') {
			$listObj->setFilter('fileName', '!=', '');
		}
		elseif ($filters['file'] == 'noAttachment') {
			$listObj->setFilter('fileName', '=', '');
		}

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

		// these must be called in this specific order
		$this->recordsList = $listObj->exportRecords();
		$this->totalRecordsCount = $listObj->getRecordsCount();
	}

}
