<?php
//Modality list for combobox search box

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

$listInstitution = array();

$conn = get_dbconnection();

if($conn)
{
  $params = [];
  $where = [];

  // Base conditions
  $where[] = "modality.removed = false";
  $where[] = "modality.mod_id != -1";
  $where[] = "modality.active = true";

  // Default filter
  $mod = "modality.modalitytitle NOT IN ('CT','MG','NM')";

  if(isset($_GET['modality']))
  {
    $modality = $_GET['modality'];

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

    switch($modality)
    {
      case 'RX': break; // default
      case 'CT': $mod = "modality.modalitytitle = $".(count($params)+1); $params[] = 'CT'; break;
      case 'MG': $mod = "modality.modalitytitle = $".(count($params)+1); $params[] = 'MG'; break;
      case 'NM': $mod = "modality.modalitytitle = $".(count($params)+1); $params[] = 'NM'; break;
      case 'RI': $mod = "modality.ri = true AND modality.modalitytitle NOT IN ('CT','MG','NM')"; break;
      case '*':  $mod = "1=1"; break;
      default: break;
    }
  }

  $where[] = $mod;

  // ?? Sécurisation du IN (...)
  if(isset($_SESSION['filter_modalitylist']) && $_SESSION['filter_modalitylist'] != '')
  {
    // On garde uniquement des entiers
    $ids = array_filter(
      explode(',', $_SESSION['filter_modalitylist']),
      fn($v) => ctype_digit($v)
    );

    if(!empty($ids))
    {
      $placeholders = [];
      foreach($ids as $id)
      {
        $params[] = (int)$id;
        $placeholders[] = "$".count($params);
      }

      $where[] = "modality.mod_id IN (".implode(',', $placeholders).")";
    }
  }

  $sql = "
    SELECT institution.inst_id, institution.name,
           modality.mod_id, modality.name, modality.modalitytitle
    FROM institution
    JOIN department ON institution.inst_id = department.inst_id
    JOIN room ON department.dep_id = room.dep_id
    JOIN modality ON room.room_id = modality.room_id
    WHERE ".implode(' AND ', $where)."
    ORDER BY institution.name, modality.name
  ";

  $listInstitution = array();

  if($query = pg_query_params($conn, $sql, $params))
  {
    while($row = pg_fetch_row($query))
    {
      for($i = 0; $i < count($row); $i++)
      {
        $row[$i] = trim(preg_replace('/[[:cntrl:]]/', '', htmlspecialchars($row[$i], 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];
      $modality->modalitytype = $row[4];

      $institution->children[] = $modality;
    }
  }
}
else{
  echo "Could not connect";
}

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

echo json_encode($vArray);
?>