<?php
namespace App\Form\Input;

/**
 * SQL queries all MICE projectTypes|projects from the DB
 * @author FlorinRusu
 *
 */
class Autocomplete_Data_MiceTypeAndProject extends \Engine\Form\Input\Autocomplete_Data_GeneralAbstract
{

	/**
	 * (non-PHPdoc)
	 * @see \Engine\Form\Input\Autocomplete_Data_GeneralAbstract::getPageResultsBulk()
	 */
	protected function getPageResultsBulk() :array
	{
		$miceProjectsListObj = new \App\EntityList\MiceProjects();
		$miceProjectsListObj->applyUserRestriction(false);
		$miceProjectsListObj->setColumn('micePrjTypes.name', 'extra');
		$miceProjectsListObj->setColumn('micePrj.name', 'result');
		$miceProjectsListObj->setCustomColumn("CONCAT(micePrjTypes.id, '|', micePrj.id)", 'code');
		$miceProjectsListObj->setCustomFilter('micePrjTypes.name LIKE ? OR micePrj.name LIKE ?', ["{$this->searchString}%", "{$this->searchString}%"]);

		$miceProjectsArr 	= $miceProjectsListObj->exportRecords();
		$miceProjectsCount	= $miceProjectsListObj->getRecordsCount();

		$miceProjectTypesListObj = new \App\EntityList\MiceProjectTypes();
		$miceProjectTypesListObj->applyUserRestriction(false);
		$miceProjectTypesListObj->setColumn('micePrjTypes.name', 'result');
		$miceProjectTypesListObj->setCustomColumn("CONCAT(micePrjTypes.id, '|0')", 'code');
		$miceProjectTypesListObj->setFilter('micePrjTypes.name', 'LIKE', "{$this->searchString}%");

		$miceProjectTypesArr 	= $miceProjectTypesListObj->exportRecords();
		$miceProjectTypesCount 	= $miceProjectTypesListObj->getRecordsCount();

		// count total and merge the results
		$this->resultsCountTotal 	= $miceProjectsCount + $miceProjectTypesCount;
		$resultMiceProjectTypesArr 	= array_merge($miceProjectsArr, $miceProjectTypesArr);

		// sort array equivalent to order by
		usort($resultMiceProjectTypesArr, function($a, $b) {
			return strcmp($a['result'], $b['result']);
		});

		// slice array equivalent to limit
		$resultMiceProjectTypesArr = array_slice($resultMiceProjectTypesArr, $this->offset, $this->resultsCountPage);

		return $resultMiceProjectTypesArr;
	}

	/**
	 * (non-PHPdoc)
	 * @see \Engine\Form\Input\Autocomplete_Data_GeneralAbstract::getPageResultsFormatted()
	 */
	protected function getPageResultsFormatted(Array $pageResults)
	{
		$list = [];
		foreach($pageResults as $row) {
			$list[] = $this->getCleanItem($row['code'], $row['result'], $row['extra']);
		}

		return $list;
	}

}