<?php  

include_once("config.php");
include("sem/sparql.php");
include("sem/sql.php");

$searchtext = $_REQUEST["term"];
$type = $_REQUEST["type"];
$concepts = $_REQUEST["concepts"];
$limit = $_REQUEST["limit"];

//echo $concepts;

$typesStr = explode(";", $type);
$types = array();
for ($i = 0; $i < count($typesStr); $i = $i + 1){
	if ($typesStr[$i] == "concept")
		$types[] = "<http://www.w3.org/2000/01/rdf-schema#Class>";
	else if ($typesStr[$i] == "property")
		$types[] = "rdf:Property";
	else if ($typesStr[$i] == "instance")
		$types[] = "<http://www.intuview.com/ontology#iv469>";
}

if (strlen($concepts) > 0){
	if ($concepts[strlen($concepts) - 1] == ';')
		$concepts = substr($concepts, 0, strlen($concepts) - 1);
	$conArr = explode(";", $concepts);
//	print_r($conArr);
}

$query = "select distinct ?e ?l";
$query .= " where { ";

for ($i = 0; $i < count($types); $i = $i + 1){
	$query .= "{";
	
	if ($types[$i] == "rdf:Property"){
		$query .= " ?e rdf:type " . $types[$i] . " .";
		$query .= " OPTIONAL{?e iv:direct-property ?dp} .";
		$query .= " FILTER(!bound(?dp)) .";
	}
	else if (is_null($conArr) || count($conArr) == 0) 
		$query .= " ?e rdf:type " . $types[$i] . " .";
		
	else{
		if (count($conArr) == 1){
			if ($types[$i] == "<http://www.intuview.com/ontology#iv469>")
				$query .= " ?e rdf:type <" . $conArr[0] . "> .";
			else{
				$query .= " ?e rdf:type " . $types[$i] . " .";
				$query .= " ?e rdfs:subClassOf " . $conArr[0] . " .";
			}
		}
		else{
			$query .= "{ ";
			for ($j = 0; $j < count($conArr); $j = $j + 1){
				if ($types[$i] == "<http://www.intuview.com/ontology#iv469>"){
					$query .= " { ?e rdf:type <" . $conArr[$j] . "> . }";
				}
				else{
					$query .= " { ?e rdf:type " . $types[$i] . " .";
					$query .= " ?e rdfs:subClassOf <" . $conArr[$j] . "> . }";
				}
				if ($j < count($conArr) - 1)
					$query .= " UNION ";
			}
			$query .= "}";
		}
	}
	$query .= "}";
	if ($i < count($types) - 1)
		$query .= " UNION ";
}

$query .= " ?e rdfs:label ?l .";
if ($rdfstoreMode == "regular"){
	$query .= " FILTER regex(?l, \"" . $searchtext . "\", \"i\") .";
}

$query .= " }";

$query .= " ORDER BY ?l";
if ($rdfstoreMode == "regular"){
	if ($limit != "unlimited"){
		$query .= " LIMIT " . $limit;
	}
	else{
		$query .= " LIMIT " . $rperpage;
	}
}

$query = buildBasicSparql($query);
if ($rdfstoreMode == "combined"){
	if ($limit == "unlimited")
		$limit = -1;
	$sqlQuery = buildBasicLabelSql($searchtext, false, "e", false);
	$json = executeSqlSparqlOnService($query, $sqlQuery, $limit, 0);
}
else{
	$json = executeSparqlOnService($query, "ont");
}

//$query = buildBasicSparql($query);
//$json = executeSparqlOnService($query, "ont");


foreach ($json[results][bindings] as $value){
	$results[] = array("name" => $value[e][value], "label" => $value[l][value]);  
}

$response = $_GET["callback"] . "(" . json_encode($results) . ")";  
echo $response;  
  
?>  