 <?php


   include 'SubFW/autoload.php';



    $GLOBALS['nbalert']   = 0;
    $GLOBALS['nbwarning'] = 0;
    $GLOBALS['nbsuccess'] = 0;

   function create_js($nameid)
   {

     switch($nameid){
       case 'alertmodstate':
       ?>
       <script>
       $('tr.modalitystate').click(function() {
           var id = this.id;
           var modid = id.split('-')[0];

           var modname = $(this).find('td.modalityname').text();

           window.location.href = 'index.php?pageid=institutionsetting&modname=' + encodeURIComponent(modname);
       }); $('tr.modalitystate').addClass('clickable');
      </script>

       <?php
       break;
       default :
     }
   }

   function create_card ( $nameid )
   {

      global $config_servernameorip;
      global $EODACS_FOLDER;

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

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

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


      $cardcontent = '';
      $cardtitle='';
      $validalert = false;

      if($nameid == 'alertnrdpatientcumulate')
      {
        $conn = get_dbconnection();
        $validalert = true;
        $table = '';
        $nalert =  '0';
        $ntypecard = $carddanger;
        $ntypeicon = $icondanger;
        $exceedvalue = '0';

       if($conn)
       {
          $sql ="select count(*),'<table id=''alertpatient''><tr><th>Last exam date</th><th>ID</th><th>Patient</th><th>Alert name</th><th>Value</th>'||string_agg(trrow,'')||'</table>'
          from(select '<tr ondblclick=\"show_patientdosimetrybystuID('''||stu_id||''')\"><td>'||to_char(studydate,'DD/MM/YYYY')||'</td><td>'||patientid||'</td><td>'||patientname||'</td><td>'|| alert_name || ' (&ge;'||value||' '|| unit ||')</td><td>'||value || ' ' || unit ||'</td></tr>' as trrow
          from v_alertwarninginfo where ack_id is null and removed = false and pat_id != -1 and  studydate >= {$GLOBALS['dashboard_alertpatient_periodtime']} order by studydate desc) as alert;";

         
          if($query=pg_query($conn,$sql))
          {
              if($row = pg_fetch_row($query))
              {
                  $nalert = $row[0];
                  $cardcontent = $row[1];
                  $exceedvalue = $row[2];
              }
          }
       }
       
       $cardtitle = $nalert." Patient alert within the last {$GLOBALS['dashboard_alertpatient_periodday']} days";
       if($nalert != '0')
       {
         $ntypecard = $carddanger;
         $ntypeicon = $icondanger;
         $GLOBALS['nbalert'] += $nalert;
       
       }
       else
       {
         $ntypecard = $cardsuccess;
         $ntypeicon = $iconsuccess;
       }
     }
     else if($nameid == 'alertnrd')
     {
       $conn = get_dbconnection();
       $validalert = true;
       $table = '';
       $nalert =  '0';
       $ntypecard = $carddanger;
       $ntypeicon = $icondanger;
       $exceedvalue = '0';

       if($conn)
       {
          



         $sql ="select array_length(regexp_split_to_array(nrdtable, E'show_studyalert'), 1)-1,nrdtable,exceedvalue from(select f_get_mailbody_alertnrd({$GLOBALS['dashboard_alert_periodtime']},now(),exceedvalue::numeric,'{".$_SESSION['filter_modalitylist']."}') as nrdtable,exceedvalue from alertmail where type = 'NRDALERT') as alert";

         if($query=pg_query($conn,$sql))
         {
           if($row = pg_fetch_row($query))
           {
             $nalert = $row[0];
             $cardcontent = $row[1];
             $exceedvalue = $row[2];
           }
         }
       }
       $cardtitle = $nalert." DRL alert within the last {$GLOBALS['dashboard_alert_periodday']} days (threshold = {$exceedvalue}%)";
       if($nalert != '0')
       {
         $ntypecard = $carddanger;
         $ntypeicon = $icondanger;
         $GLOBALS['nbalert'] += $nalert;
         
       }
       else
       {
         $ntypecard = $cardsuccess;
         $ntypeicon = $iconsuccess;
       }
     }
     else if($nameid == 'asyncdl')
      {
          $conn = get_dbconnection();

          $table = '';
          $nalert =  '0';
          $ntypecard = $cardsuccess;
          $ntypeicon = $iconsuccess;

          if($conn)
          {
              $sql ="select count(*),'<table id=''tasyncdl''><tr><th>Date</th><th>File</th><th>Link</th>'||string_agg(trrow,'')||'</table>' from
              (select '<tr><td>'||to_char(created_at,'DD/MM/YYYY HH24:MI')||'</td><td>'||linked_file||'</td><td>'||'<a href=\"".$config_servernameorip.$EODACS_FOLDER."/eoDACSCommon/async_download.php?id='||md5(ad_id||'''hash''')||'\" download><i class=\"fa fa-download\" style=\"font-size:36px\"></i></a>'||'</td>' as trrow from async_download where visible = true and created_at + interval '3 day' >= now() and account_id = ".$_SESSION['id']." order by created_at desc) as asyncdl;";

              if($query=pg_query($conn,$sql))
              {
                  if($row = pg_fetch_row($query))
                  {
                      $nalert = $row[0];

                      if($nalert != '0')
                      {
                          $validalert = true;
                          $GLOBALS['nbalert'] += $nalert;
                          
                      }

                      $cardcontent = $row[1];
                  }
              }
          }
          if($validalert == true)
          {
              $cardtitle = $nalert." download ready";
          }
      } 
      else if($nameid == 'alertmodstate')
      {
          $path = "/SubFW/database/alertutils/db_modalitystate.php";
          $ret = get_filecontent($path);
          $row = json_decode($ret,true);
          $table = '';
          $nalert =  '0';
          $ntypecard = $carddanger;
          $ntypeicon = $icondanger;
          if(!empty($row) && $row['error'] == 0)
          {
              $nalert = $row['numberofalert'];

              if($nalert != '0')
              {
                  $validalert = true;
                  $GLOBALS['nbalert'] += $nalert;
                  
              }

              $cardcontent = $row['alerttable'];
          }
          if($validalert == true)
          {
              $cardtitle = $nalert." modalitie(s) have not been integrated for severals days";
          }
      }
      else if($nameid == 'alertmodident')
      {
          $conn = get_dbconnection();

          $table = '';
          $nalert =  '0';
          $ntypecard = $cardwarning;
          $ntypeicon = $iconwarning;

          if($conn)
          {
              $sql ="select count(*),'<table id=''newmodident''><tr><th>ID</th><th>Device Serial or UID</th><th>Station Name</th><th>Station AET</th><th>Performed Station Name</th><th>Performed Station AET</th><th>Manufacturer</th><th>Manufacturer model</th>'||string_agg(trrow,'')||'</table>'
                from(select '<tr><td>'||mi.modident_id||'</td><td>'||mi.device_uid||'</td><td>'||mi.stationname||'</td><td>'||mi.stationaet||'</td><td>'||mi.performedstationname||'</td><td>'||mi.performedstationaet||'</td><td>'||mi.manufacturer||'</td><td>'||mi.manufacturermodel||'</td>' as trrow from modality_identity mi where status = 0) as alert;";
              if($query=pg_query($conn,$sql))
              {
                  if($row = pg_fetch_row($query))
                  {
                      $nalert = $row[0];

                      if($nalert != '0')
                      {
                        $validalert = true;
                        $GLOBALS['nbalert'] += $nalert;
                        
                      }

                      $cardcontent = $row[1];
                  }
              }
          }
          if($validalert == true)
          {
              $cardtitle = $nalert." modality identity waiting to be configured";
          }
      }
      else if($nameid == 'alertlicence')
      {
          $nmodality = get_number_of_modality();
          $_SESSION[LICENCE_ACTIVE_MODALITY] = get_number_of_modality();

          if($nmodality > $_SESSION[LICENCE_MAXMODALITY])
          {
              $ntypecard = $carddanger;
              $ntypeicon = $icondanger;
              if($nmodality == 1+$_SESSION[LICENCE_MAXMODALITY])
              {
                  $ntypecard = $cardwarning;
                  $ntypeicon = $iconwarning;
                  $GLOBALS['bwarning'] += 1;
              }
              $validalert = true;
              $cardcontent = '<div></div>';
          }

          if($validalert == true)
          {
              $cardtitle = 'Licence alert: '. $nmodality.'/'.$_SESSION[LICENCE_MAXMODALITY].' modalities.';
          }
     }

     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 $nameid; ?>" 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 $nameid; ?>" class="accordion-collapse collapse" data-bs-parent="#accordionExample">
                      <div class="accordion-body overflow-auto"  style="max-height: 200px !important;">
                        <?php echo $cardcontent; ?>
                      </div>
                    </div>
                </div>
            </div>
        </div>

        <?php create_js($nameid); ?>
            <div class="divider div-transparent"></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="">
   <link rel="shortcut icon" type="image/x-icon" href="<?=$GLOBALS['approot']?>/eoDACSCommon/pics/eodacs.png" />
   
   <title>eoDACS</title>


  <style>
  </style>
	   <?php   	
	$libmanager = new eoLibrariesManagerDACS();
	$libmanager->init_page();
	$libmanager->render_library();
?>
  <script>

 <?php create_translate_xml_js_function(); ?>


 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;
  }

 </script>
 </head>

 <body>
    <!--
    <div class="w-100 h-100 m-0 p-0 bg-warning">
      <div class="container-fluid w-100 h-100 m-0 p-0 pe-4">
      -->
      <?php
      /*
        create_card('alertnrdpatientcumulate');
        create_card('alertnrd');
        if($_SESSION['role'] >= "1")
        {
          create_card('alertmodstate');
          create_card('alertmodident');
          create_card('alertlicence');
        }
        create_card('asyncdl');
      */
      ?>
      <!--
      </div>
    </div>
  -->


    <div id="IdcDashboard" class="w-100 h-100 m-0 p-0" data-alertperiod="<?php echo htmlspecialchars($GLOBALS['dashboard_alert_periodday']); ?>">
        <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="Dashboard">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">
                                    <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 m-2 ms-0">
                                    <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"><?php echo $arr[2].' '. $_Warning;?></div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col header-success m-2 ms-0">
                                    <div class="card nocardborder text-dark fs-4 o-hidden h-100">
                                        <div class="card-body ximeo_bg_success">
                                            <div class="card-body-icon"> <i class="fas fa-fw fa-info-circle"></i> </div>
                                            <div class="mr-5" id="countsuccess"><?php echo $arr[2].' '. $_Success;?></div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="row flex-grow-1 w-100 m-0 p-0 pt-4 border-top" style="min-height: 0px;">
                                <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" style="overflow-y: auto;">

                                            <div class="col w-100 h-100 m-0 p-0 pe-3">

                                              <?php
                                                create_card('alertnrdpatientcumulate');
                                                create_card('alertnrd');
                                              ?>
                                            </div>

                                            <div class="col w-100 h-100 m-0 p-0 pe-3">

                                              <?php
                                                if($_SESSION['role'] >= "1")
                                                {
                                                    create_card('alertmodstate');
                                                    create_card('alertmodident');
                                                    create_card('alertlicence');
                                                }
                                                create_card('asyncdl');
                                              ?>
                                            </div>

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

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


                

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

 <script>
    WaitingStop ();
    
    
    var nbAlert   = parseInt ( <?php echo $GLOBALS['nbalert']; ?> );
    var nbWarning = parseInt ( <?php echo $GLOBALS['nbwarning']; ?> );
    var nbInfo    = parseInt ( <?php echo $GLOBALS['nbsuccess']; ?> );
  
    var alertMsg    = ( nbAlert > 1)? nbAlert + ' ' + Translate('Alerts') : nbAlert + ' ' + Translate('Alert');
    var warningMsg  = ( nbWarning > 1)? nbWarning + ' ' + Translate('Warnings') : nbWarning + ' ' + Translate('Warning');
    var infoMsg     = ( nbInfo > 1)? nbInfo + ' ' + Translate('Informations') : nbInfo + ' ' + Translate('Information');
  
    document.getElementById('countalert').innerHTML = alertMsg;
    document.getElementById('countwarning').innerHTML = warningMsg;
    document.getElementById('countsuccess').innerHTML = infoMsg;

    

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

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

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

    
    switchLanguage (eoDACS.CurrentLanguage);

    /*
    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);
                }
   	        },200);
        }
    }
    */
  </script>

 </body>

 </html>
