<?php
//Modality list for combobox search box

require_once('../../autoload.php');
header('Content-Type: application/json');

$listInstitution = array();

$conn = get_dbconnection();




if($conn)
{
  $mod="and modality.modalitytitle not in ('CT','MG','NM')";

  if(isset($_GET['modality']))
  {
    $extracond = '';
    if(isset($_GET['filterri']) && $_GET['filterri'] == 'true')
    {
      if($_GET['modality'] != 'RI')
      {
        $mod.= " and ri = false";
      }
    }

    switch($_GET['modality'])
    {
      case 'RX': ;break; //default;
      case 'CT': $mod=" and modality.modalitytitle = 'CT'";break;
      case 'MG': $mod=" and modality.modalitytitle = 'MG'";break;
      case 'NM': $mod=" and modality.modalitytitle = 'NM'";break;
      case 'RI': $mod=" and modality.ri = true and modalitytitle not in ('CT','MG','NM')" ;break;
	    case '*':  $mod="";break;
      default:break;
    }
  }

  $user_modality_filter = '';
  if(isset($_SESSION['filter_modalitylist']) && $_SESSION['filter_modalitylist'] != '')
  {
    $user_modality_filter = 'and modality.mod_id in('.$_SESSION['filter_modalitylist'].')';
  }

  $sql="select institution.inst_id, institution.name,modality.mod_id, modality.name from institution,department,room,modality where institution.inst_id = department.inst_id and department.dep_id = room.dep_id and room.room_id = modality.room_id and modality.removed = false and modality.mod_id != -1 and modality.removed = false and modality.active = true {$user_modality_filter} {$mod} order by institution.name,modality.name";

  $listInstitution = array();
  if($query=pg_query($conn,$sql))
  {
    $counter = 0;
    while($row = pg_fetch_row($query))
    {

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

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

        $listInstitution[$row[0]] = $tt;

      }

      $institution = &$listInstitution[$row[0]];
      $modality = new stdClass();
      $modality->type = "option";
      $modality->value = $row[2];
      $modality->label = $row[3];
      $institution->children[] = $modality;
    }
  }


}
else{
  echo "Could not connect";
}
$vArray = [];
foreach ($listInstitution as $key => $value){
  $vArray[] =  $value;
}
$myJSON = json_encode($vArray);

echo $myJSON;
?>
