<?php

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

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

	protected function checkRequestData() :void
	{

		parent::checkRequestData();

		// check the type of the contact persons
		if (!$this->request->type) {
			throw new \Modules\RemoteData\EntityManagementWs\Model\RuntimeException('The contact person type is not set.', 'ContactPersonTypeNotSet');
		} elseif ($this->request->type!='corporate' and $this->request->type!='supplier') {
			throw new \Modules\RemoteData\EntityManagementWs\Model\RuntimeException('The contact person type is not valid - it can only be `corporate` or `supplier`.', 'ContactPersonTypeNotValid');
		}

	}


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

		// get the results from DB
		$words = preg_split("/[\s,]+/", $this->request->searchString);

		$entityList = new \App\EntityList\ContactPersons();
		$entityList->setColumns( [ 'idCompany', 'title', 'firstName', 'lastName', 'idOffice' ] );
		$entityList->setFilter('type', 'LIKE', $this->request->type);

		foreach($words as $word) {
			// search mode = contains
			if ($this->request->searchMode=='contains') {
				$entityList->setCustomFilter('lastName LIKE ? OR firstName LIKE ?', ['%'.$word.'%', '%'.$word.'%']);
			}
			// search mode = starts
			else {
				$entityList->setCustomFilter('lastName LIKE ? OR firstName LIKE ?', [$word.'%', $word.'%']);
			}
		}

		// 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('lastName', 'ASC');
			$entityList->setOrderBy('firstName', 'ASC');
		}

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

		$records = $entityList->getExecution();

		$listResults = [];
		foreach ($records as $record) {
			$object = new \stdClass();

			$object->id	= $record['id'];
			$object->lastName = $record['lastName'];
			$object->firstName = $record['firstName'];
			$object->title = $record['title'];
			$object->idCompany = $record['idCompany'];
			if ($record['idOffice']) {
				$object->idCompany = $record['idOffice'];
			}

			$listResults[] = $object;
		}

		// populate the response with records and total results
		$this->response->type = 		$this->request->type;

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

	}

}


