<?php

namespace Modules\RemoteData\EntityManagementWs\Model\Entity\Supplier;

class Search extends \Modules\RemoteData\EntityManagementWs\Model\Entity\SearchAbstract
{

	/**
	 * {@inheritDoc}
	 * @see \Modules\RemoteData\EntityManagementWs\Model\Entity\SearchAbstract::search()
	 */
	protected function search() :void
	{

		// GETS THE RAW DETAILS OF THE SEARCH /////////////////////////////////////////////////////
		$words = preg_split("/[\s,]+/", $this->request->searchString);

		$entityList = new \App\EntityList\Suppliers();
		$entityList->setColumns( [ 'alias', 'companyPrefix', 'company', 'companySuffix', 'telephone', 'fax', 'email' ] );

		foreach($words as $word) {
			if ($this->request->searchMode=='contains') { // contains
				$entityList->setCustomFilter(
					"alias LIKE ? OR company LIKE ?",
					[ "%{$word}%", "%{$word}%" ]
				);
			} else { // starts
				$entityList->setCustomFilter(
					"alias LIKE ? OR company LIKE ?",
					[ "{$word}%", "{$word}%" ]
				);
			}
		}

		$entityList->setFilter('idRealSupplier', '=', 0);

		// order the results
		if ($this->request->columnOrder and $this->request->directionOrder) {
			$entityList->setOrderBy($this->request->columnOrder, $this->request->directionOrder);
		}
		elseif ($this->request->columnOrder and !$this->request->directionOrder) {
			$entityList->setOrderBy($this->request->columnOrder, 'ASC');
		}
		else {
			$entityList->setOrderBy('alias', 'ASC');
		}

		$entityList->setLimit((Int)$this->request->offset, $this->request->limit);

		$records = $entityList->exportRecords();

		// COMPOSE THE OUTPUT /////////////////////////////////////////////////////////////////////
		$listResults = [];
		foreach ($records as $record) {

			$object = new \stdClass();

			$object->id				= $record['id'];
			$object->alias 			= $record['alias'];
			$object->company		= $record['company'];
			$object->companyPrefix	= $record['companyPrefix'];
			$object->companySuffix	= $record['companySuffix'];
			$object->email 			= $record['email'];
			$object->fax 			= $record['fax'];
			$object->telephone 		= $record['telephone'];

			$listResults[] = $object;
		}

		// populate the response with records and total results
		$this->populateSearchResponse($listResults, $entityList->getRecordsCount());

	}

}
