<?php
  error_log ( "Dashboard..." );

  include '../autoload.php';

  if($_SESSION['view'][VIEW_DASHBOARD] != '1' && $_SESSION['view'][VIEW_DASHBOARD_WORKING] != '1')
  {
      error_log ( "Dashboard EXIT !!!" );
      include('../Common/404nf.html');
      exit();
  }


  $globalalert[0] = 0;
  $globalalert[1] = 0;
  $globalalert[2] = 0;
  $globalalert[3] = 0;

  $dashboard_alert_req['staff'] = "select distinct vf.name,level,to_char(planned_date,'DD/MM/YYYY') from v_alert_staff_formation vf,v_staffmember_taglistdep_active_staffjob vm
where vm.staff_id  = vf.staff_id and taglistdep_id && '{{$_SESSION['alltagidallow']}}'::integer[]";

  $dashboard_alert_req['incidentreporting'] = "select title,severity, to_char(reportdate,'DD/MM/YYYY') from v_alert_report left join v_taglink_instdep on v_alert_report.dep_id = v_taglink_instdep.dep_id
              where tagdepid is null or tagdepid = any('{{$_SESSION['alltagidallow']}}'::integer[]) order by severity desc,reportdate desc";

$dashboard_alert_req['device_maintenance'] = "select distinct name,level,to_char(planned_date,'DD/MM/YYYY') as planned_date from v_alert_device_maintenance alert,v_device_actif_by_deptagid vdabd where alert.id = vdabd.device_id
              and tag_id = any('{{$_SESSION['alltagidallow']}}'::integer[]) and planned_date::date <= {$GLOBALS["date_planned_maintenance"]} order by planned_date";

$dashboard_alert_req['device_inspection']   = "SELECT 
                                                distinct name,
                                                level,
                                                to_char(planned_date,'DD/MM/YYYY') as planned_date 
                                              FROM v_alert_device_inspection alert,v_device_actif_by_deptagid vdabd 
                                              WHERE 
                                                alert.id = vdabd.device_id and 
                                                tag_id = any('{{$_SESSION['alltagidallow']}}'::integer[]) and 
                                                planned_date::date <= {$GLOBALS["date_planned_inspection"]} 
                                              ORDER BY planned_date";


$dashboard_alert_req['audit']               = "SELECT 
                                                title,
                                                level,
                                                to_char(date,'DD/MM/YYYY') 
                                              FROM v_alert_audit 
                                              LEFT JOIN tag_link tli 
                                              ON 
                                                tli.type = 'institution' and 
                                                tli.ext_id = inst_id 
                                              LEFT JOIN tag_link tld 
                                              ON 
                                                tld.type='department' and 
                                                tld.ext_id = dep_id
                                              WHERE  coalesce(tld.tag_id,tli.tag_id) = any('{{$_SESSION['alltagidallow']}}'::integer[])";

$dashboard_alert_req['dosimetry']           = "SELECT 
                                                distinct department,
                                                level,
                                                to_char(senddate,'DD/MM/YYYY'),
                                                senddate 
                                              FROM v_alert_afcnsend vaa 
                                              LEFT JOIN tag_link 
                                              ON tag_link.type = 'department' and 
                                                tag_link.ext_id = vaa.dep_id, department 
                                              WHERE 
                                                department.id = vaa.dep_id and 
                                                vaa.dep_id != -1 and 
                                                tag_id = any('{{$_SESSION['alltagidallow']}}'::integer[]) 
                                              ORDER BY senddate,level";
/*
$dashboard_alert_req['scheduledtask']       = "SELECT 
                                                level, 
                                                title, 
                                                description, 
                                                to_char(due_date, 'DD/MM/YYYY') as due_date, 
                                                civilitylist.name || ' ' || upper(staff_member.lastname) || ' ' || staff_member.firstname as staff_member
                                              FROM v_alert_task, staff_member, civilitylist 
                                              WHERE 
                                                v_alert_task.staff_member_id=staff_member.id and civilitylist.id=civility_id";
*/

$dashboard_alert_req['scheduledtask']       = "WITH t2 as (
                                                  WITH 
                                                  t0 as (
                                                    SELECT 
                                                      task_id,
                                                      level, 
                                                      title, 
                                                      description, 
                                                      due_date, 
                                                      civilitylist.name || ' ' || upper(staff_member.lastname) || ' ' || staff_member.firstname as staff_member, 
                                                      staff_member_id,
                                                      task_master_id,
                                                      last_reminder 
                                                    FROM 
                                                      v_alert_task, 
                                                      staff_member, 
                                                      civilitylist 
                                                    WHERE 
                                                      v_alert_task.staff_member_id=staff_member.id and 
                                                      civilitylist.id=civility_id) ,
                                                  t1 as (
                                                    SELECT 
                                                      *, 
                                                      row_number() over (partition by t0.task_master_id order by due_date asc) as rn 
                                                    FROM 
                                                      t0 
                                                    WHERE 
                                                      due_date>NOW()) 
                                                  SELECT 
                                                    task_id,
                                                    title, 
                                                    staff_member,
                                                    staff_member_id,
                                                    level,
                                                    due_date,
                                                    last_reminder 
                                                  FROM 
                                                    t1 
                                                  WHERE 
                                                    rn=1 
                                                  UNION
                                                  SELECT 
                                                    task_id,
                                                    title, 
                                                    staff_member,
                                                    staff_member_id, 
                                                    level, 
                                                    due_date,
                                                    last_reminder 
                                                  FROM 
                                                    t0 
                                                  WHERE 
                                                    due_date<=NOW()) 
                                              SELECT 
                                                task_id,
                                                level,
                                                title,
                                                staff_member,
                                                staff_member_id,
                                                to_char(due_date, 'DD/MM/YYYY') as due_date_fmt,
                                                NOW()::date-last_reminder::date as last_reminder 
                                              FROM t2 ORDER BY DUE_DATE ASC";

$dashboard_alert_req['scheduledtaskworking']= "WITH t2 as (
                                                  WITH 
                                                  t0 as (
                                                    SELECT
                                                      task_id, 
                                                      level, 
                                                      title, 
                                                      description, 
                                                      due_date, 
                                                      civilitylist.name || ' ' || upper(staff_member.lastname) || ' ' || staff_member.firstname as staff_member, 
                                                      staff_member_id,
                                                      task_master_id,
                                                      last_reminder 
                                                    FROM 
                                                      v_alert_task, 
                                                      staff_member, 
                                                      civilitylist 
                                                    WHERE 
                                                      v_alert_task.staff_member_id=staff_member.id and 
                                                      civilitylist.id=civility_id) ,
                                                  t1 as (
                                                    SELECT 
                                                      *, 
                                                      row_number() over (partition by t0.task_master_id order by due_date asc) as rn 
                                                    FROM 
                                                      t0 
                                                    WHERE 
                                                      due_date>NOW()) 
                                                  SELECT
                                                    task_id, 
                                                    title, 
                                                    staff_member,
                                                    staff_member_id,
                                                    level,
                                                    due_date,
                                                    last_reminder 
                                                  FROM 
                                                    t1 
                                                  WHERE 
                                                    rn=1 
                                                  UNION
                                                  SELECT 
                                                    task_id,
                                                    title, 
                                                    staff_member,
                                                    staff_member_id, 
                                                    level, 
                                                    due_date,
                                                    last_reminder 
                                                  FROM 
                                                    t0 
                                                  WHERE 
                                                    due_date<=NOW()) 
                                              SELECT 
                                                task_id,
                                                level,
                                                title,
                                                staff_member,
                                                to_char(due_date, 'DD/MM/YYYY') as due_date_fmt,
                                                NOW()::date-last_reminder::date as last_reminder  
                                              FROM 
                                                t2 
                                              WHERE 
                                                staff_member_id=:staff_member_id
                                              ORDER BY DUE_DATE ASC";


$dashboard_alert_req['document']            = "SELECT 
                                                civilitylist.name || ' ' || UPPER(lastname) || ' ' || firstname as username, 
                                                document_master.name || ' - ' || label as document_name, 
                                                document.id as doc_id, 
                                                action_status_link.date, 
                                                action_at, 
                                                CASE 
                                                  WHEN (now()::date - '5 days'::interval)::date >= action_status_link.date::date THEN 3 
                                                  WHEN (now()::date - '3 days'::interval)::date >= action_status_link.date::date THEN 2 
                                                  ELSE 1 
                                                END AS level, 
                                                NOW()::date-action_status_link.date::date as duration,
                                                case
                                                  when folder='audit' then 'Audit' 
                                                  when folder='device' then 'Matériel' 
                                                  when folder='procedure' then 'Procédure'
                                                  when folder='staff_member' then 'Ressources humaines'
                                                  else ''
                                                end as document_type_label,
                                                folder as document_type,
                                                staff_member_id,
                                                NOW()::date-last_reminder::date as last_reminder 
                                              FROM 
                                                document, 
                                                document_master,
                                                action_status_link, 
                                                staff_member,
                                                civilitylist
                                              WHERE 
                                                action_at is null and 
                                                action_id=:action_id and 
                                                document.doc_master_id =document_master.id and 
                                                action_status_link.document_id =document.id and 
                                                action_status_link.staff_member_id =staff_member.id and 
                                                staff_member.civility_id =civilitylist.id
                                              ORDER BY 
                                                document_master.name";

$dashboard_alert_req['mydocument']         = "SELECT 
                                                civilitylist.name || ' ' || UPPER(lastname) || ' ' || firstname as username, 
                                                document_master.name || ' - ' || label as document_name, 
                                                document.id as doc_id, 
                                                action_status_link.date, 
                                                action_at, 
                                                CASE 
                                                  WHEN (now()::date - '5 days'::interval)::date >= action_status_link.date::date THEN 3 
                                                  WHEN (now()::date - '3 days'::interval)::date >= action_status_link.date::date THEN 2 
                                                  ELSE 1 
                                                END AS level, 
                                                NOW()::date-action_status_link.date::date as duration,
                                                case 
                                                  when folder='audit' then 'Audit' 
                                                  when folder='device' then 'Matériel' 
                                                  when folder='procedure' then 'Procédure'
                                                  when folder='staff_member' then 'Ressources humaines'
                                                  else ''
                                                end as document_type_label,
                                                folder as document_type,
                                                staff_member_id,
                                                NOW()::date-last_reminder::date as last_reminder 
                                              FROM 
                                                document, 
                                                document_master,
                                                action_status_link, 
                                                staff_member,
                                                civilitylist
                                              WHERE 
                                                action_at is null and 
                                                action_id=:action_id and 
                                                document.doc_master_id =document_master.id and 
                                                action_status_link.document_id =document.id and 
                                                action_status_link.staff_member_id =staff_member.id and 
                                                staff_member.civility_id =civilitylist.id and 
                                                staff_member.id=:staff_member_id
                                              ORDER BY 
                                                document_master.name";                                                


  function DashDocument ( $nameid, $action_id, $use_id, &$cardcontent, &$cardtitle, &$nalert, &$maxseverity, $caption )
  {
      error_log ( "DashDocument...");
      error_log ( " use_id : " .$use_id );

      global $dashboard_alert_req;

      $pdo = getPDO ();

      if ( $pdo )
      {
          if ( $use_id == -1 )
          {
              $sql = $dashboard_alert_req['document'];

              $s0 = $pdo->prepare ( $sql );
              $s0->bindParam ( ":action_id", $action_id );
          }
          else
          {
              $sql = $dashboard_alert_req['mydocument'];

              $s0 = $pdo->prepare ( $sql );
              $s0->bindParam ( ":action_id", $action_id );
              $s0->bindParam ( ":staff_member_id", $use_id );
          }

          if ( $s0->execute () )
          {
              $lastdoc = '';
              $tableToclose = false;
              $tmp = '';

              $d0 = $s0->fetchAll ( PDO::FETCH_ASSOC );

              for ( $i=0; $i<count($d0); $i++ )
              {
                  $username             = $d0[$i]['username'];
                  $doc_id               = $d0[$i]['doc_id'];
                  $staff_member_id      = $d0[$i]['staff_member_id'];
                  $level                = $d0[$i]['level'];
                  $duration             = $d0[$i]['duration'];
                  $document_type        = $d0[$i]['document_type'];
                  $document_type_label  = $d0[$i]['document_type_label'];
                  $document_name        = $d0[$i]['document_name'];
                  $last_reminder        = $d0[$i]['last_reminder'];

                  error_log ( "Document type : " .$document_type );
                  $pagelink = '';
                  switch ( $document_type )
                  {
                      case 'audit':         $pagelink = 'VIEW_AUDIT';           break;
                      case 'device':        $pagelink = 'VIEW_DEVICE';          break;
                      case 'procedure':     $pagelink = 'VIEW_PROCEDURE';       break;
                      case 'staff_member':  $pagelink = 'VIEW_STAFF';           break;
                  }

                  $nalert++;
                  if($maxseverity < $level)
                      $maxseverity = $level;

                  if ( $document_name != $lastdoc )
                  {
                      if ( $tableToclose == true )
                      {
                          $tableToclose == false;
                          $tmp .=   '</tbody>';
                          $tmp .= '</table>';

                          $cardcontent.=create_alert1 ( $level, $tmp );
                      }

                      $lastdoc = $document_name;
                      $tmp = '<table class="w-100">';
                      $tmp .=   '<tbody>';
                      $tableToclose = true;

                      $text1 = '<div class="fw-bold w-auto m-0 p-0 pe-2" style="cursor:pointer" onclick="SelectPage(\''.$pagelink.'\')"><li class="w-auto">'.$document_type_label.' - '.$document_name.'</li></div>';
                  }
                  else
                      $text1 = '<div class="fw-bold text-center" style="cursor:pointer" onclick="SelectPage(\''.$pagelink.'\')">---</div>';
                  $text2 = ' par '.$username.' depuis '.$duration.' jours';
              
                  $text3 = '';
                  if ( $last_reminder != '' )
                  {
                    switch ( $last_reminder )
                    {
                      case "0":     $text3 = "Rappel aujourd'hui.";                     break;
                      case "1":     $text3 = 'Rappel hier.';                            break;
                      default:      $text3 = 'Rappel il y a '.$last_reminder.' jours.'; break;
                    }
                  }

                  $reminder_id = 'Idc_'.$nameid.'_'.$doc_id.'_'.$staff_member_id;
                  $tmp .=     '<tr>';
                  $tmp .=       '<td style="white-space: nowrap;">';
                  $tmp .=           $text1;
                  $tmp .=       '</td>';

                  $tmp .=       '<td style="white-space: nowrap;">';
                  $tmp .=           $text2;
                  $tmp .=       '</td>';
              
                  $tmp .=       '<td id="'.$reminder_id.'" style="width: 100% !important; text-align: right; color: red; white-space: nowrap;">';
                  $tmp .=           $text3;
                  $tmp .=       '</td>';

                  $tmp .=       '<td style="text-align: right;">';
                  $tmp .=         '<img class="m-0 p-0 ps-3 imgclickable" title="Envoyer un rappel" src="/eoQUALBootstrap/eoQUAL/SubFW/bmp/reminder.png" style="height: 18px; width: auto;" onclick="SendDocumentReminder(\''.$doc_id.'\',\''.$staff_member_id.'\',\''.$reminder_id.'\')"></img>';
                  $tmp .=       '</td>';
              
                  $tmp .=     '</tr>';
              }

              if ( $tableToclose == true )
              {
                  $tableToclose == false;
                  $tmp .=   '</tbody>';
                  $tmp .= '</table>';

                  $cardcontent.=create_alert1 ( $level, $tmp );
              }
          }
      }

      $cardtitle =  $caption.' ('.$nalert.')';
  }



  function DashTask ( $nameid, $action_id, $use_id, &$cardcontent, &$cardtitle, &$nalert, &$maxseverity, $caption )
  {
      error_log ( "DashTask...");
      error_log ( " use_id : " .$use_id );

      global $dashboard_alert_req;

      $pdo = getPDO ();

      if ( $pdo )
      {
          if ( $use_id == -1 )
          {
              $sql = $dashboard_alert_req['scheduledtask'];

              $s0 = $pdo->prepare ( $sql );
          }
          else
          {
              $sql = $dashboard_alert_req['scheduledtaskworking'];

              $s0 = $pdo->prepare ( $sql );
              $s0->bindParam ( ":staff_member_id", $use_id );
          }

          if ( $s0->execute () )
          {
              $lastdoc = '';
              $tableToclose = false;
              $tmp = '';

              $tmp = '<table class="w-100">';
              $tmp .=   '<tbody>';

              $d0 = $s0->fetchAll ( PDO::FETCH_ASSOC );

              for ( $i=0; $i<count($d0); $i++ )
              {
                  $title                = $d0[$i]['title'];
                  $username             = $d0[$i]['staff_member'];
                  $task_id              = $d0[$i]['task_id'];
                  $staff_member_id      = $d0[$i]['staff_member_id'];
                  $level                = $d0[$i]['level'];
                  $due_date_fmt         = $d0[$i]['due_date_fmt'];
                  $last_reminder        = $d0[$i]['last_reminder'];
                  // $last_reminder = '1';

                  $pagelink = 'VIEW_SCHEDULED_TASK';
                  

                  $nalert++;
                  if($maxseverity < $level)
                      $maxseverity = $level;

                  $text1 = '<div class="fw-bold" style="cursor:pointer" onclick="SelectPage(\''.$pagelink.'\')"><li>'.$title.'</li></div>';
                  if ( $use_id == -1 )
                      $text2 = ' - '.$username.' - Echéance : '.$due_date_fmt;
                  else
                      $text2 = ' - Echéance : '.$due_date_fmt;
              
                  $text3 = '';
                  if ( $last_reminder != '' )
                  {
                    switch ( $last_reminder )
                    {
                      case "0":     $text3 = ($use_id==-1)? "Rappel aujourd'hui." : "Rappel reçu aujourd'hui.";                     break;
                      case "1":     $text3 = ($use_id==-1)? "Rappel aujourd'hui." : "Rappel reçu hier.";                            break;
                      default:      $text3 = ($use_id==-1)? 'Rappel il y a '.$last_reminder.' jours.' : 'Rappel reçu il y a '.$last_reminder.' jours.'; break;
                    }
                  }

                  $reminder_id = 'Idc_'.$nameid.'_'.$task_id.'_'.$staff_member_id;
                  $tmp .=     '<tr>';
                  $tmp .=       '<td style="white-space: nowrap;">';
                  $tmp .=           $text1;
                  $tmp .=       '</td>';

                  $tmp .=       '<td class="m-0 p-0 ps-1" style="white-space: nowrap;">';
                  $tmp .=           $text2;
                  $tmp .=       '</td>';
              
                  $tmp .=       '<td id="'.$reminder_id.'" style="width: 100% !important; text-align: right; color: red; white-space: nowrap;">';
                  $tmp .=           $text3;
                  $tmp .=       '</td>';
                  if ( $use_id == -1 )
                  {
                    $tmp .=       '<td style="text-align: right;">';
                    $tmp .=         '<img class="m-0 p-0 ps-3 imgclickable" title="Envoyer un rappel" src="/eoQUALBootstrap/eoQUAL/SubFW/bmp/reminder.png" style="height: 18px; width: auto;" onclick="SendTaskReminder(\''.$task_id.'\',\''.$staff_member_id.'\',\''.$reminder_id.'\','.$_SESSION['id'].')"></img>';
                    $tmp .=       '</td>';
                  }
              
                  $tmp .=     '</tr>';
              }

              $tmp .=   '</tbody>';
              $tmp .= '</table>';

              $cardcontent.=create_alert1 ( $level, $tmp );
          }
      }

      $cardtitle =  $caption.' ('.$nalert.')';
  }


  function create_alert ( $level, $string, $onclick, $string2 )
  {
    global $globalalert;

    if ( $level == -1 )
      return;

    $alertype = '';
    $thediv = '';
    switch ( $level )
    {
      case 0: $alertype = 'alert-success-element';      break;
      case 1: $alertype = 'alert-info-element';         break;
      case 2: $alertype = 'alert-warning-element';      break;
      case 3: $alertype = 'alert-danger-element';       break;
    }
    
    $globalalert[$level]++;

    if($onclick != '')
    {
      $onclick .= ' style="cursor:pointer"';
    }
    
    // $thediv = '<div  class="p-3 fw-bold" '.$onclick.'>- '.$string.'</div>';
    $thediv  =  '<tr>';
    $thediv .=    '<td>';
    $thediv .=        '<div  class="p-0 fw-bold" '.$onclick.'>'.$string.'</div>';
    $thediv .=    '</td>';
    $thediv .=    '<td>';
    $thediv .=        '<div  class="p-0 fw-bold" '.$onclick.'>'.$string2.'</div>';
    $thediv .=    '</td>';
    $thediv .=  '</tr>';

    return $thediv;
  }

  function create_alert1 ( $level, $string )
  {
    error_log ( "create_alert1..");
    error_log ( "string : ".$string);
    global $globalalert;

    if ( $level == -1 )
      return;

    $alertype = '';
    $thediv = '';
    switch ( $level )
    {
      case 0: $alertype = 'alert-success-element';      break;
      case 1: $alertype = 'alert-info-element';         break;
      case 2: $alertype = 'alert-warning-element';      break;
      case 3: $alertype = 'alert-danger-element';       break;
    }
    
    $globalalert[$level]++;

    $thediv  =  '<tr>';
    $thediv .=    '<td>';
    $thediv .=        $string;
    $thediv .=    '</td>';
    $thediv .=  '</tr>';

    return $thediv;
  }


  function create_card ( $nameid )
  {
    global $dashboard_alert_req;
    global $config_servernameorip;
    global $EOQUAL_FOLDER;

    global $_IncidentReporting;
    global $_Staff;
    global $_Audit;
    global $_DeviceInspection;
    global $_DeviceMaintenance;
    global $_Task;
    global $_MyTask;
    global $_Dosimetry;


    $_IncidentReporting   = "Incident";
    $_Staff               = "Ressources humaines";
    $_DeviceInspection    = "Plateau technique (inspection)";
    $_DeviceMaintenance   = "Plateau technique (maintenance)";
    $_Audit               = "Audit";
    $_Task                = "Tâches planifiées";
    $_MyTask              = "Mes tâches planifiées";
    $_Dosimetry           = "Dosimétrie";
    $_MyDocToRead         = "Documents à lire";
    $_MyDocToValidate     = "Documents à valider";
    $_MyDocToRead         = "Documents à lire";
    $_DocToValidate       = "Etat des validations de documents";
    $_DocToRead           = "Etat des lectures de documents";


    $carddanger     = 'ximeo_bg_danger';
    $icondanger     = 'fa-exclamation-triangle';

    $cardwarning    = 'ximeo_bg_warning';
    $iconwarning    = 'fa-exclamation-circle';

    $alertinfo      = 'ximeo_bg_info';
    $iconalertinfo  = 'fa-info-circle';

    $cardsuccess    = 'ximeo_bg_success';
    $iconsuccess    = 'fa-check-circle';

    $cardcontent    = '';
    $cardtitle      ='';
    $validalert     = true;
    $maxseverity    = 0;
    $nalert         = 0;

    $cardIdent      = "";

    switch ( $nameid )
    {
        case 'incidentreporting':
            if($_SESSION['view'][VIEW_INCIDENTREPORTING] == '0')
                return;

            $conn = get_dbconnection();
            $sql = $dashboard_alert_req[$nameid];

            if ($query = pg_query($conn,$sql))
            {
                if(($row = pg_fetch_row($query)))
                {
                    $nalert++;
                    if($maxseverity < $row[1])
                        $maxseverity = $row[1];

                    $text = 'An incident '.$row[0].'  has been opened ('.$row[2].').';
                    $cardcontent.=create_alert($row[1],$text,'onclick="loadpage(\'VIEW_INCIDENTREPORTING\')"', '');
                    while(($row = pg_fetch_row($query)))
                    {
                        $nalert++;
                        if($maxseverity < $row[1])
                            $maxseverity = $row[1];
                        $text = 'An incident '.$row[0].'  has been opened ('.$row[2].').';
                        $cardcontent.=create_alert($row[1],$text,'onclick="loadpage(\'VIEW_INCIDENTREPORTING\')"', '');
                    }
                }
            }

            $cardtitle =  $_IncidentReporting.' ('.$nalert.')';
            $cardIdent = 'Reporting';
            break;

        case 'staff':
            if($_SESSION['view'][VIEW_STAFF] == '0')
                return;

            $conn = get_dbconnection();
            $sql = $dashboard_alert_req[$nameid];

            if ($query = pg_query($conn,$sql))
            {
                if(($row = pg_fetch_row($query)))
                {
                    $nalert++;
                    if($maxseverity < $row[1])
                        $maxseverity = $row[1];
                    $text = $row[0].' : Training '.$row[3].' planned for '.$row[2]. '.';
                    $cardcontent.=create_alert($row[1],$text,'onclick="SelectPage(\'VIEW_STAFF\')"', '');
                    while(($row = pg_fetch_row($query)))
                    {
                        $nalert++;
                        if($maxseverity < $row[1])
                          $maxseverity = $row[1];
                        $text = $row[0].' : Training '.$row[3].' planned for '.$row[2]. '.';
                        $cardcontent.=create_alert($row[1],$text,'onclick="SelectPage(\'VIEW_STAFF\')"', '');
                    }
                }
            }

            $cardtitle =  $_Staff.' ('.$nalert.')';
            $cardIdent = 'Staff';
            break;
    
        case 'audit':
            if($_SESSION['view'][VIEW_AUDIT] == '0')
                return ;
            $conn = get_dbconnection();
            $sql = $dashboard_alert_req[$nameid];

            if ($query = pg_query($conn,$sql))
            {
                if(($row = pg_fetch_row($query)))
                {
                    $nalert++;
                    if($maxseverity < $row[1])
                        $maxseverity = $row[1];
                    $text = 'Audit '.$row[0].' planned for '.$row[2]. '.';
                    $cardcontent.=create_alert($row[1],$text,'onclick="SelectPage(\'VIEW_AUDIT\')"', '');
                    while(($row = pg_fetch_row($query)))
                    {
                        $nalert++;
                        if($maxseverity < $row[1])
                            $maxseverity = $row[1];
                        $text = 'Audit '.$row[0].' planned for '.$row[2]. '.';
                        $cardcontent.=create_alert($row[1],$text,'onclick="SelectPage(\'VIEW_AUDIT\')"', '');
                    }
                }
            }
            $cardtitle =  $_Audit.' ('.$nalert.')';
            $cardIdent = 'Audit';
            break;
    
        case 'device_inspection':
            if($_SESSION['view'][VIEW_DEVICE] == '0')
                return ;
            $conn = get_dbconnection();
            $sql = $dashboard_alert_req[$nameid];
            if ($query = pg_query($conn,$sql))
            {
                if(($row = pg_fetch_row($query)))
                {
                    $nalert++;
                    if($maxseverity < $row[1])
                        $maxseverity = $row[1];
                    $text = 'An inspection on '.$row[0].' is planned for '.$row[2].'.';
                    $cardcontent.=create_alert($row[1],$text,'onclick="SelectPage(\'VIEW_DEVICE\')"', '');
                    while(($row = pg_fetch_row($query)))
                    {
                        $nalert++;
                        if($maxseverity < $row[1])
                            $maxseverity = $row[1];
                        $text = 'An inspection on '.$row[0].' is planned for '.$row[2].'.';
                        $cardcontent.=create_alert($row[1],$text,'onclick="SelectPage(\'VIEW_DEVICE\')"', '');
                    }
                }
            }
            $cardtitle =  $_DeviceInspection.' ('.$nalert.')';
            $cardIdent = 'DeviceInspection';
            break;

        case 'device_maintenance':
            if($_SESSION['view'][VIEW_DEVICE] == '0')
                return ;
            $conn = get_dbconnection();
            $sql = $dashboard_alert_req[$nameid];

            if ($query = pg_query($conn,$sql))
            {
                if(($row = pg_fetch_row($query)))
                {
                    $nalert++;
                    if($maxseverity < $row[1])
                        $maxseverity = $row[1];
                    $text = 'A maintenance on '.$row[0].' is planned for '.$row[2].'.';
                    $cardcontent.=create_alert($row[1],$text,'onclick="SelectPage(\'VIEW_DEVICE\')"', '');
                    while(($row = pg_fetch_row($query)))
                    {
                        $nalert++;
                        if($maxseverity < $row[1])
                            $maxseverity = $row[1];
                        $text = 'A maintenance on '.$row[0].' is planned for '.$row[2].'.';
                        $cardcontent.=create_alert($row[1],$text,'onclick="SelectPage(\'VIEW_DEVICE\')"', '');
                    }
                }
            }
            $cardtitle =  $_DeviceMaintenance.' ('.$nalert.')';
            $cardIdent = 'DeviceMaintenance';
            break;
    
        /*
        case 'scheduledtask':
            if ( $_SESSION['view'][VIEW_SCHEDULEDTASK] == '0' )
                return ;
            $sql = $dashboard_alert_req[$nameid];

            $pdo = getPDO ();

            $s0 = $pdo->prepare ( $sql );
            if ( $s0->execute () )
            {
                $d0 = $s0->fetchAll ( PDO::FETCH_ASSOC );
                $first=0;
                foreach ( $d0 as $data )
                {
                    $nalert++;
                    if ( $maxseverity < $data['level'])
                        $maxseverity = $data['level'];
                    $text = '<span class="m-0 p-0 fw-bold">'.$data['title'].'</span><span class="m-0 p-O fw-normal"> par '.$data['staff_member'].'</span><span class="m-0 p-0 ps-2">Echéance : '.$data['due_date_fmt'].'</span>';
                    $cardcontent.=create_alert($row[1],$text,'onclick="SelectPage(\'VIEW_SCHEDULED_TASK\')"', '');

                  $first++;
                }
            }

            $cardtitle =  $_Task.' ('.$nalert.')';
            $cardIdent = 'Task';
            break;

        
        case 'scheduledtaskworking':
            if ( $_SESSION['view'][VIEW_SCHEDULEDTASK_WORKING] == '0')
                return ;
            $sql = $dashboard_alert_req[$nameid];

            $pdo = getPDO ();

            $s0 = $pdo->prepare ( $sql );
            if ( $s0->execute () )
            {
                $d0 = $s0->fetchAll ( PDO::FETCH_ASSOC );
                $first=0;
                foreach ( $d0 as $data )
                {
                    $nalert++;
                    if ( $maxseverity < $data['level'])
                        $maxseverity = $data['level'];
                    $text = '<span class="m-0 p-0 fw-bold">'.$data['title'].'</span><span class="m-0 p-0 ps-2">Echéance : '.$data['due_date_fmt'].'</span>';
                    $cardcontent.=create_alert($row[1],$text,'onclick="SelectPage(\'VIEW_SCHEDULED_TASK\')"', '');

                  $first++;
                }
            }

            $cardtitle =  $_MyTask.' ('.$nalert.')';
            $cardIdent = 'MyTask';
            break;

        
        */

        case 'scheduledtask':
            $cardIdent = 'Task';
            DashTask ( $nameid, 1, -1, $cardcontent, $cardtitle, $nalert, $maxseverity, $_Task );
            break;

        case 'scheduledtaskworking':
            $cardIdent = 'MyTask';
            DashTask ( $nameid, 1, $_SESSION['id'], $cardcontent, $cardtitle, $nalert, $maxseverity, $_MyTask );
            break;

        case 'dosimetry':
            if($_SESSION['view'][VIEW_DOSIMETRY] == '0')
                return ;
      
            $conn = get_dbconnection();

            $sql = $dashboard_alert_req[$nameid];

            if ($query = pg_query($conn,$sql))
            {
                if(($row = pg_fetch_row($query)))
                {
                    $nalert++;

                    if($maxseverity < $row[1])
                        $maxseverity = $row[1];

                    $text = 'Report to send for "'.$row[0].'" before '.$row[2].'.';
                    $cardcontent.=create_alert($row[1],$text,'onclick="SelectPage(\'VIEW_DOSIMETRY\')"', '');
                    while(($row = pg_fetch_row($query)))
                    {
                        $nalert++;
                        if($maxseverity < $row[1])
                            $maxseverity = $row[1];

                        $text = 'Report to send for "'.$row[0].'" before '.$row[2].'.';
                        $cardcontent.=create_alert($row[1],$text,'onclick="SelectPage(\'VIEW_DOSIMETRY\')"', '');
                    }
                }
            }
            $cardtitle =  $_Dosimetry.' ('.$nalert.')';
            $cardIdent = 'Dosimetry';
            break;
    
        case 'mydocumenttoread':
            $cardIdent = 'MyDocumentToRead';
            DashDocument ( $nameid, 1, $_SESSION['id'], $cardcontent, $cardtitle, $nalert, $maxseverity, $_MyDocToRead );
            break;

        case 'mydocumenttovalidate':
            $cardIdent = 'MyDocumentToValidate';
            DashDocument ( $nameid, 1, $_SESSION['id'], $cardcontent, $cardtitle, $nalert, $maxseverity, $_MyDocToValidate );
            break;

        case 'documenttovalidate':
            $cardIdent = 'DocumentToValidate';
            DashDocument ( $nameid, 1, -1, $cardcontent, $cardtitle, $nalert, $maxseverity, $_DocToValidate );
            break;

        case 'documenttoread':
            $cardIdent = 'DocumentToRead';
            DashDocument ( $nameid, 0, -1, $cardcontent, $cardtitle, $nalert, $maxseverity, $_DocToRead );
            break;
    }


    switch ( $maxseverity )
    {
        case 0:
          $ntypecard = $cardsuccess;
          $ntypeicon = $iconsuccess;
          break;
      
      case 1:
          $ntypecard = $alertinfo;
          $ntypeicon = $iconalertinfo;
          break;
      
      case 2:
          $ntypecard = $cardwarning;
          $ntypeicon = $iconwarning;
          break;
      
      case 3:
          $ntypecard = $carddanger;
          $ntypeicon = $icondanger;
          break;
    }


    if ( $validalert == true )
    {
        ?>
            
            <div class="row m-0 p-0 mb-3">
          
              <div class="accordion rounded-top-3 p-0">
                <div class="accordion-item rounded-top-3">
                    <button class="accordion-button collapsed rounded-top-3 fs-4 <?php echo $ntypecard; ?>" type="button" data-bs-toggle="collapse" data-bs-target="#<?php echo $cardIdent; ?>" aria-expanded="false" aria-controls="collapseOne">
                            <div class="row w-100 h-100 m-0 p-0">
                                <div class="col-md-auto">
                                  <div class="card-body-icon-1">
                                    <i class="fas fa-fw <?php echo $ntypeicon;?>"></i>
                                  </div>
                                </div>
                                <div class="col">
                                  <?php echo $cardtitle;?>
                                </div>
                              </div>
                    </button>
                        
                    <div id="<?php echo $cardIdent; ?>" class="accordion-collapse collapse" data-bs-parent="#accordionExample">
                      <div class="accordion-body">
                        <table class="w-100">
                          <tbody>
                            <?php echo $cardcontent; ?>
                          </tbody>
                        </table>
                      </div>
                    </div>
                </div>
              </div>
            </div>

        <?php
      }
  }

 ?>
<!DOCTYPE html>
<html lang="en">

<head>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">



  

  <!-- <script src="<?php echo $EOQUAL_ROOT;?>/js/jquery/jquery.min.js"></script> -->

  <!-- Core plugin JavaScript-->
  <!-- <script src="<?php echo $EOQUAL_ROOT;?>/js/jquery-easing/jquery.easing.min.js"></script> -->
  <!-- Custom styles for this template-->


  <!-- <script type="text/javascript" src="js/jquery/jquery.js"></script> -->


  <?php
      // $libmanager = new eoLibrariesManager ($GLOBALS['approot']);
      $libmanager = new eoLibrariesManager ();
      // $libmanager = new eoLibrariesManager ($GLOBALS);
      $libmanager->init_page();
      $libmanager->render_library ();
    ?>

  <style>

  

  div#layout {
   position: absolute;
   margin:0 auto;
    overflow: hidden;
   width: 100%;
   height: 100%;
 }
 .divider
{
 position: relative;

 height: 5px;
}



 #drltable, #newmodident,#tasyncdl{
   font-family: 'Trebuchet MS', Arial, Helvetica, sans-serif;
   border-collapse: collapse;
   width: 100%;
 }
 #drltable tr:nth-child(even), #newmodident tr:nth-child(even),#tasyncdl tr:nth-child(even){
   background-color: #f2f2f2;

 }
 #drltable tr:hover,#newmodident tr:hover,#tasyncdl tr:hover {
   background-color: #ddd;
 }
 #drltable tr>td:hover {
   cursor: pointer;
 }

 #drltable th,#newmodident th,#tasyncdl th {
      padding-top: 12px;
      padding-bottom: 12px;
      text-align: left;
      background-color: rgba(52, 56, 62, 0.86);
      font-weight: normal;
      color:white;
 }

 .t-group
 {
   overflow-y: auto;
   max-height: 325px;
   min-width: 250px;
   width: auto;
   padding: 0.75rem 1.25rem;
   background-color: #fafafa;
   border: 1px solid #dfdfdf;
   border-radius: 0.25rem;
   margin: 7px 7px 7px 7px;
 }

 .header-alert, .header-warning, .header-info
 {
   background-color: #fff; */
   border: 0px solid !important;
   border-radius: .25rem;
   background-color: #fafafa;
   border: 1px solid #dfdfdf;
   border-radius: 0.25rem;
   margin: 7px 7px 7px 7px;
 }

 .header-alert
 {
   background-color: #f8d7da;
   border-color: #f5c6cb;
 }

 .header-warning
 {
   background-color: #fff3cd;
   border-color: #ffeeba;
 }

 .header-info
 {
   background-color: #d1ecf1;;
   border-color: #bee5eb;
 }

 .nocardborder
 {
   border: 0px solid !important;
 }

 hr.sep{
  height: 15px;
  border-style: solid;
  border-color: #8c8b8b;
  border-width: 1px 0 0 0;
}



</style>

<script>

<?php create_translate_xml_js_function(); ?>

var myTabbar;
var studyframe;
var serieframe;
/*
var myLayout;

function init_layout(){
   myLayout = new dhtmlXLayoutObject(layout, '1C');

   var a = myLayout.cells('a');
   a.attachObject('layoutcontent');
   a.hideHeader();
   a.showInnerScroll();

   window.myLayout = myLayout;
   alert('init');
 }
 */

</script>
</head>

<body>
  <div class="w-100 h-100 m-0 p-0">
    <div class="container-fluid m-0 p-0 w-100 h-100">
      <div class="h-100 d-flex flex-column m-0 p-0 w-100">

        <div class="row w-100 m-0 p-0">  
          <div class="ximeo_caption w-100 m-0 ps-2 pe-2 pt-2 pb-2" >
            <div class="row w-100 m-0 p-0">
              <div class="col m-0 p-0" style="min-height: 25px;">
                <span data-langkey="Dash board">Tableau de bord</span>
              </div>
                  
            </div>
          </div>
        </div>
            
        <div class="row flex-grow-1 w-100 m-0 p-2 bg-white" style="min-height: 0px;">
          <div class="container-fluid m-0 p-0 w-100 h-100">
            <div class="h-100 d-flex flex-column m-0 p-0 w-100">

              <div class="row m-0 p-0">
                <div class="col-auto m-0 p-0 pt-2 pb-2 ps-1 pe-3">
                  <canvas id="IdcDashboardChartCanvas" style="object-fit: contain; max-width: 120px; max-height: 120px; width: auto; height: auto;"></canvas>
                </div>

                <div class="col header-alert m-2 ms-0">
                  <?php
                      $arraysql = array();

                      if($_SESSION['view'][VIEW_DOSIMETRY] == '1')
                      {
                          $arraysql[] = $dashboard_alert_req['dosimetry'];
                      }

                      if($_SESSION['view'][VIEW_SCHEDULEDTASK] == '1')
                      {
                          $arraysql[] = $dashboard_alert_req['scheduledtask'];
                      }

                      if($_SESSION['view'][VIEW_SCHEDULEDTASK_WORKING] == '1')
                      {
                          $arraysql[] = $dashboard_alert_req['scheduledtaskworking'];
                      }

                      if($_SESSION['view'][VIEW_DEVICE] == '1')
                      {
                          $arraysql[] =  $dashboard_alert_req['device_inspection'];
                          $arraysql[] =  $dashboard_alert_req['device_maintenance'];
                      }

                      if($_SESSION['view'][VIEW_AUDIT] == '1')
                      {
                          $arraysql[] =  $dashboard_alert_req['audit'];
                      }

                      if($_SESSION['view'][VIEW_STAFF] == '1')
                      {
                          $arraysql[] =  $dashboard_alert_req['staff'];
                      }

                      if($_SESSION['view'][VIEW_INCIDENTREPORTING] == '1')
                      {
                          $arraysql[] =  $dashboard_alert_req['incidentreporting'];
                      }

                      global $globalalert;
                      $arr[3] = $globalalert[3];
                      $arr[2] = $globalalert[2];
                      $arr[1] = $globalalert[1];
                  ?>

                  <div class="card nocardborder text-dark fs-4 o-hidden h-100">
                    <div class="card-body ximeo_bg_danger">
                      <div class="card-body-icon"> <i class="fas fa-fw fa-exclamation-circle"></i>   
                      </div>
                      <div class="mr-5 ximeo_bg_danger" id="countalert">
                      </div>
                    </div>
                  </div>
                </div>

                <div class="col header-warning">
                  <div class="card nocardborder text-dark fs-4 o-hidden h-100">
                    <div class="card-body ximeo_bg_warning">
                      <div class="card-body-icon"> <i class="fas fa-fw fa-exclamation-triangle"></i> </div>
                      <div class="mr-5" id="countwarning"></div>
                    </div>
                  </div>
                </div>

                <div class="col header-info">
                  <div class="card nocardborder text-dark fs-4 o-hidden h-100">
                    <div class="card-body ximeo_bg_info">
                      <div class="card-body-icon"> <i class="fas fa-fw fa-info-circle"></i></div>
                      <div class="mr-5" id="countinfo"></div>
                    </div>
                  </div>
                </div>
              </div>
            
              <!-- <hr class='sep' /> -->
    
              <div class="row flex-grow-1 w-100 m-0 p-0 pt-4 border-top" style="min-height: 0px;">
              <!-- <div class="w-100 h-100 bg-warning"> -->

                <div class="container h-100 w-100 m-0 p-0">
                      
                  <div class="d-flex flex-column w-100 h-100 m-0 p-0">

                    <div class="row w-100 h-100 m-0 p-0 pt-4 border-top" style="overflow-y: auto;">

                      <div class="col w-100 h-100 m-0 p-0 pe-3">
                        <?php 
                          create_card('incidentreporting');
                          create_card('audit');
                          create_card('device_inspection');
                          create_card('scheduledtask');
                          create_card('scheduledtaskworking');
                          create_card('mydocumenttoread');
                          create_card('mydocumenttovalidate'); 
                        ?>
                      </div>
                      <div class="col w-100 h-100 m-0 p-0 ps-3">
                        <?php 
                          create_card('staff');
                          create_card('device_maintenance');
                          create_card('dosimetry');
                          create_card('documenttovalidate');
                          create_card('documenttoread'); 
                        ?>
                      </div>
                    </div>
                  </div>
              <!-- </div> -->
                </div>

              </div>
            </div>
          </div>

        </div>
      </div>
    </div>
  </div>

  <script>
    let nbAlert   = parseInt ( <?php echo $globalalert[3]; ?> );
    let nbWarning = parseInt ( <?php echo $globalalert[2]; ?> );
    let nbInfo    = parseInt ( <?php echo $globalalert[1]; ?> );
  
    let alertMsg    = ( nbAlert > 1)? nbAlert + ' ' + Translate('Alerts') : nbAlert + ' ' + Translate('Alert');
    let warningMsg  = ( nbWarning > 1)? nbWarning + ' ' + Translate('Warnings') : nbWarning + ' ' + Translate('Warning');
    let infoMsg     = ( nbInfo > 1)? nbInfo + ' ' + Translate('Informations') : nbInfo + ' ' + Translate('Information');
  
    document.getElementById('countalert').innerHTML = alertMsg;
    document.getElementById('countwarning').innerHTML = warningMsg;
    document.getElementById('countinfo').innerHTML = infoMsg;

    window.ToggleDiv = function(_div) {
      if (_div.style.display === "none") 
      {
        _div.style.display = "block";
        _div.parentNode.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'end' });
      } 
      else 
      {
        _div.style.display = "none";
      }
    }

    if (typeof resizeLayout !== "function") 
    {
      if (window.attachEvent)
        window.attachEvent("onresize",resizeLayout);
      else
        window.addEventListener("resize",resizeLayout, false);

      var t;

      function resizeLayout()
      {
          window.clearTimeout(t);
          t = window.setTimeout(function(){
            if(myLayout != null)
            {
              // target.style.width = contentw.offsetWidth;
              // target.style.height = contentw.offsetHeight;

              myLayout.setSizes(false);

              //myTabbar.
            }
          },200);
      }
    }

    let datas = new Array();
    datas.push ( nbAlert );
    datas.push ( nbWarning );
    datas.push ( nbInfo );

    const dataCfg = {
      labels: [Translate('Alert'), Translate('Warning'), Translate('Information')],
      datasets: [
          {
            data: datas,
            backgroundColor: [ '#F8D7DA', '#FFF3CD', '#D1ECF1']
          }
        ]
    };

    const config = {
      type: 'pie',
      data: dataCfg,
      options: { responsive: true, legend: {display: false} }
    };
    dashChart = new Chart ( document.getElementById('IdcDashboardChartCanvas'), config );
  </script>

</body>
</html>
