<?php
	include(__DIR__.'/../includes/sysinit.php');
	$searchString = trim(SableSystem::sableDecode($_POST['input_id']));
	if (!isset($resultDescFieldName)) $resultDescFieldName = $resultDescField;
	
	if (is_array($resultTableName))
	{
		$sql = "select ".$resultIdField.", ".$resultDescField.PHP_EOL."from ".$resultTableName[0]['table_name'].PHP_EOL;
		$cnt = 0;
		foreach($resultTableName as $rt)
		{
			if ($cnt) //ignore the first entry (main table)
			{
				$sql .= "inner join ".$rt['table_name']." on ".$rt['table_name'].".".$rt['id_field_name']." = ".$resultTableName[0]['table_name'].".".$rt['id_field_name'].PHP_EOL;
			}
			$cnt++;
		}
	}
	else $sql = "select ".$resultIdField.", ".$resultDescField." from ".$resultTableName;
	
	$where = false;
	if (!empty($searchString)) 
	{
		$where = true;
		$sql .= " where (";
		if(is_array($callRefineField))
		{
			$idx = 0;
			foreach($callRefineField as $fld)
			{
				if ($idx) $sql .= " or ";
				$sql .= "(".$fld." like '%".$searchString."%')";
				$idx++;
			}
		}
		else $sql .= $callRefineField." like '%".$searchString."%'";
		$sql .= ") "; //encase in brackets for adding restrictions below.
	}
	
	if (isset($restrictionFields))
	{
		if (is_array($restrictionFields))
		{
			$sz = sizeof(array_filter($restrictionFields));
			if ($sz)
			{
				if (!$where) 
				{
					$sql .= " where (";
					$where = true;
				} else $sql .= " and (";
				$cnt = 0;
				foreach($restrictionFields as $restrictionField)
				{
					if($cnt) $sql = " and ".$sql;
					$sql .= "(".$restrictionField['name']." ".$restrictionField['operator']." '".$restrictionField['value']."')";
				}
				$sql .= ") "; //encase in brackets for more features in future.
			}
		} 
		else 
		{
			$sql .= $where ? ' and '.$restrictionFields : ' where '.$restrictionFields;
		}
	}
	
	if ($callOrderField) $sql .= " order by ".$callOrderField;

	$rows = $sableDB->getRows($sql);

	$html = "";
	foreach($rows as $row)
	{
		$html .= '<option value="'.SableSystem::sableEncode($row[$resultIdField]).'">'.trim($row[$resultDescFieldName]).'</option>';
	}
	
	if (!isset($resultIgnoreDelims))
	{
		$html = str_replace(',', ' or', $html);
		$html = str_replace('.', '', $html);
	}

	$output = (empty($html))?'<option>No results...</option>':$html;
	SableSystem::ajaxFillField($output, $_POST['field_id']);