<?php

	require_once('../../autoload.php');

	header('Content-Type: application/json');

	$type = "";

	if ( isset ( $_GET['type'] ) && $_GET['type'] != '' 	)		$type = $_GET['type'];

	$request = '';
	$groupbyoption = false;
	switch ( $type )
	{
		case 'modality':
			$request = "select id,name,modalitytype from device where removed=false and (ris_name is not null or pacs_name is not null or dacs_name is not null) order by modalitytype,name";
			$groupbyoption = true;
			break;

		case 'radiologist':
			$request = "select id, lastname || ' ' || firstname as name,'' from staff_member where removed = false and (ris_name is not null or pacs_name is not null or dacs_name is not null) order by lastname";
			break;
	}

  $listmodalitytitle = array();

	if($request != '')
	{
		$conn = get_dbconnection();

		if($conn)
		{


		  if($query=pg_query($conn,$request))
		  {

			  if($groupbyoption)
				{
			    while($row = pg_fetch_row($query))
			    {

			      $row[1]=trim(preg_replace('/[[:cntrl:]]/', '', htmlspecialchars($row[1],ENT_QUOTES)));
			      if(!array_key_exists($row[2],$listmodalitytitle))
			      {
			        $tt = new stdClass();
			        $tt->type = "optiongroup";

			        $tt->label = $row[2];
			        $tt->children = array();

			        $listmodalitytitle[$row[2]] = $tt;
			      }
			      $devicelist = &$listmodalitytitle[$row[2]];
			      $device = new stdClass();
			      $device->type = "option";
			      $device->value = $row[0];
			      $device->label = $row[1];
			      $devicelist->children[] = $device;
			    }
				}else{
				 while($row = pg_fetch_row($query))
				 {
					 $row[1]=trim(preg_replace('/[[:cntrl:]]/', '', htmlspecialchars($row[1],ENT_QUOTES)));
		       $cb = new stdClass();
		       $cb->type = "option";
		       $cb->value = $row[0];
		       $cb->label = $row[1];
		       $listmodalitytitle[] = $cb;
				 }
				}
		  }

		}
		else{
		  error_log("Could not connect");
		}
	}

	$vArray = [];
	foreach ($listmodalitytitle as $key => $value){
	  $vArray[] =  $value;
	}

	$myJSON = json_encode($vArray);
	echo $myJSON;
?>
