<?php

require_once '../../autoload.php';

header('Content-Type: application/json; charset=utf-8');

$conn = get_dbconnection();

$row = array();

if($conn)
{

$sql = "select count(*) as numberofalert,'<table id=''modalitystatetable''><tr><th>Modality</th><th>Last study</th><th>Number of day</th></tr>'||string_agg(trrow,'')||'</table>' as alerttable
from(select '<tr class=''modalitystate'' id='''||mi.mod_id||'-modalitystate''><td class=''modalityname''>'||mi.name||'</td><td>'||coalesce(to_char(mi.last_study_date,'dd/MM/YYYY HH24:MI'),'Never')||'</td><td>'||coalesce((now()::date - mi.last_study_date::date)::text,'')||'</td></tr>'
   as trrow
   from v_last_study_by_modality  mi,modality m where mi.modactive = true  and mi.modremoved = false
   and m.mod_id = mi.mod_id and (now()::date - mi.last_study_date::date > m.alert_disconnected_in_day or mi.last_study_date is null)
   order by last_study_date desc nulls last) as alert;";

  if($query=pg_query($conn,$sql))
  {
    if($row = pg_fetch_assoc($query))
    {

      $nalert = $row['numberofalert'];

      if($nalert != '0')
       $validalert = true;

    }
    else
    {
        $row['numberofalert'] = 0;
    }
    
    $row['error'] = 0;
  }
  else
  {
    $row['error'] = 1;
    error_log('Failed to execute query:'. $sql);
  }
}
else
{
  $row['error'] = 1;
}

echo json_encode($row);

?>


