<?php
namespace Modules\Admin\UsersTrails;

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\UserTraces();
		$listObj->applyUserRestriction(false);
		$listObj->setColumns(['module', 'action', 'entityType', 'entityOperation', 'idEntity', 'extraData', 'timestamp', 'idUser']);

		if (!$filters['timeInterval']['start']) {
			throw new \Exception("Start date is not filled in");
		}

		if (!$filters['timeInterval']['end']) {
			throw new \Exception('End date is not filled in');
		}

		if (strlen($filters['timeInterval']['start']) == 10) {
			$listObj->setFilter('timestamp', '>=', \Engine\DateTime::createFromIsoDateOrDatetime($filters['timeInterval']['start'] . " 00:00:00")->formatTime());
		}
		else {
			$listObj->setFilter('timestamp', '>=', \Engine\DateTime::createFromIsoDateOrDatetime($filters['timeInterval']['start'])->formatTime());
		}

		if (strlen($filters['timeInterval']['end']) == 10) {
			$listObj->setFilter('timestamp', '<=', \Engine\DateTime::createFromIsoDateOrDatetime($filters['timeInterval']['end'] . " 23:59:59")->formatTime());
		}
		else {
			$listObj->setFilter('timestamp', '<=', \Engine\DateTime::createFromIsoDateOrDatetime($filters['timeInterval']['end'])->formatTime());
		}

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

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

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

		// entity type
		if ($filters['entityType']) {
			$listObj->setFilter('entityType', 'LIKE', $filters['entityType']);
		}

		// operation
		if ($filters['operation']) {
			$listObj->setFilter('entityOperation', 'LIKE', $filters['operation']);
		}

		// entity code
		if ($filters['entityCode']) {
			$listObj->setFilter('idEntity', 'LIKE', $filters['entityCode']);
		}

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

		// EXTRA DATA /////////////////////////////////////////////////////////////////////
		foreach ($trailsList as $key => $visit) {
			if($visit['extraData']) {
				$trailsList[$key]['extraDataArr'] = unserialize($visit['extraData']);
			}
		}

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