<?php

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

$listInstitution = array();

$conn = get_dbconnection();

if($conn)
{
    $sql = "select msd.mserd_id,msd.description,msd.type from master_serie_description msd, raw_serie_description rsd
  where msd.mserd_id != -1 and removed = false
  and msd.mserd_id  = rsd.mserd_id group by msd.mserd_id,msd.description,msd.type
  order by type,description";
    
    $listInstitution = array();
    if($query=pg_query($conn,$sql))
    {
        $counter = 0;
        while($row = pg_fetch_row($query))
        {
            if ( !array_key_exists($row[2],$listInstitution) )
            {
                $tt = new stdClass();
                $tt->type = "optiongroup";

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

            $institution = &$listInstitution[$row[2]];
            $modality = new stdClass();
            $modality->type = "option";
            $modality->value = $row[0];
            $modality->label = $row[1];
            $institution->children[] = $modality;
        }
    }
}
else
{
    echo "Could not connect";
}

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

$myJSON = json_encode($vArray);

echo $myJSON;
?>
