<?php
/*ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);*/
function toTime($value, $fromSeconds = false){
    if($value){
        $totalSeconds = $fromSeconds ? $value : ($value * 60);
        $hours = (int) floor($totalSeconds / 3600);
        $minutes = (int) floor(($totalSeconds - ($hours*3600))/60);
        $minutes = str_pad($minutes,2,"0",STR_PAD_LEFT);
        $seconds = (int) $totalSeconds - ($hours*3600 + $minutes*60);
        $seconds = str_pad($seconds,2,"0",STR_PAD_LEFT);
        $hours = $hours ? (str_pad($hours,2,"0",STR_PAD_LEFT).":") : "";
        return $hours.$minutes.":".$seconds;
    }
    return "00:00";
}

function toTimeForChart($value, $fromSeconds = false){
    if($value){
        $totalSeconds = $fromSeconds ? $value : ($value * 60);
        $hours = (int) floor($totalSeconds / 3600);
        $hours = str_pad($hours,2,"0",STR_PAD_LEFT);
        $minutes = (int) floor(($totalSeconds - ($hours*3600))/60);
        $minutes = str_pad($minutes,2,"0",STR_PAD_LEFT);
        $seconds = (int) $totalSeconds - ($hours*3600 + $minutes*60);
        $seconds = str_pad($seconds,2,"0",STR_PAD_LEFT);
        if($totalSeconds >= 3600){
            $duration = array($hours,$minutes,$seconds);
        }else{
            $duration = array($minutes,$seconds);
        }
        return implode(':', $duration);
    }
    return "00:00";
}


setlocale(LC_TIME, 'fr_FR.utf8', 'fra');

session_start();
if (!isset($_SESSION['auth'])) {
    header("location:index.php");
}
// print_r($_SESSION);
require_once("../inc/confNetisse.php");
$locale = 'fr_FR.UTF-8';
setlocale(LC_ALL, $locale);

$table = 'ca_statistiques';

$daysagoQ = "";

if (isset($_SESSION['profiles'])) {
    // GET PROFILE IDs FROM PROFILE NAMES IN RETURNED XML
    $profiles = "";
    //print "<pre>"; print_r($_SESSION['profiles']);print "</pre>";
    foreach ($_SESSION['profiles'] as $value) {
        $q = "SELECT id_profil FROM ca_profils WHERE nom = :nom";
        $values = [':nom' => $value];
        $result = excuteQuery($q, $values);
        if ($result['status']) {
            $r = $result['stmt'];
            $id_profil = $r->fetch( PDO::FETCH_ASSOC )['id_profil']; 
            $profiles .= $id_profil . ',';
        }else{
             wts_die($stmt->error);
        }
    }
    $profiles = rtrim($profiles, ',');

    // CONSTRUCT THE PERMISSIONS ARRAY
    $query = "SELECT type_permission FROM ca_profil_permission LEFT JOIN ca_permissions ON ca_permissions.id_permission = ca_profil_permission.id_permission WHERE ca_profil_permission.id_profil IN (:id_profil)";
    $values = array(':id_profil' => $profiles);
} else if (isset($_SESSION['profil'])) {
    // CONSTRUCT THE PERMISSIONS ARRAY
    $query = "SELECT type_permission FROM ca_profil_permission LEFT JOIN ca_permissions ON ca_permissions.id_permission = ca_profil_permission.id_permission LEFT JOIN ca_profils ON ca_profil_permission.id_profil = ca_profils.id_profil WHERE ca_profils.profil=:profil";
        $values = array(':profil' => intval($_SESSION['profil']));
}
if ($query != "") {
    $result = excuteQuery($query, $values);
    $permissionsResult = $result['stmt'];
    $permissionsArray = array();
    while ($perm = $permissionsResult->fetchObject()) {
        $permissionsArray[] = $perm->type_permission;
    }
    //SET PERMISSIONS ARRAY IN SESSION SO WE CAN USE IT IN OTHER PAGES
    $_SESSION['permissions'] = $permissionsArray;
} else {
    header("location:index.php");
}
// echo "<pre>";var_dump($_SESSION['permissions']);

$viewContent = (isset($_SESSION['permissions']) && in_array("view_homepage", $_SESSION['permissions'])) ? 1 : 0;
$empty = !in_array('view_homepage', $_SESSION['permissions']) ? 1 : 0;

// $lastCronQ = "SELECT date_format(date_arrivee,'%d/%m/%Y') last_cron FROM ca_clients ORDER BY date_arrivee DESC LIMIT 0,1";
// $lastCronR = $GLOBALS['cnx']->query($lastCronQ);
// $lastCronO = $lastCronR->fetchObject();
// $lastCron = $lastCronO->last_cron;
function hms($laps)
{
    $laps = sprintf("%.0f",$laps);
    if ($laps >= 3600)
        return sprintf("%d:%02d:%02d", $laps / 3600, ($laps / 60) % 60, $laps % 60);
    else
        return sprintf("%2d:%02d", $laps / 60, $laps % 60);
}
if($viewContent){
    $qagcList = "SELECT id_agence, nom_agence FROM ca_agences WHERE is_active=:is_active AND supp=:supp ORDER BY nom_agence ASC";
    if($_SESSION['profil'] != 100){
        $qagcList = "SELECT id_agence, nom_agence FROM ca_agences a WHERE id_agence IN (SELECT id_agence FROM ca_links WHERE id_admin = ". intval($_SESSION["id"]) .") AND is_active=:is_active AND supp=:supp ORDER BY nom_agence ASC" ;
    }
    $values_agc_list = array(':is_active' => 1, ':supp' => 0);
    $result_agc_list = excuteQuery($qagcList, $values_agc_list);
    $res_agc_list = $result_agc_list['stmt'];
    $AGC_LIST = array();
    $agc_filter = array();
    if($result_agc_list['status']){
            while ($row = $res_agc_list->fetchObject()){
                $obj = new stdClass();
                $obj->id_agence = $row->id_agence;
                $obj->nom_agence = $row->nom_agence;
                $AGC_LIST[] = $obj;
                $agc_filter[] = $row->id_agence;
            }
            // 0D80B1/008992/582583/931918/E30613/009597/ED1B2F
        }
    //filter global
    $DEB = isset($_REQUEST["debg"])?$_REQUEST["debg"].' 00:00:00':'';
    $FIN = isset($_REQUEST["fing"])?$_REQUEST["fing"].' 23:59:59':'';
    $AGENCES = isset($_GET['agencies'])?$_GET['agencies']:array();
    $agc_arr = array();
    $nb_agences = "Toutes les agences";
    $nom_agences = "Toutes les agences";

    if($AGENCES){ 
        foreach ($AGENCES as $a) {
            $agc_arr[] = intval($a);
        }
        $AGC_IN_FILTER_NB_Q = "SELECT COUNT(id_agence) nb FROM ca_agences WHERE id_agence IN (".implode(',', $agc_arr).")";
        $AGC_IN_FILTER_Q = "SELECT id_agence, nom_agence FROM ca_agences WHERE id_agence IN (".implode(',', $agc_arr).")";

        $AGC_IN_FILTER_STMT = excuteQuery($AGC_IN_FILTER_Q);
        $AGC_IN_FILTER_NB_STMT = excuteQuery($AGC_IN_FILTER_NB_Q);
        $AGC_IN_FILTER_ROWS = $AGC_IN_FILTER_STMT['stmt'];
        $a = $AGC_IN_FILTER_NB_STMT['stmt']->fetch(PDO::FETCH_OBJ)->nb;
        if(count($AGC_LIST) > $AGC_IN_FILTER_NB_STMT['stmt']->fetch(PDO::FETCH_OBJ)->nb){
            $nb_agences = $a." agences";
        }
        $agc_list_arr = array();
        while ($rowa = $AGC_IN_FILTER_ROWS->fetchObject()) {
            $agc_list_arr[] = $rowa->nom_agence;
        }
        if (count($agc_list_arr) == count($AGC_LIST)) {
            $nom_agences ="Toutes les agences";
        }else{
            $nom_agences = implode(', ', $agc_list_arr);
        }
        
    }
    $periodeArriveeMotifsQ = "";
    $periodeArriveeQ="";
    $agcQ="";
    $agcMotifsQ="";
    if($_SESSION["profil"] != 100 && !isset($_GET['agencies'])){
        $agcQ=" AND c.id_agence IN(".implode(',', $_SESSION["agences"]).")";
        $agcMotifsQ=" AND c.id_agence IN(".implode(',', $_SESSION["agences"]).")";
    }
    $valuesg = array();
    if(($DEB!="") && ($FIN!="")){
        $dd = date('Y-m-d',strtotime($DEB)).' 00:00:00';
        $df = date('Y-m-d',strtotime($FIN)).' 23:59:59';
        $periodeArriveeQ .= " AND date_arrivee BETWEEN :deb AND :fin";
        $periodeArriveeMotifsQ = " AND c.date_arrivee BETWEEN :deb AND :fin";
        $valuesg[':deb'] = $dd;
        $valuesg[':fin'] = $df;
    }
    
    if(!$periodeArriveeQ && !$periodeArriveeMotifsQ){
        $ddQ = date('Y-m-01') . ' 00:00:00';
        $daysagoQ = " AND date_arrivee >= '".$ddQ."'";
    }
    
    if($AGENCES){
        if((count($AGENCES)>0)&&($AGENCES!="null")){
            if(($DEB=="") && ($FIN=="")){
                $agcQ .= "AND c.id_agence IN (".implode(',', $AGENCES).")";
                $agcMotifsQ .= "AND c.id_agence IN (".implode(',', $AGENCES).")";
                //$valuesg[':id_agence'] =  implode(',', $AGENCES);
            }else{
                $agcMotifsQ .= " AND c.id_agence IN (".implode(',', $AGENCES).")";
                $agcQ .= " AND c.id_agence IN (".implode(',', $AGENCES).")";
                //$valuesg[':id_agence'] = implode(',', $AGENCES);
            }
        }
    }




    //durée attente request
    $q_duree_attente = "SELECT rdv,
     AVG(CASE WHEN rdv=1 AND date_priseencharge AND date_priseencharge >= date_arrivee THEN TIMESTAMPDIFF(SECOND, date_arrivee, date_priseencharge) END) as dureerdv,
     AVG(CASE WHEN rdv=0 AND date_priseencharge AND date_priseencharge >= date_arrivee THEN TIMESTAMPDIFF(SECOND, date_arrivee, date_priseencharge) END) as dureesrdv,
     AVG(CASE WHEN rdv=5 AND date_priseencharge AND date_priseencharge >= date_arrivee THEN TIMESTAMPDIFF(SECOND, date_arrivee, date_priseencharge) END) as dureeship /*Livraison*/

     FROM ".$table." c
     LEFT JOIN ca_agences a ON a.id_agence = c.id_agence 
     WHERE a.supp=0 AND rdv NOT IN(3,4)
     ".$periodeArriveeQ.$agcQ.$daysagoQ."
      GROUP BY rdv";
    
      if(count($valuesg)>0){
        $stmt = excuteQuery($q_duree_attente, $valuesg);
        $result_1 = $stmt['stmt'];
      }else{
            $result_1 = $GLOBALS['cnx']->query($q_duree_attente);
      }
    $DURATIONS_ATTENTE = array();


    if($result_1->rowCount() >0){
        while ($row = $result_1->fetchObject()){
            $obj = new stdClass();
            switch ($row->rdv) {
                case 0:
                    $obj->type = 'SRDV';
                    $obj->duree = hms($row->dureesrdv);
                    $obj->color = '#2196f3';
                break;
                case 1:
                    $obj->type = 'RDV';
                    $obj->duree = hms($row->dureerdv);
                    $obj->color = '#f44336';
                break;
                case 5:
                    $obj->type = 'Livraison';
                    $obj->duree = hms($row->dureeship);
                    $obj->color = $GLOBALS["PILE_CONF"]["COLORS"]["SHIP"];
                break;
            }
            $DURATIONS_ATTENTE[] = $obj;
        }
        // 0D80B1/008992/582583/931918/E30613/009597/ED1B2F
    }
    // var_dump($DURATIONS_ATTENTE);die();

    //durée entretien request
    $q_duree_entretien = "SELECT rdv,
     AVG(CASE WHEN rdv=1 AND date_cloture AND date_cloture >= date_priseencharge THEN TIMESTAMPDIFF(SECOND, date_priseencharge, date_cloture) END) as duree_ent_rdv,
     AVG(CASE WHEN rdv=0 AND date_cloture AND date_cloture >= date_priseencharge THEN TIMESTAMPDIFF(SECOND, date_priseencharge, date_cloture) END) as duree_ent_srdv,
     AVG(CASE WHEN rdv=5 AND date_cloture AND date_cloture >= date_priseencharge THEN TIMESTAMPDIFF(SECOND, date_priseencharge, date_cloture) END) as duree_ent_ship /*Livraison*/
     FROM ".$table." c 
     LEFT JOIN ca_agences a ON a.id_agence = c.id_agence
     WHERE a.supp=0 AND rdv NOT IN(3,4)
     ".$periodeArriveeQ.$agcQ.$daysagoQ."
      GROUP BY rdv";
    if(count($valuesg)>0){
        $stmt = excuteQuery($q_duree_entretien, $valuesg);
        $result_2 = $stmt['stmt'];
      }else{
            $result_2 = $GLOBALS['cnx']->query($q_duree_entretien);
      }
    $DURATIONS_ENTRETIEN = array();
    if($result_2->rowCount() >0){
        while ($row = $result_2->fetchObject()){
            $obj = new stdClass();
            switch ($row->rdv) {
                case 0:
                    $obj->type = 'SRDV';
                    $obj->duree = hms($row->duree_ent_srdv);
                    $obj->color = '#2196f3';
                break;
                case 1:
                    $obj->type = 'RDV';
                    $obj->duree = hms($row->duree_ent_rdv);
                    $obj->color = '#f44336';
                break;
                case 5:
                    $obj->type = 'Livraison';
                    $obj->duree = hms($row->duree_ent_ship);
                    $obj->color = $GLOBALS["PILE_CONF"]["COLORS"]["SHIP"];
                break;
            }
            $DURATIONS_ENTRETIEN[] = $obj;
        }
        // 0D80B1/008992/582583/931918/E30613/009597/ED1B2F
    }

    //Nombre de visite (RDV/SRDV) request
    $q_nb_visite = "SELECT rdv,
    COUNT(CASE when rdv = '0' then 1 END ) as noAppointment,
    COUNT(CASE when rdv = '1' then 1 END ) as appointment,
    COUNT(CASE when rdv = '5' then 1 END ) as ship
     FROM ".$table." c      
    LEFT JOIN ca_agences a ON a.id_agence = c.id_agence
     WHERE a.supp=0 AND rdv NOT IN(3,4) 
     ".$periodeArriveeQ.$agcQ.$daysagoQ."
      GROUP BY rdv";
    if(count($valuesg)>0){
        $stmt = excuteQuery($q_nb_visite, $valuesg);
        $result_3 = $stmt['stmt'];
      }else{
            $result_3 = $GLOBALS['cnx']->query($q_nb_visite);
      }
    $NB_VISITES = array();
    if($result_3->rowCount() >0){
        while ($row = $result_3->fetchObject()){
            $obj = new stdClass();
            switch ($row->rdv) {
                case 0:
                    $obj->type = 'SRDV';
                    $obj->visite = $row->noAppointment;
                    $obj->color = '#2196f3';
                break;
                case 1:
                    $obj->type = 'RDV';
                    $obj->visite = $row->appointment;
                    $obj->color = '#f44336';
                break;
                case 5:
                    $obj->type = 'Livraison';
                    $obj->visite = $row->ship;
                    $obj->color = $GLOBALS["PILE_CONF"]["COLORS"]["SHIP"];
                break;
            }
            $NB_VISITES[count($NB_VISITES)] = $obj;
        }
        // 0D80B1/008992/582583/931918/E30613/009597/ED1B2F
    }

    //Agences (ACTIF/INACTIF) request
    $q_agences = "SELECT is_active,COUNT(*) nb
     FROM ca_agences
     WHERE supp = :supp";
      if($_SESSION['profil'] != 100){
        $qagcByProfil = " AND id_agence IN (SELECT id_agence FROM ca_links WHERE id_admin = ". intval($_SESSION["id"]) .")" ;
        $q_agences.=$qagcByProfil;
        }
        $q_agences .= " GROUP BY is_active";
      $values_agences = array(':supp' => 0);
      $stmt_agences = excuteQuery($q_agences, $values_agences);
    $result_4 = $stmt_agences['stmt'];
    $AGENCES_LIST = array();
    if($result_4->rowCount() >0){
        while ($row = $result_4->fetchObject()){
            $obj = new stdClass();
            $obj->type = $row->is_active == 1?'Actives':'Inactives';
            $obj->value = $row->nb;
            $obj->title_popup = $row->is_active ==1 ?'Agences actives':'Agences inactives';
            $obj->status = $row->is_active;
            $obj->color = $row->is_active == 1?'#3366cc':'#dc3912';
            $AGENCES_LIST[count($AGENCES_LIST)] = $obj;
        }
        // 0D80B1/008992/582583/931918/E30613/009597/ED1B2F
    }
    //Motifs request
    $joinQ = count($values)>0?" LEFT JOIN ".$table." c ON cm.id_client=c.id_client":"";
    $rdvQ = count($values)>0?"AND rdv = 0":"";
    $q_motifs = "SELECT cm.id_motif,COUNT(cm.id_motif) nb, m.titre, m.code
     FROM ca_historique_client_motifs cm
     ".$joinQ."      
     LEFT JOIN ca_motifs m ON cm.id_motif=m.id_motif
     LEFT JOIN ca_agences a ON a.id_agence = c.id_agence
     WHERE a.supp=0 
     ".$periodeArriveeMotifsQ.$agcMotifsQ.$daysagoQ."
     ".$rdvQ."
      GROUP BY cm.id_motif";
    
    if(count($valuesg)>0){
        $stmt = excuteQuery($q_motifs, $valuesg);
        $result_5 = $stmt['stmt'];
      }else{
            $result_5 = $GLOBALS['cnx']->query($q_motifs);
      }
    $MOTIFS_LIST = array();
    if($result_5->rowCount() >0){
        while ($row = $result_5->fetchObject()){
            $obj = new stdClass();
            $obj->type = $row->titre;
            $obj->code = $row->code;
            $obj->value = $row->nb;
            $MOTIFS_LIST[count($MOTIFS_LIST)] = $obj;
        }
        // 0D80B1/008992/582583/931918/E30613/009597/ED1B2F
    }

    //NFC request
    $q_nfc = "SELECT nfcprov,COUNT(*) nb

     FROM ".$table." c LEFT JOIN ca_agences a ON a.id_agence = c.id_agence WHERE a.supp=0 AND rdv NOT IN(3,4)
     ".$periodeArriveeQ.$agcQ.$daysagoQ."
      GROUP BY nfcprov";

    if(count($valuesg)>0){
        $stmt = excuteQuery($q_nfc, $valuesg);
        $result_6 = $stmt['stmt'];
      }else{
            $result_6 = $GLOBALS['cnx']->query($q_nfc);
      }
    $NFC_LIST = array();
    if($result_6->rowCount() >0){
        while ($row = $result_6->fetchObject()){
            $obj = new stdClass();
            $obj->type = $row->nfcprov == 1?'NFC':'Standard';
            $obj->value = $row->nb;
            $obj->color = $row->nfcprov == 1?'#2196f3':'#f44336';
            $NFC_LIST[count($NFC_LIST)] = $obj;
        }
        // 0D80B1/008992/582583/931918/E30613/009597/ED1B2F
    }
}


?>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta charset="utf-8">
    <title><?php echo $PROJECT_TITLE;?></title>
    <link rel="stylesheet" href="css/font-awesome.min.css" />
    <link rel="stylesheet" type="text/css" href="css/cadif.css" />
    <link rel="stylesheet" type="text/css" href="css/dashboard.css" />
    <link rel="stylesheet" type="text/css" href="css/card.css" />
    <link rel="stylesheet" type="text/css" href="css/multiselect.css">
    <link rel="stylesheet" type="text/css" href="css/jquery-labelauty.css">
    <link rel="stylesheet" type="text/css" href="css/cans/jquery-ui-1.8.17.custom.css" />
    
    <script type="text/javascript" src="js/multiselect.min.js"></script>
    <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
    <script type="text/javascript" src="js/jquery-ui-1.8.22.custom.min.js"></script>
    <script type="text/javascript" src="js/uidatepicker-fr.js"></script>
    <script type="text/javascript" src="js/loader.js"></script>
    <script type="text/javascript" src="js/chartFilter.js"></script>
    <script type="text/javascript" src="js/jquery-labelauty.js"></script>

    
    <!--<script type="text/javascript" src="amcharts/amcharts.js"></script>
    <script type="text/javascript" src="amcharts/lang/fr.js"></script>
    <script type="text/javascript" src="amcharts/serial.js"></script>
    <script type="text/javascript" src="amcharts/pie.js"></script>-->
    <style type="text/css">
        .ui-dialog-titlebar {
            background-color: #e96224;
            color: #FFF;
        }
        .ui-widget-header{
            border-color: #e96224;
            background: #e96224;
            color: #FFF;
            font-weight: bold;
        }
        .filter-bloc-chart{
            display: flex;
            margin-left: 13px;
            padding: 16px 4% 10px 3%;
        }
        
        .sortable label {
            width: 100%;
        }

        .filter-bloc-chart  label {
            width: 100%;
        }

        .sortable input.labelauty:checked + label,
        .sortable input.labelauty:not(:checked):not([disabled]) + label {
            width: 100%;
            font-size: 12px;
        }

        .sortable  div {
            display: inline-flex;
            flex-direction: row;
            align-items: center;
            justify-content: center;
            align-content: space-between;
            margin-right: 10px;
        }

        .sortable.ui-sortable {
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto;
        }
        .btn-filter-bloc-chart{
            height: 36px;
        }

        .tab-stat {
            font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
            border-collapse: collapse;
            width: 30%;
            right: 3%;
            position: absolute;
        }
        

        .tab-stat td, .tab-stat th {
          border: 1px solid #ddd;
          padding: 5px 10px;
        }
        .s-tab td, .s-tab th {
            border: 1px solid #ddd;
            padding: 10px 37px;
        }
        .tab-mot td{
            font-size: 12px;
        }

        .tab-stat tr:nth-child(even){background-color: #f2f2f2;}

        .tab-stat tr:hover {background-color: #ddd;}

        .tab-stat th {
          padding-top: 5px;
          padding-bottom: 5px;
          text-align: center;
          background-color: #f21b2f;
          color: white;
        }
        .dropdown-content{
            display: none;
            padding: 20px;
            box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
            position: absolute;
            top: 50px;
            right: 0;
            background-color: #f9f9f9;
            border-radius: 9px;
            z-index: 9;
        }
        .filter-prop-content{
            display: none;
            box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
            position: absolute;
            top: 51px;
            border: 2px solid #757575;
            width: 95.5%;
            height: 71.5%;
            /* right: 33%; */
            text-align: center;
            background-color: #fff;
            border-radius: 9px;
            z-index: 1;
            overflow: auto;
        }
        .filter-prop-content::-webkit-scrollbar-track
        {
            box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
            border-radius: 10px;
            background-color: #E1E1E1;
        }

        .filter-prop-content::-webkit-scrollbar
        {
            width: 12px;
            background-color: #F5F5F5;
        }

        .filter-prop-content::-webkit-scrollbar-thumb
        {
            border-radius: 10px;
            box-shadow: inset 0 0 6px rgba(0,0,0,.3);
            background-color: #D62929;
        }
        .card{
            background: #fff;
            position: relative;
        }
        .card-content{
            background: #fff;
            display: flex;
            align-items: center;
            margin-top: 30px;
            padding: 4% 1% 1% 1%;
        }
        .card input[type="text"] {
            padding: 5px;
            border-radius: 5px;
        }

        .multiselect-wrapper ul li.active span {
            color: white;
        }

        div#agcSelectList_multiSelect {
            position: relative;
        }
        .loader {
            text-align: center;
          border: 5px solid #f3f3f3; /* Light grey */
          border-top: 5px solid #009597; /* Blue */
          border-radius: 50%;
          width: 30px;
          height: 30px;
          animation: spin 2s linear infinite;
        }

        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }
        
        
        /* IE */
        @media all and (-ms-high-contrast:none)
         {
         .tab-stat { width: 35%; } /* IE10 */
         .tab-mot{margin-top: -30px;}
         .btn-filter-bloc-chart{
            top: 0;
         }

         .tab-mot th { font-size: 11px; }.text-empty-data{left: 28%;}
         *::-ms-backdrop, .tab-stat { width: 35%; }.tab-mot{margin-top: -30px;}.tab-mot th { font-size: 11px; }.text-empty-data{left: 243px;}
         .filter-prop-content{width: 95%;}
         .filter-info-details-close{
            top: 2px;            /* IE11 */
         }
         .btn-filter-bloc-chart{
            top: 0;
         }

        .multiselect-count{
            width: auto;
            right: 30px;
            left: auto !important;
        }
    }

    .ghost{
        opacity: .3;
    }

    </style>
    <script type="text/javascript">
         $(function(){
        $('.btn-tools-card').on("click",function(){
            $(this).next().slideToggle();
            $(this).toggleClass('active-btn-tools');
            if($(this).parents('.card').find('.filter-prop-content').css('display') == 'block'){
                $(this).parents('.card').find('.filter-prop-content').hide();
            }
        });
        $('.btn-info-filter').on("click",function(){
            $(this).next().toggle();
            if($(this).parents('.card').find('.dropdown-content').css('display') == 'block'){
                $(this).parents('.card').find('.dropdown-content').hide();
            }
        });
        $('.filter-info-details-close').on("click", function () {
            $(this).parents('.filter-prop-content').hide();
        });
         });
         
        //durée attente chart
        <?php if($result_1 && $result_1->rowCount()>0){ ?>
        google.charts.load('current', {packages: ['corechart', 'bar']});
        google.charts.setOnLoadCallback(drawBasic);
           function drawBasic()  
           {  
                var data = google.visualization.arrayToDataTable([  
                          ['Task', 'Durée par type de visite', {role: 'annotation'}, {role: 'tooltip'}, { role: 'style' }],  
                          <?php 
                          foreach($DURATIONS_ATTENTE as $DURATION_ATTENTE)  
                          {  
                               echo "['".$DURATION_ATTENTE->type."', ".round($DURATION_ATTENTE->duree*60).", '".$DURATION_ATTENTE->duree."', 'Durée : ".toTimeForChart($DURATION_ATTENTE->duree, true)."','color: ".$DURATION_ATTENTE->color."'],";  
                          }  
                          ?>  
                     ]);  
                var options = {  
                    legend: 'none',
                    hAxis: { textPosition: 'none' },
                    annotations: {
                        textStyle: {
                            color: 'black',
                            fontSize: 11,
                        },
                        alwaysOutside: true
                    }
                      //title: 'Durée moyenne d\'attente',  
                      //is3D:true,  
                      /*hAxis: {
                          title: 'Durée',
                          italic: false
                        }*/
                     };  
                var chart = new google.visualization.BarChart(document.getElementById('attenteChart'));  
                chart.draw(data, options);  
           } 
        <?php } ?>
        <?php if($result_2 && $result_2->rowCount()>0){ ?>
           //durée entretien chart
        google.charts.load('current', {packages: ['corechart', 'bar']});
        google.charts.setOnLoadCallback(drawBasic2);
           function drawBasic2()  
           {  
                var data = google.visualization.arrayToDataTable([  
                          ['Task', 'Durée par type de visite', {role: 'annotation'}, {role: 'tooltip'}, { role: 'style' }],  
                          <?php  
                          foreach($DURATIONS_ENTRETIEN as $DURATION_ENTRETIEN)  
                          {  
                               echo "['".$DURATION_ENTRETIEN->type."', ".round($DURATION_ENTRETIEN->duree*60).", '".$DURATION_ENTRETIEN->duree."', 'Durée : ".toTimeForChart($DURATION_ENTRETIEN->duree, true)."','color: ".$DURATION_ENTRETIEN->color."'],";  
                          }  
                          ?>  
                     ]);  
                var options = {  
                    legend: 'none',
                    hAxis: { textPosition: 'none' },
                    annotations: {
                        textStyle: {
                            color: 'black',
                            fontSize: 11,
                        },
                        alwaysOutside: true
                    }
                      //title: 'Durée moyenne d\'entretien',  
                      //is3D:true,  
                      /*hAxis: {
                          title: 'Durée',
                        },*/
                     };  
                var chart = new google.visualization.BarChart(document.getElementById('entretienChart'));  
                chart.draw(data, options);  
           } 

        <?php } ?>
        <?php if($result_3 && $result_3->rowCount()>0){ ?>
           //Nombre de visite (RDV/SRDV) chart
        google.charts.load('current', {packages: ['corechart', 'bar']});
        google.charts.setOnLoadCallback(drawBasic3);
           function drawBasic3()  
           {  
                var data = google.visualization.arrayToDataTable([  
                          ['Task', 'Durée par type de visite', { role: 'style' }],  
                          <?php  
                          foreach($NB_VISITES as $VISITE)  
                          {  
                               echo "['".$VISITE->type."', ".$VISITE->visite.",'color: ".$VISITE->color."'],";  
                          }  
                          ?>  
                     ]);  
                var options = {  
                      //title: 'Nombre de visites',  
                      //is3D:true,  
                      colors: ['#2196f3','#f44336','#e5ab3d'],
                      pieHole: 0.2  
                     };  
                var chart = new google.visualization.PieChart(document.getElementById('visitsChart'));  
                chart.draw(data, options);  
           } 

        <?php } ?>
           ////Agences (ACTIF/INACTIF) chart
        google.charts.load('current', {packages: ['corechart', 'bar']});
        google.charts.setOnLoadCallback(drawBasic4);
           function drawBasic4()  
           {  
                var data = google.visualization.arrayToDataTable([  
                          ['Task', 'Durée par type de visite'],  
                          <?php  
                          foreach($AGENCES_LIST as $AGENCE)  
                          {  
                               echo "['".$AGENCE->type."', ".$AGENCE->value."],";  
                          }  
                          ?>  
                     ]);  
                var options = {  
                      //title: 'Agences',  
                      //is3D:true,  
                      pieHole: 0.2,
                      slices: {


                        <?php  foreach($AGENCES_LIST as $key=>$AGENCE)  
                          {  
                            echo $key.": { color:'".$AGENCE->color."'},";
                            
                          }
                          ?>
                      }
                     };  
                var chart = new google.visualization.PieChart(document.getElementById('agencesChart'));  
                chart.draw(data, options);  
           } 
        <?php if($result_5 && $result_5->rowCount()>0){ ?>
           ////Motifs chart
        google.charts.load('current', {packages: ['corechart', 'bar']});
        google.charts.setOnLoadCallback(drawBasic5);
       function drawBasic5()  
       {  
            var data = google.visualization.arrayToDataTable([  
                      ['Task', 'Durée par type de viste'],  
                      <?php  
                      foreach($MOTIFS_LIST as $MOTIF)  
                      {  
                        if(isset($MOTIF->type)){
                           echo "['".$MOTIF->code."', ".$MOTIF->value."],";  
                        }
                      }  
                      ?>  
                 ]);  
            var options = {  
                  //title: 'Motifs',  
                  //is3D:true,  
                  pieHole: 0.2  
                 };  
            var chart = new google.visualization.PieChart(document.getElementById('motifsChart'));  
            chart.draw(data, options);  
       } 
       <?php } ?>
       <?php if($result_6 && $result_6->rowCount()>0){
        ?>
       ////NFC chart
        google.charts.load('current', {packages: ['corechart', 'bar']});
        google.charts.setOnLoadCallback(drawBasic6);
       function drawBasic6()  
       {  
            var data = google.visualization.arrayToDataTable([  
                      ['Task', 'Durée par type de visite'],  
                      <?php  
                      foreach($NFC_LIST as $NFC)  
                      {  
                           echo "['".$NFC->type."', ".$NFC->value."],";  
                      }  
                      ?>  
                 ]);  
            var options = {  
                  //title: 'NFC',  
                  //is3D:true,  
                  pieHole: 0.2  
                 };  
            var chart = new google.visualization.PieChart(document.getElementById('nfcChart'));  
            chart.draw(data, options);  
       } 
   <?php } ?>
    </script>
</head>

<body>

<div id="global">

    <div id="home">
        <div id="logo"><a href="dashboard.php"><img src="<?php echo $SERVER; ?>assets/img/logo.png" height="110" border="0"/></a></div>
        <div id="username">
            <b><?php echo isset($_SESSION["nom"]) ? $_SESSION["nom"] : $_SESSION["matricule"];?></b> &nbsp; | &nbsp; <a href="close.php" class="link" title="Fermer et clore votre session">D&#233;connexion</a>
            <!--<br/>
            Se connecter en tant que: <a href="<?php echo $SERVER;?>edsGetUrl.php?eds=00001&matricule=M006996">DA</a> | <a href="<?php echo $SERVER;?>edsGetUrl.php?eds=00001&matricule=M025481">PRO</a>-->
        </div>
    </div>
    <div id="panels">
      <?php include "menu.php";?>
      <div class="main-content">
        <div id="title">
            Administration des bornes d'orientation
        </div>
      <?php if($viewContent){?>
        <?php
        if ($_SESSION['profil'] != 100) {
        ?>
            <input type="hidden" name="default_agencies" id="default_agencies" value="<?php echo implode(',', $_SESSION["agences"]); ?>">
            <?php
        }
        ?>
            <div class="filter-bloc-chart">
                <div class="sortable">
                    <div data-panel="nbVisites"><input checked type="checkbox" id="toggle-nb-visite" class="filterBlock" data-labelauty="Nombre de visite|Nombre de visite" onchange="toggleBlockChart('toggle-nb-visite', 'nbVisites')"/></div>
                    <div data-panel="agencesliste"><input checked type="checkbox" id="toggle-agences" class="filterBlock" data-labelauty="Agences|Agences" onchange="toggleBlockChart('toggle-agences', 'agencesliste')"/></div>
                    <div data-panel="attente"><input checked type="checkbox" id="toggle-attente" class="filterBlock" data-labelauty="Durée moyenne d'attente|Durée moyenne d'attente" onchange="toggleBlockChart('toggle-attente', 'attente')" /></div>
                    <div data-panel="entretien"><input checked type="checkbox" id="toggle-entretien" class="filterBlock" data-labelauty="Durée moyenne d'entretien|Durée moyenne d'entretien" onchange="toggleBlockChart('toggle-entretien', 'entretien')"/></div>
                    <div data-panel="motifsliste"><input checked type="checkbox" id="toggle-motifs" class="filterBlock" data-labelauty="Motifs|Motifs" onchange="toggleBlockChart('toggle-motifs', 'motifsliste')" /></div>
                    <div data-panel="nfcliste"><input checked type="checkbox" id="toggle-nfc" class="filterBlock" data-labelauty="Type d'identification|Type d'identification" onchange="toggleBlockChart('toggle-nfc', 'nfcliste')"/></div>
                </div>
                <button type="button" class="btn-filter-bloc-chart"><i class="fa fa-tasks"></i> Filtrer</button>
            </div>
            <div class="global-filter">
                <form action="dashboard.php" method="GET" id="form-global-filter">
                    <span class="col-2">
                        <input type="text" name="debg" max="<?php echo date("d-m-Y");?>" class="debg" placeholder="Date de début" <?php if(!empty($_GET['debg'])){ ?>value="<?php echo $_GET['debg']; ?>"<?php } ?>>
                    </span>
                    <span class="col-2">
                        <input type="text" name="fing" max="<?php echo date("d-m-Y");?>" class="fing" placeholder="Date de fin" <?php if(!empty($_GET['fing'])){ ?>value="<?php echo $_GET['fing']; ?>"<?php } ?>>
                    </span>
                    <span class="col-6">
                        <input type="hidden" id="agcSelectList6_hidden">
                        <select id="agcSelectList6" style="width: 30%;margin-top: 5px;" multiple="multiple" name="agencies[]">
                            <?php
                            foreach ($AGC_LIST as $agc) {
                                ?>
                                <option value="<?php echo $agc->id_agence; ?>" data-nom="<?php echo $agc->nom_agence; ?>" <?php if(in_array($agc->id_agence, $agc_arr)){ ?>selected="true"<?php } ?>><?php echo $agc->nom_agence; ?></option>
                                <?php
                            }
                            ?>
                        </select>
                    </span>
                    <span class="col-2">
                        <button type="submit" class="btn-global-filter"<?php if(count($valuesg)==0){ ?> style="width: 100%;"<?php }?>>Recherche</button>
                        <?php if(count($valuesg)>0){ ?>
                        <button type="button" onclick="document.location='dashboard.php'" class="btn-global-filter">Réinitialiser</button>
                        <!--<a href="dashboard.php" class="btn-global-filter" style="padding: 5px;width: 50%;">Réinitialiser</a>-->
                        <?php } ?>
                    </span>
                </form>
            </div>
            <div class="cards-container">
                <div class="first-half card ui-state-default" id="nbVisites">
                    <div class="head-card">
                        <span class="head-card-title">Nombre de visite</span>
                        <button class="btn-tools-card">
                            <i class="fa fa-tasks"></i> <span class="text-btn-tools-card">Filtrer</span>
                        </button>
                        <div class="dropdown-content">
                            <div style="text-align: center;margin-bottom: 5px;color: #000;width: 100%;font-size: 14px;margin-top: 5px;">Période</div>
                            <input type="text" name="deb" max="<?php echo date("d-m-Y");?>" class="deb" placeholder="Date de début">
                            <input type="text" name="fin" max="<?php echo date("d-m-Y");?>" class="fin" placeholder="Date de fin">
                            <input type="hidden" id="agcSelectList2_hidden">
                            <br>
                            <div style="text-align: center;margin-bottom: 5px;color: #000;width: 100%;font-size: 14px;margin-top: 5px;">Agence</div>
                            <select id="agcSelectList2" style="width: 100%;margin-top: 5px;" multiple="multiple">
                                <?php
                                foreach ($AGC_LIST as $agc) {
                                    ?>
                                    <option value="<?php echo $agc->id_agence; ?>" data-nom="<?php echo $agc->nom_agence; ?>"><?php echo $agc->nom_agence; ?></option>
                                    <?php
                                }
                                ?>
                            </select>
                            <input type="hidden" id="agccount2">
                            <div style="text-align: center;">
                                <button class="btn-validate-filter" onclick="filterChart('nbVisites', 'pie', 'visitsChart', 'agcSelectList2')">Valider</button>
                                <button class="btn-reset-filter" onclick="resetFilterChart('nbVisites', 'pie', 'visitsChart', 'agcSelectList2', 'agccount2')">Réinitialiser</button>
                            </div>
                        </div>
                    </div>
                    <div class="card-content">
                        <?php if($result_3->rowCount() == 0 && count($values)>0){?> <div class="text-empty-data">Aucun résultat</div><?php } ?>
                        <div id="visitsChart" style="width: 68%; height: 200px;top: -100px;<?php if($result_3->rowCount() == 0 && count($values)>0){?>display: none <?php }else{ ?>display: inline-block<?php } ?>" ></div>
                        <table class="tab-stat" style="width: 30%;<?php if($result_3->rowCount() == 0 && count($values)>0){ ?>display: none;<?php } ?>">
                            <thead>
                                <tr>
                                    <th>Type</th>
                                    <th>Visite</th>
                                </tr>
                            </thead>
                            <tbody class="nbvisites-rows rows">
                                <?php  
                                  foreach($NB_VISITES as $VISITE)  
                                  {  ?>
                                    <tr>
                                        <td>
                                            <?php echo $VISITE->type;?>
                                        </td>
                                        <td>
                                            <?php echo round($VISITE->visite);?>
                                        </td>
                                   </tr>
                                       <?php
                                  }  
                                  ?> 
                            </tbody>
                        </table>
                    </div>
                    <div class="card-footer">
                        <span class="filter-info"><span style="color: #000;font-weight: 100">
                            <?php 
                            if(!empty($_REQUEST['debg']) || !empty($_REQUEST['fing'])){ ?>
                                <b>Date de début : </b><?php echo date("d-m-Y", strtotime($_REQUEST['debg'])); ?>
                                <b> Date de fin : </b><?php echo date("d-m-Y", strtotime($_REQUEST['fing'])); ?>
                                <?php }else{ ?>

                                    <b>Période : </b>Ce mois-ci | 
                                    <?php } ?>
                                <?php if(isset($_REQUEST['agencies'])){ ?>  
                                    <b>Agences : </b><?php echo $nb_agences; ?></span>
                                    <?php }else{ ?>
                            <b>Agences : </b>Toutes les agences</span>
                             <?php } ?>
                        </span><button class="btn-info-filter" type="button"><i class="fa fa-question-circle"></i></button>
                        <div class="filter-prop-content">
                            <button type="button" class="filter-info-details-close"><i class="fa fa-times-circle"></i></button>
                            <span class="filter-info-details">
                                <?php if(!empty($_REQUEST['debg']) || !empty($_REQUEST['fing'])){ ?>
                                <b>Période : </b><br><br><b>Date de début : </b>
                                <?php echo date("d-m-Y", strtotime($_REQUEST['debg'])); ?><b> | Date de fin : </b><?php echo date("d-m-Y", strtotime($_REQUEST['fing'])); ?>
                                <?php }else{ ?>

                                <b>Période : </b>Ce mois-ci
                                <?php } ?>
                                <?php if(isset($_REQUEST['agencies'])){ ?>  
                                    <br><br><b>Agences : </b><?php echo $nom_agences; ?>
                                    <?php }else{ ?>
                                <br><br><b>Agences : </b>Toutes les agences
                                <?php } ?>
                            </span>
                        </div>
                    </div>
                </div>
                <div class="second-half card ui-state-default" id="agencesliste">
                    <div class="head-card">
                        <span class="head-card-title">Agences</span>
                    </div>
                    <div class="card-content agences" style="height: auto;">
                    <div id="agencesChart" style="width: 67%; height: 200px;display: inline-block;top: -100px;" ></div>
                        <table class="tab-stat" style="width: 30%;">
                            <thead>
                                <tr>
                                    <th>Status</th>
                                    <th>Agences</th>
                                </tr>   
                            </thead>
                            <tbody class="rows">
                                <?php  
                                  foreach($AGENCES_LIST as $AGENCE)  
                                  {  ?>
                                    <tr>
                                        <td>
                                            <?php echo $AGENCE->type;?>
                                        </td>
                                        <td>
                                            <a href="javascript:agenciesInPOPUP(<?php echo $AGENCE->status.', \''.$AGENCE->title_popup; ?>' );">
                                                <?php echo round($AGENCE->value);?>
                                            </a>
                                        </td>
                                   </tr>
                                       <?php
                                  }  
                                  ?> 
                            </tbody>
                        </table>
                    </div>
                    <div class="card-footer" style="border-top: 1px solid transparent;">
                        <span class="filter-info"><span style="color: #fff;"><b>Période : </b>Ce mois-ci</span></span><button class="btn-info-filter" type="button" style="background-color: transparent;color: transparent;"><i class="fa fa-question-circle"></i></button>
                        <!--<div class="filter-prop-content">
                            <button type="button" class="filter-info-details-close"><i class="fa fa-times-circle"></i></button>
                            <span class="filter-info-details"><b>Période : </b>Ce mois-ci</span></div>-->
                    </div>
                </div>
                <div class="first-half card ui-state-default" id="attente">    
                    <div class="head-card">
                        <span class="head-card-title">Durée moyenne d'attente</span>
                        <button class="btn-tools-card">
                            <i class="fa fa-tasks"></i> <span class="text-btn-tools-card">Filtrer</span>
                        </button>
                        <div class="dropdown-content">
                            <div style="text-align: center;margin-bottom: 5px;color: #000;width: 100%;font-size: 14px;margin-top: 5px;">Période</div>
                            <input type="text" name="deb" max="<?php echo date("d-m-Y");?>" class="deb" placeholder="Date de début">
                            <input type="text" name="fin" max="<?php echo date("d-m-Y");?>" class="fin" placeholder="Date de fin">
                            <input type="hidden" id="agcSelectList_hidden">
                            <br>
                            <div style="text-align: center;margin-bottom: 5px;color: #000;width: 100%;font-size: 14px;margin-top: 5px;">Agence</div>
                            <select id="agcSelectList" style="width: 100%;margin-top: 5px;" multiple="multiple">
                                <?php
                                foreach ($AGC_LIST as $agc) {
                                    ?>
                                    <option value="<?php echo $agc->id_agence; ?>" data-nom="<?php echo $agc->nom_agence; ?>"><?php echo $agc->nom_agence; ?></option>
                                    <?php
                                }
                                ?>
                            </select>
                            <input type="hidden" id="agccount">
                            <div style="text-align: center;">
                                <button class="btn-validate-filter" onclick="filterChart('attente', 'bar', 'attenteChart', 'agcSelectList')">Valider</button>
                                <button class="btn-reset-filter" onclick="resetFilterChart('attente', 'bar', 'attenteChart', 'agcSelectList', 'agccount')">Réinitialiser</button>
                            </div>
                        </div>
                    </div>
                    <div class="card-content attente">
                        <?php if($result_1->rowCount() == 0 && count($values)>0){ ?><div class="text-empty-data">Aucun résultat</div><?php } ?>
                        <div id="attenteChart"<?php if($result_1->rowCount() == 0 && count($values)>0){ ?> style="display:none;"<?php }else{ ?> style="width: 60%; height: 200px;display: inline-block;"<?php } ?> ></div>
                        <table class="tab-stat" <?php if($result_1->rowCount() == 0 && count($values)>0){ ?>style="display:none;"<?php } ?>>
                            <thead>
                                <tr>
                                    <th>Type</th>
                                    <th>Durée</th>
                                </tr>   
                            </thead>
                            <tbody class="attente-rows rows">
                                <?php
                              foreach($DURATIONS_ATTENTE as $DURATION_ATTENTE)  
                              { ?>
                                <tr>
                                    <td>
                                        <?php echo $DURATION_ATTENTE->type;?>
                                    </td>
                                    <td>
                                        <?php echo $DURATION_ATTENTE->duree;?>
                                    </td>
                               </tr>
                                   <?php
                              }  
                              ?>    
                            </tbody>
                              
                        </table>
                    </div>
                    <div class="card-footer">
                        <span class="filter-info"><span style="color: #000;font-weight: 100">
                            <?php 
                            if(!empty($_REQUEST['debg']) || !empty($_REQUEST['fing'])){ ?>
                                <b>Date de début : </b><?php echo date("d-m-Y", strtotime($_REQUEST['debg'])); ?>
                                <b> Date de fin : </b><?php echo date("d-m-Y", strtotime($_REQUEST['fing'])); ?>
                                <?php }else{ ?>

                                    <b>Période : </b>Ce mois-ci | 
                                    <?php } ?>
                                <?php if(isset($_REQUEST['agencies'])){ ?>  
                                    <b>Agences : </b><?php echo $nb_agences; ?></span>
                                    <?php }else{ ?>
                            <b>Agences : </b>Toutes les agences</span>
                             <?php } ?>
                        </span><button class="btn-info-filter" type="button"><i class="fa fa-question-circle"></i></button>
                        <div class="filter-prop-content">
                            <button type="button" class="filter-info-details-close"><i class="fa fa-times-circle"></i></button>
                            <span class="filter-info-details">
                                <?php if(!empty($_REQUEST['debg']) || !empty($_REQUEST['fing'])){ ?>
                                <b>Période : </b><br><br><b>Date de début : </b>
                                <?php echo date("d-m-Y", strtotime($_REQUEST['debg'])); ?><b> | Date de fin : </b><?php echo date("d-m-Y", strtotime($_REQUEST['fing'])); ?>
                                <?php }else{ ?>

                                <b>Période : </b>Ce mois-ci
                                <?php } ?>
                                <?php if(!empty($_REQUEST['agencies'])){ ?>  
                                    <br><br><b>Agences : </b><?php echo $nom_agences; ?>
                                    <?php }else{ ?>
                                <br><br><b>Agences : </b>Toutes les agences
                                <?php } ?>
                            </span>
                        </div>
                    </div>
                </div>
                <div class="second-half card ui-state-default" id="entretien">
                    <div class="head-card">
                        <span class="head-card-title">Durée moyenne d'entretien</span>
                        <button class="btn-tools-card">
                            <i class="fa fa-tasks"></i> <span class="text-btn-tools-card">Filtrer</span>
                        </button>
                        <div class="dropdown-content">
                            <div style="text-align: center;margin-bottom: 5px;color: #000;width: 100%;font-size: 14px;margin-top: 5px;">Période</div>
                            <input type="text" name="deb" max="<?php echo date("d-m-Y");?>" class="deb" placeholder="Date de début">
                            <input type="text" name="fin" max="<?php echo date("d-m-Y");?>" class="fin" placeholder="Date de fin">
                            <input type="hidden" id="agcSelectList1_hidden">
                            <br>
                            <div style="text-align: center;margin-bottom: 5px;color: #000;width: 100%;font-size: 14px;margin-top: 5px;">Agence</div>
                            <select id="agcSelectList1" style="width: 100%;margin-top: 5px;" multiple="multiple">
                                <?php
                                foreach ($AGC_LIST as $agc) {
                                    ?>
                                    <option value="<?php echo $agc->id_agence; ?>" data-nom="<?php echo $agc->nom_agence; ?>"><?php echo $agc->nom_agence; ?></option>
                                    <?php
                                }
                                ?>
                            </select>
                            <input type="hidden" id="agccount1">
                            <div style="text-align: center;">
                                <button class="btn-validate-filter" onclick="filterChart('entretien', 'bar', 'entretienChart', 'agcSelectList1')">Valider</button>
                                <button class="btn-reset-filter" onclick="resetFilterChart('entretien', 'bar', 'entretienChart', 'agcSelectList1', 'agccount1')">Réinitialiser</button>
                            </div>
                        </div>
                    </div>
                    <div class="card-content entretien">
                        <?php if($result_2->rowCount() == 0 && count($values)>0){ ?><div class="text-empty-data">Aucun résultat</div><?php } ?>
                        <div id="entretienChart" style="width: 60%; height: 200px;<?php if($result_2->rowCount() == 0 && count($values)>0){?>display: none;<?php }else{ ?>display: inline-block;<?php } ?>" ></div>
                        <table class="tab-stat" <?php if($result_2->rowCount() == 0 && count($values)>0){ ?> style="display:none;"<?php } ?>>
                            <thead>
                                <tr>
                                    <th>Type</th>
                                    <th>Durée</th>
                                </tr>
                            </thead>
                            <tbody class="entretien-rows rows">
                            <?php  
                              foreach($DURATIONS_ENTRETIEN as $DURATION_ENTRETIEN)  
                              {  ?>
                                <tr>
                                    <td>
                                        <?php echo $DURATION_ENTRETIEN->type;?>
                                    </td>
                                    <td>
                                        <?php echo $DURATION_ENTRETIEN->duree;?>
                                    </td>
                               </tr>
                                   <?php
                              }  
                              ?>  
                            </tbody>
                        </table>
                    </div>
                    <div class="card-footer">
                        <span class="filter-info"><span style="color: #000;font-weight: 100">
                            <?php 
                            if(!empty($_REQUEST['debg']) || !empty($_REQUEST['fing'])){ ?>
                                <b>Date de début : </b><?php echo date("d-m-Y", strtotime($_REQUEST['debg'])); ?>
                                <b> Date de fin : </b><?php echo date("d-m-Y", strtotime($_REQUEST['fing'])); ?>
                                <?php }else{ ?>

                                    <b>Période : </b>Ce mois-ci | 
                                    <?php } ?>
                                <?php if(!empty($_REQUEST['agencies'])){ ?>  
                                    <b>Agences : </b><?php echo $nb_agences; ?></span>
                                    <?php }else{ ?>
                            <b>Agences : </b>Toutes les agences</span>
                             <?php } ?>
                        </span><button class="btn-info-filter" type="button"><i class="fa fa-question-circle"></i></button>
                        <div class="filter-prop-content">
                            <button type="button" class="filter-info-details-close"><i class="fa fa-times-circle"></i></button>
                            <span class="filter-info-details">
                                <?php if(!empty($_REQUEST['debg']) || !empty($_REQUEST['fing'])){ ?>
                                <b>Période : </b><br><br><b>Date de début : </b>
                                <?php echo date("d-m-Y", strtotime($_REQUEST['debg'])); ?><b> | Date de fin : </b><?php echo date("d-m-Y", strtotime($_REQUEST['fing'])); ?>
                                <?php }else{ ?>

                                <b>Période : </b>Ce mois-ci
                                <?php } ?>
                                <?php if(isset($_REQUEST['agencies'])){ ?>  
                                    <br><br><b>Agences : </b><?php echo $nom_agences; ?>
                                    <?php }else{ ?>
                                <br><br><b>Agences : </b>Toutes les agences
                                <?php } ?>
                            </span>
                        </div>
                    </div>
                </div>
              
                <div class="first-half card ui-state-default" id="motifsliste">
                    <div class="head-card">
                        <span class="head-card-title">Motifs</span>
                        <button class="btn-tools-card">
                            <i class="fa fa-tasks"></i> <span class="text-btn-tools-card">Filtrer</span>
                        </button>
                        <div class="dropdown-content">
                            <div style="text-align: center;margin-bottom: 5px;color: #000;width: 100%;font-size: 14px;margin-top: 5px;">Période</div>
                            <input type="text" name="deb" max="<?php echo date("d-m-Y");?>" class="deb" placeholder="Date de début">
                            <input type="text" name="fin" max="<?php echo date("d-m-Y");?>" class="fin" placeholder="Date de fin">
                            <input type="hidden" id="agcSelectList3_hidden">
                            <br>
                            <div style="text-align: center;margin-bottom: 5px;color: #000;width: 100%;font-size: 14px;margin-top: 5px;">Agence</div>
                            <select id="agcSelectList3" style="width: 100%;margin-top: 5px;" multiple="multiple">
                                <?php
                                foreach ($AGC_LIST as $agc) {
                                    ?>
                                    <option value="<?php echo $agc->id_agence; ?>" data-nom="<?php echo $agc->nom_agence; ?>"><?php echo $agc->nom_agence; ?></option>
                                    <?php
                                }
                                ?>
                            </select>
                            <input type="hidden" id="agccount3">
                            <div style="text-align: center;">
                                <button class="btn-validate-filter" onclick="filterChart('motifsliste', 'pie', 'motifsChart', 'agcSelectList3')">Valider</button>
                                <button class="btn-reset-filter" onclick="resetFilterChart('motifsliste', 'pie', 'motifsChart', 'agcSelectList3', 'agccount3')">Réinitialiser</button>
                            </div>
                        </div>
                    </div>
                    <div class="card-content motifsliste">
                    <?php if($result_5->rowCount() == 0 && count($values)>0){ ?><div class="text-empty-data">Aucun résultat</div><?php } ?>
                    <div id="motifsChart" style="width: 65%; height: 200px;<?php if($result_5->rowCount() == 0 && count($values)>0){ ?>display: none;<?php }else{ ?>display: inline-block;<?php } ?>top: -100px;" ></div>
                        <table class="tab-stat tab-mot" style="width: 33%;margin-top: -32px;<?php if($result_5->rowCount() == 0 && count($values)>0){ ?>display:none;<?php } ?>">
                            <thead>
                                <tr>
                                    <th>Motif</th>
                                    <th>Visite</th>
                                </tr>
                            </thead>
                            <tbody class="motif-rows rows">
                                <?php  
                                  foreach($MOTIFS_LIST as $MOTIF)  
                                  {  
                                    if(isset($MOTIF->type)){
                                    ?>
                                    <tr>
                                        <td class="card-tooltip"><?php echo $MOTIF->code;?>
                                              <span class="card-tooltiptext"><?php echo $MOTIF->type;?></span>
                                        </td>
                                        <td>
                                            <?php echo round($MOTIF->value);?>
                                        </td>
                                   </tr>
                                       <?php
                                   }
                                  }  
                                  ?>  
                            </tbody>
                        </table>
                    </div>
                    <div class="card-footer">
                        <span class="filter-info"><span style="color: #000;font-weight: 100">
                            <?php 
                            if(!empty($_REQUEST['debg']) || !empty($_REQUEST['fing'])){ ?>
                                <b>Date de début : </b><?php echo date("d-m-Y", strtotime($_REQUEST['debg'])); ?>
                                <b> Date de fin : </b><?php echo date("d-m-Y", strtotime($_REQUEST['fing'])); ?>
                                <?php }else{ ?>

                                    <b>Période : </b>Ce mois-ci | 
                                    <?php } ?>
                                <?php if(!empty($_REQUEST['agencies'])){ ?>  
                                    <b>Agences : </b><?php echo $nb_agences; ?></span>
                                    <?php }else{ ?>
                            <b>Agences : </b>Toutes les agences</span>
                             <?php } ?>
                        </span><button class="btn-info-filter" type="button"><i class="fa fa-question-circle"></i></button>
                        <div class="filter-prop-content">
                            <button type="button" class="filter-info-details-close"><i class="fa fa-times-circle"></i></button>
                            <span class="filter-info-details">
                                <?php if(!empty($_REQUEST['debg']) || !empty($_REQUEST['fing'])){ ?>
                                <b>Période : </b><br><br><b>Date de début : </b>
                                <?php echo date("d-m-Y", strtotime($_REQUEST['debg'])); ?><b> | Date de fin : </b><?php echo date("d-m-Y", strtotime($_REQUEST['fing'])); ?>
                                <?php }else{ ?>

                                <b>Période : </b>Ce mois-ci
                                <?php } ?>
                                <?php if(isset($_REQUEST['agencies'])){ ?>  
                                    <br><br><b>Agences : </b><?php echo $nom_agences; ?>
                                    <?php }else{ ?>
                                <br><br><b>Agences : </b>Toutes les agences
                                <?php } ?>
                            </span>
                        </div>
                    </div>
                </div>
              
                <div class="second-half card ui-state-default" id="nfcliste">
                    <div class="head-card">
                        <span class="head-card-title">Type d'identification</span>
                        <button class="btn-tools-card">
                        <i class="fa fa-tasks"></i> <span class="text-btn-tools-card">Filtrer</span>
                        </button>
                        <div class="dropdown-content">
                            <div style="text-align: center;margin-bottom: 5px;color: #000;width: 100%;font-size: 14px;margin-top: 5px;">Période</div>
                            <input type="text" name="deb" max="<?php echo date("d-m-Y");?>" class="deb" placeholder="Date de début">
                            <input type="text" name="fin" max="<?php echo date("d-m-Y");?>" class="fin" placeholder="Date de fin">
                            <input type="hidden" id="agcSelectList4_hidden">
                            <br>
                            <div style="text-align: center;margin-bottom: 5px;color: #000;width: 100%;font-size: 14px;margin-top: 5px;">Agence</div>
                            <select id="agcSelectList4" style="width: 100%;margin-top: 5px;" multiple="multiple">
                                <?php
                                foreach ($AGC_LIST as $agc) {
                                    ?>
                                    <option value="<?php echo $agc->id_agence; ?>" data-nom="<?php echo $agc->nom_agence; ?>"><?php echo $agc->nom_agence; ?></option>
                                    <?php
                                }
                                ?>
                            </select>
                            <input type="hidden" id="agccount4">
                            <div style="text-align: center;">
                                <button class="btn-validate-filter" onclick="filterChart('nfcliste', 'pie', 'nfcChart', 'agcSelectList4')">Valider</button>
                                <button class="btn-reset-filter" onclick="resetFilterChart('nfcliste', 'pie', 'nfcChart', 'agcSelectList4', 'agccount4')">Réinitialiser</button>
                            </div>
                        </div>
                    </div>

                    <div class="card-content nfc">
                        <?php if($result_6->rowCount() == 0 && count($values)>0){ ?><div class="text-empty-data">Aucun résultat</div><?php } ?>
                        <div id="nfcChart" style="width: 69%; height: 200px;<?php if($result_6->rowCount() == 0 && count($values)>0){ ?>display: none;<?php }else{ ?>display: inline-block;<?php } ?>top: -100px;" ></div>
                        <table class="tab-stat" style="width: 30%;<?php if($result_6->rowCount() == 0 && count($values)>0){?>display:none;<?php } ?>">
                            <thead>
                                <tr>
                                    <th>Type</th>
                                    <th>Visite</th>
                                </tr>
                            </thead>
                            <tbody class="rows">
                                <?php  
                                $nfc_val = 0;
                                $standard_val = 0;
                                  foreach($NFC_LIST as $NFC)  
                                  {  
                                    if($NFC->type == 'NFC'){
                                        $nfc_val = $nfc_val + $NFC->value;
                                    }else{
                                        $standard_val = $standard_val + $NFC->value;
                                    }
                                  }  
                                  ?>
                                  <tr>
                                      <td>Standard</td>
                                      <td><?php echo $standard_val; ?></td>
                                  </tr>
                                  <tr>
                                      <td>NFC</td>
                                      <td><?php echo $nfc_val; ?></td>
                                  </tr>
                            </tbody>
                              
                        </table>
                    </div>
                    <div class="card-footer">
                        <span class="filter-info"><span style="color: #000;font-weight: 100">
                            <?php 
                            if(!empty($_REQUEST['debg']) || !empty($_REQUEST['fing'])){ ?>
                                <b>Date de début : </b><?php echo date("d-m-Y", strtotime($_REQUEST['debg'])); ?>
                                <b> Date de fin : </b><?php echo date("d-m-Y", strtotime($_REQUEST['fing'])); ?>
                                <?php }else{ ?>

                                    <b>Période : </b>Ce mois-ci | 
                                    <?php } ?>
                                <?php if(isset($_REQUEST['agencies'])){ ?>  
                                    <b>Agences : </b><?php echo $nb_agences; ?></span>
                                    <?php }else{ ?>
                            <b>Agences : </b>Toutes les agences</span>
                             <?php } ?>
                        </span><button class="btn-info-filter" type="button"><i class="fa fa-question-circle"></i></button>
                        <div class="filter-prop-content">
                            <button type="button" class="filter-info-details-close"><i class="fa fa-times-circle"></i></button>
                            <span class="filter-info-details">
                                <?php if(!empty($_REQUEST['debg']) || !empty($_REQUEST['fing'])){ ?>
                                <b>Période : </b><br><br><b>Date de début : </b>
                                <?php echo date("d-m-Y", strtotime($_REQUEST['debg'])); ?><b> | Date de fin : </b><?php echo date("d-m-Y", strtotime($_REQUEST['fing'])); ?>
                                <?php }else{ ?>

                                <b>Période : </b>Ce mois-ci
                                <?php } ?>
                                <?php if(isset($_REQUEST['agencies'])){ ?>  
                                    <br><br><b>Agences : </b><?php echo $nom_agences; ?>
                                    <?php }else{ ?>
                                <br><br><b>Agences : </b>Toutes les agences
                                <?php } ?>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
      <?php } else if($empty){ ?>
      <center><h3>Bienvenue sur le Back-Office d'administration.</h3></center>
      <?php } ?>
      </div>
    </div>






</div>
<?php include 'footer.php';?>
<script type="text/javascript" src="js/jquery.cookie.js"></script>
<script type="text/javascript">
    document.multiselect('#agcSelectList6');
    document.multiselect('#agcSelectList');
    document.multiselect('#agcSelectList1');
    document.multiselect('#agcSelectList2');
    document.multiselect('#agcSelectList3');
    document.multiselect('#agcSelectList4');
    $(document).ready(function(){
        $(".filterBlock").labelauty();
        
    });
    function toggleBlockChart(elementChecked, block){
        if($('#'+elementChecked).attr('checked')){
            $('#'+block).fadeIn(800);
        }else{
            $('#'+block).fadeOut(800);
        }
    }
    
    function agenciesInPOPUP(status, title){
        $.ajax({
            type: "GET",
            url: "ajax/getList.php?type=agenciesInPopup&status="+status,
            success: function(result) {
                var POP = $('<div></div>').html(result).dialog({autoOpen: false,title: title});
                POP.dialog({autoOpen:false, modal:true, draggable: false, width:360 ,height: 'auto'});
                POP.dialog("open");
            },
            error: function(data) {
                console.log('Erreur');
                //$('.attente').html(data);
            }
        });
    }
    $( function() {
        $.urlParam = function(name){
            var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
            if (results==null) {
               return null;
            }
            return decodeURI(results[1]) || 0;
        }
        //console.log($.urlParam('agencies'));

        $("#form-global-filter").submit(function(event){
            
            var deb = $(".debg").val();
            var fin = $(".fing").val();
            var agencies = $("#agcSelectList6").val();
            if((agencies == null) && ((deb == '')||(fin == ''))){
                event.preventDefault();
                var POP = $('<div></div>').html("<center>Vous devez sélectionner au moins une période <br> ou choisir une ou des agences.</center>").dialog({autoOpen: false, title: 'Erreur'});
                POP.dialog({autoOpen:false, modal:true, draggable: false, width:360, height:100, close:function(ev, ui){document.getElementById("email").focus(); } });
                POP.dialog("open");
            }
        });
        $("input").attr('autocomplete', 'off');
        $('.btn-filter-bloc-chart').click(function () {
            $('.global-filter').slideToggle(300);
            $('.dropdown-content').hide();
        });
        $( ".deb" ).datepicker({ dateFormat: 'dd-mm-yy',maxDate: 0,navigationAsDateFormat: true, nextText: 'Suiv >', prevText: '< Préc' }).bind("change",function(){
            var minValue = $(this).val();
            minValue = $.datepicker.parseDate("dd-mm-yy", minValue);
            minValue.setDate(minValue.getDate());
            $(".fin").datepicker( "option", "minDate", minValue );
        })
        $( ".fin" ).datepicker({ dateFormat: 'dd-mm-yy', maxDate: 0,navigationAsDateFormat: true, nextText: 'Suiv >', prevText: '< Préc' });
        $( ".debg" ).datepicker({ dateFormat: 'dd-mm-yy',maxDate: 0,navigationAsDateFormat: true, nextText: 'Suiv >', prevText: '< Préc' }).bind("change",function(){
            var minValue = $(this).val();
            minValue = $.datepicker.parseDate("dd-mm-yy", minValue);
            minValue.setDate(minValue.getDate());
            $(".fing").datepicker( "option", "minDate", minValue );
        })
        $( ".fing" ).datepicker({ dateFormat: 'dd-mm-yy', maxDate: 0,navigationAsDateFormat: true, nextText: 'Suiv >', prevText: '< Préc' });
        /* save order in coockies */
        $.cookie.json = true;
        var list = $.cookie('list')
        var children = $("#sortable").children().each(function(i) {
            $(this).data('number', i) // number the children
        })
        if (list && list.length) { // cookie order
            $.each(list, function(v, i) {
                $("#sortable").append(children.eq(i))
            })
        }

        $.fn.orderChildren = function(order) {
            this.each(function() {
                var el = $(this);
                for(var i = order.length - 1; i >= 0; i--) {
                    el.prepend(el.children(order[i]));
                }
            });
            return this;
        };

        $.cookie.json = true;
        var list = $.cookie('list')
        var children = $(".sortable").children().each(function(i) {
            $(this).data('number', i) // number the children
        })
        if (list && list.length) { // cookie order
            var panels = [];
            $.each(list, function(v, i) {
                var panelID = children.eq(i).data('panel');
                panels.push("#"+panelID);
                $(".sortable").append(children.eq(i))
            })
            $(".cards-container").orderChildren(panels);
        }

        $( ".sortable" ).sortable({
             revert: true,
             placeholder: 'drag-place-holder',
             forcePlaceholderSize: true, 
             connectWith: ".sortable",
             helper:function(event, element){return $(element).clone().addClass('dragging');},
             start: function (e, ui) {ui.item.show().addClass('ghost')},
             stop: function(e,ui){ui.item.show().removeClass('ghost')},
            update: function(e, ui) {
                var panels = [];
                ui.item.show().removeClass('ghost');
                var list = $(this).children().map(function() {
                    var panelID = $(this).data('panel');
                    panels.push("#"+panelID);
                    var order = $(this).data('number');
                    return order;
                }).get();
                $.cookie('list', list) // save new order
                
                // reorder panels
                $(".cards-container").orderChildren(panels);

            },      
             cursor:'move'
         })
         .disableSelection();
      } );
    

        var href = new URL(window.location.href);
        var c = href.searchParams.getAll("agencies[]");
        if(c.length>0){
            $('input[type=checkbox]').each(function () {
                for (var i = 0; i < c.length; i++) {
                    document.multiselect('#agcSelectList6').select(c[i]);
                 }
                
            });
            
        }
</script>
</body>

</html>