<?php
$version = "3.2.6";

// error_reporting(E_ALL);
// ini_set('display_errors', 'On');
function getPileStatsData($date, $agence, $conseiller, $motifs) {
    // Stats

    $data = array(
        // Nombre total de clients -- pas utilisé
        "COUNT(*) AS nb",
        // XXX à certains endroits on utilise le nombre de clients pris en charge ou pas, et à d'autres le nom de clients pris en charge uniquement
        // Nombre total avec rendez-vous, pris en charge par ce conseiller
        "COALESCE(SUM(CASE WHEN rdv=1 AND id_action=" . $conseiller->id_conseiller . " THEN 1 ELSE 0 END),0) AS nb_rdv_agent",
        // nombre total avec rendez-vous
        "COALESCE(SUM(CASE WHEN rdv=1 THEN 1 ELSE 0 END),0) AS nb_rdv",
        // Nombre total sans rendez-vous, pris en charge par ce conseiller
        "COALESCE(SUM(CASE WHEN rdv=0 AND id_action=" . $conseiller->id_conseiller . " THEN 1 ELSE 0 END),0) AS nb_srdv_agent",
        // nombre total sans rendez-vous
        "COALESCE(SUM(CASE WHEN rdv=0 THEN 1 ELSE 0 END),0) AS nb_srdv",
        // Nombre total Livraison, pris en charge par ce conseiller
        "COALESCE(SUM(CASE WHEN rdv=5 AND id_action=" . $conseiller->id_conseiller . " THEN 1 ELSE 0 END),0) AS nb_ship_agent",
        // nombre total Livraison
        "COALESCE(SUM(CASE WHEN rdv=5 THEN 1 ELSE 0 END),0) AS nb_ship",
        // attente moyenne pris en charge par ce conseiller
        "COALESCE(AVG(CASE WHEN date_priseencharge > date_arrivee AND id_action=" . $conseiller->id_conseiller . " THEN timestampdiff(SECOND,date_arrivee,date_priseencharge) END),0) AS da_agent ",
        // attente moyenne pris en charge
        "COALESCE(AVG(CASE WHEN date_priseencharge > date_arrivee THEN timestampdiff(SECOND,date_arrivee,date_priseencharge) END),0) AS da",
        // attente moyenne avec rendez-vous, pris en charge par ce conseiller
        "COALESCE(AVG(CASE WHEN date_priseencharge > date_arrivee AND rdv=1 AND id_action=" . $conseiller->id_conseiller . " THEN timestampdiff(SECOND,date_arrivee,date_priseencharge) END),0) AS da_rdv_agent",
        // attente moyenne avec rendez-vous
        "COALESCE(AVG(CASE WHEN date_priseencharge > date_arrivee AND rdv=1 THEN timestampdiff(SECOND,date_arrivee,date_priseencharge) END),0) AS da_rdv",
        // attente moyenne sans rendez-vous, pris en charge par ce conseiller
        "COALESCE(AVG(CASE WHEN date_priseencharge > date_arrivee AND rdv=0 AND id_action=" . $conseiller->id_conseiller . " THEN timestampdiff(SECOND,date_arrivee,date_priseencharge) END),0) AS da_srdv_agent",
        // attente moyenne sans rendez-vous
        "COALESCE(AVG(CASE WHEN date_priseencharge > date_arrivee AND rdv=0 THEN timestampdiff(SECOND,date_arrivee,date_priseencharge) END),0) AS da_srdv",
        // attente moyenne Livraison, pris en charge par ce conseiller
        "COALESCE(AVG(CASE WHEN date_priseencharge > date_arrivee AND rdv=5 AND id_action=" . $conseiller->id_conseiller . " THEN timestampdiff(SECOND,date_arrivee,date_priseencharge) END),0) AS da_ship_agent",
        // attente moyenne Livraison
        "COALESCE(AVG(CASE WHEN date_priseencharge > date_arrivee AND rdv=5 THEN timestampdiff(SECOND,date_arrivee,date_priseencharge) END),0) AS da_ship",
        // nombre pris en charge
        "COALESCE(SUM(CASE WHEN ca_clients.date_priseencharge > ca_clients.date_arrivee THEN 1 ELSE 0 END),0) AS nb_pris_en_charge",
        // nombre pris en charge avec rendez-vous
        "COALESCE(SUM(CASE WHEN rdv=1 AND ca_clients.date_priseencharge > ca_clients.date_arrivee THEN 1 ELSE 0 END),0) AS nb_pris_en_charge_rdv",
        // nombre pris en charge par ce conseiller, avec rendez-vous
        "COALESCE(SUM(CASE WHEN rdv=1 AND ca_clients.date_priseencharge > ca_clients.date_arrivee AND id_action=" . $conseiller->id_conseiller . " THEN 1 ELSE 0 END),0) AS nb_pris_en_charge_rdv_agent",
        // nombre pris en charge sans rendez-vous
        "COALESCE(SUM(CASE WHEN rdv=0 AND ca_clients.date_priseencharge > ca_clients.date_arrivee THEN 1 ELSE 0 END),0) AS nb_pris_en_charge_srdv",
        // nombre pris en charge par ce conseiller, Livraison
        "COALESCE(SUM(CASE WHEN rdv=0 AND ca_clients.date_priseencharge > ca_clients.date_arrivee AND id_action=" . $conseiller->id_conseiller . " THEN 1 ELSE 0 END),0) AS nb_pris_en_charge_srdv_agent",
        // nombre pris en charge sans rendez-vous
        "COALESCE(SUM(CASE WHEN rdv=5 AND ca_clients.date_priseencharge > ca_clients.date_arrivee THEN 1 ELSE 0 END),0) AS nb_pris_en_charge_ship",
        // nombre pris en charge par ce conseiller, Livraison
        "COALESCE(SUM(CASE WHEN rdv=5 AND ca_clients.date_priseencharge > ca_clients.date_arrivee AND id_action=" . $conseiller->id_conseiller . " THEN 1 ELSE 0 END),0) AS nb_pris_en_charge_ship_agent",
    );
    if ($GLOBALS["PILE_CONF"]["STATS"]["showMotifs"]) {
        for ($i = 0; $i < count($motifs); $i++) {
            if ($motifs[$i]->current_agency == 1) {
                array_push($data,
                        // nombre pris en charge pour motif N
                        "COALESCE(SUM(CASE WHEN FIND_IN_SET('" . $motifs[$i]->id_motif . "', motifs) AND ca_clients.date_priseencharge > ca_clients.date_arrivee THEN 1 ELSE 0 END),0) AS nb_pris_en_charge_motif_" . $motifs[$i]->id_motif,
                        // nombre pris en charge par ce conseiller, avec motif N
                        "COALESCE(SUM(CASE WHEN FIND_IN_SET('" . $motifs[$i]->id_motif . "', motifs) AND ca_clients.date_priseencharge > ca_clients.date_arrivee AND id_action=" . $conseiller->id_conseiller . " THEN 1 ELSE 0 END),0) AS nb_pris_en_charge_motif_" . $motifs[$i]->id_motif . "_agent"
                );
            }
        }
        if ($GLOBALS["BO_CONF"]["AFA"] && $agence->is_afa) {
            $actions = load_actions();
            foreach ($actions as $action) {
                if ($action->is_motif) {
                    array_push($data,
                            // nombre pris en charge pour motif N
                            "COALESCE(SUM(CASE WHEN rdv_type = '" . $action->id_action . "' AND ca_clients.date_priseencharge > ca_clients.date_arrivee THEN 1 ELSE 0 END),0) AS nb_pris_en_charge_motif_action_" . $action->id_action,
                            // nombre pris en charge par ce conseiller, avec motif N
                            "COALESCE(SUM(CASE WHEN rdv_type = '" . $action->id_action . "' AND ca_clients.date_priseencharge > ca_clients.date_arrivee AND id_action=" . $conseiller->id_conseiller . " THEN 1 ELSE 0 END),0) AS nb_pris_en_charge_motif_action_" . $action->id_action . "_agent"
                    );
                }
            }
        }
    }
    $meetingFilter = "";
    if ($GLOBALS["BO_CONF"]["MEETING"] && isset($agence->meeting)) {
        $meetingFilter = " AND rdv != 2 ";
    }
    $motifJoin = "";
    if($GLOBALS["PILE_CONF"]["STATS"]["showMotifs"] && ($GLOBALS["BO_CONF"]["MOTIFS"] || ($GLOBALS["BO_CONF"]["DYNAMIC_MOTIFS"] && $agence->is_motif))){
        $motifJoin = " LEFT JOIN (SELECT mc.id_client, GROUP_CONCAT(mc.id_motif) AS motifs FROM ca_client_motifs mc JOIN ca_clients c ON mc.id_client = c.id_client WHERE c.id_agence=" . $agence->id_agence . " GROUP BY mc.id_client) combinedmotifs ON ca_clients.id_client = combinedmotifs.id_client";
    }
    $q = "SELECT " . implode(", ", $data) . " FROM ca_clients" . $motifJoin . " WHERE id_agence = :id_agence AND date_arrivee >= CURRENT_DATE() " . $meetingFilter;
    $values = array(':id_agence' => $agence->id_agence);
    $result = excuteQuery($q, $values);
    $res = $result['stmt'];
    $stats = $res->fetchObject();

    return $stats;
}

function sec2hms($sec, $padHours = false) {
    $hms = "";
    $hours = intval(intval($sec) / 3600);
    if ($hours >= 24) {
        $days = intval($hours / 24);
        $plural = $days > 1 ? " Jours" : "Jour";
        $hours = $hours % 24;
        $hms .= sprintf("%s {$plural} ", $days);
    }
    if ($hours > 0) {
        $hoursLength = $padHours ? 2 : 1;
        $hms .= sprintf("%0{$hoursLength}dh ", $hours);
    }
    $minutesLength = ($hours > 0) ? 2 : 1;
    $hms .= sprintf("%0{$minutesLength}dm %02ds", ($sec / 60) % 60, $sec % 60);
    return $hms;
}

class fakeConseiller {

    public $status;
    public $id_agent = 0;
    public $id_conseiller = 0;
    public $blocked = 0;

}

class fakeAgence {

    public $nom_agence;
    public $id_agence = 0;
    public $code_agence = 0;
    public $eds = 0;
    public $coffre = 0;

}

function load_agence() {
    $meeting = ($GLOBALS["BO_CONF"]["MEETING"]) ? ", meeting" : "";
    $coffreQ = $GLOBALS["BO_CONF"]["COFFRE"] ? ",coffre " : "";
    $logoQ = $GLOBALS["BO_CONF"]["LOGO"] ? ",logo " : "";
    $afaQ = $GLOBALS["BO_CONF"]["AFA"] ? ",is_afa " : "";
    $infoQ = $GLOBALS["BO_CONF"]["PILETVC"] ? ",pile_tv_info " : "";
    $nfcQ = $GLOBALS["BO_CONF"]["NFCBYAGENCY"] ? ", nfc" : ''; 
    $motifQ = $GLOBALS["BO_CONF"]["DYNAMIC_MOTIFS"]?",is_motif ":"";
    $q = "SELECT id_agence, code_agence" . $coffreQ . $logoQ . $afaQ . $motifQ .",type_agence,is_active, nom_agence, eds" . $meeting . $infoQ . $nfcQ . " FROM ca_agences WHERE code_agence=:code_agence";
    $values = array(':code_agence' => $_REQUEST['IDA']);
    $result = excuteQuery($q, $values);
    $res = $result['stmt'];
    $agence = $res->fetchObject();
    $n = $res->rowCount();
    if ($n <= 0) {
        $agence = new fakeAgence();
        $agence->nom_agence = "non reconnu";
        // Redirection no agency
        if(isset($GLOBALS["PILE_CONF"]["REDIRECT_NO_AGENCY"]) && $GLOBALS["PILE_CONF"]["REDIRECT_NO_AGENCY"]){
            header('Location:'.$GLOBALS["PILE_CONF"]["REDIRECT_NO_AGENCY"]);
        }
    }
    if (!$GLOBALS["BO_CONF"]["LOGO"])
        $agence->logo = "../logos/logo.png";
    return $agence;
}

function load_entites($agence) {
    $entites = array();
    $q = "SELECT id_entite,entite,libelle, pile_color, borne_color FROM ca_entites WHERE id_agence=:id_agence AND supp=0 AND enabled=1";
    
    $values = array(':id_agence' => $agence->id_agence);
    $result = excuteQuery($q, $values);
    $res = $result['stmt'];
    while ($o = $res->fetchObject()) {
        array_push($entites, $o);
    }
    return $entites;
}

function load_user_cc($agence) {

    if ($agence->id_agence) {
        $matricule = "";
        if (isset($_REQUEST["MAT"])) {
            $matricule = $_REQUEST["MAT"];
        } else if (isset($_SESSION["matricule"])) {
            $matricule = $_SESSION['matricule'];
        }
        if ($matricule != "") {
            /* MC-20170602 By M.A */
            $_SESSION['matricule'] = $matricule;

            // conseiller connecté
            $qx = 'SELECT id_cc as id_conseiller, email, civ, nom, prenom, id_agent, IF(civ = "Mme", "assets/img/femme.png", "assets/img/homme.png") as photo FROM ca_users_cc WHERE id_agent=:id_agent AND supp IS NULL';
            $values = array(':id_agent' => $matricule);
            $result = excuteQuery($qx, $values);
            $res = $result['stmt'];
            
            $n = $result['stmt']->rowCount();
            if ($n > 0) {
                $conseiller = $res->fetchObject();

                $conseiller->profiles = array();
                $conseiller->status = 'reconnu';
                // Récupérer le status et date dernière activité pour le conseiller dans l'agence de la pile
                $conseiller->last_active = null;
                $conseiller->receive_notifications = 1;
                $conseiller->mobility_status = 0;
                $conseiller->temporary = 0;
                $conseiller->entite = 0;
                $conseiller->user_cc = 1;
                authentificate_conseiller($agence, $conseiller, $matricule);
                updateLastActivePileAFA($conseiller->id_conseiller);
            } else {
                $conseiller = new fakeConseiller();
                $conseiller->status = 'non_reconnu';
            }
        } else {
            $conseiller = new fakeConseiller();
            $conseiller->status = 'non_identifie';
        }
    } else {
        $conseiller = new fakeConseiller();
        $conseiller->status = 'non_identifie';
    }
    if ($conseiller->id_conseiller == 0 && $GLOBALS["PILE_CONF"]["MENU"]["CCM"]["ACCESS"]) {
        return load_conseiller($agence);
    }
    return $conseiller;
}

function getHash() {
    return isset($GLOBALS["BO_CONF"]["SECURITY"]["HASH"]) ? $GLOBALS["BO_CONF"]["SECURITY"]["HASH"] : '4Mb2llgMrcwuTu3cXWOr7kFPxxlf9SxdGwx4ofus0YJyDdOg';
}

function load_conseiller($agence) {
    $valuesBind = array();

    if ($agence->id_agence) {
        $matricule = "";
        if ($GLOBALS['PILE_CONF']["MAIL_GUICHET_AUTHENTICATION"]) {
            if (isset($_SESSION['auth']) && $_SESSION['auth'] && $_SESSION['user'] == 'conseiller' && isset($_SESSION['id']) && !isset($_REQUEST["email"])) { // Page reloading
                $authentication_by = 'id_conseiller =:id_conseiller';
                $matricule = $_SESSION["email"];
                $valuesBind[] = ['id_conseiller' => $_SESSION['id']];
                $typesBind .= "i";
            } else {
                if (isset($_REQUEST["mail"])) {
                    $matricule = $_REQUEST["mail"];
                } else if (isset($_SESSION["mail"])) {
                    $matricule = $_SESSION['mail'];
                }
                $mail = isset($_REQUEST["mail"]) ? $_REQUEST["mail"] : '';
                $password = isset($_REQUEST["password"]) ? $_REQUEST["password"] : '';
                $password = md5(getHash() . $password);
                $authentication_by = 'email =:email AND `password`=:password';
                $valuesBind[':email'] = $mail;
                $valuesBind[':password'] = $password;
                $typesBind .= "ss";
            }
        } else {
            if (isset($_REQUEST["MAT"])) {
                $matricule = $_REQUEST["MAT"];
            } else if (isset($_SESSION["matricule"])) {
                $matricule = $_SESSION['matricule'];
            }
            $authentication_by = 'id_agent=:matricule';
            $valuesBind[':matricule'] = $matricule;
        }
        if ($matricule != "") {
            /* MC-20170602 By M.A */
            $_SESSION['matricule'] = $matricule;
            $prenomColumn = ($GLOBALS["BO_CONF"]["CONSEILLER"]["prenom"]) ? ", prenom" : "";
            $daColumn = ($GLOBALS["BO_CONF"]["CONSEILLER"]["da"]) ? ", da" : "";
            $fctColumn = ($GLOBALS["BO_CONF"]["CONSEILLER"]["fonction"]) ? ", fonction" : "";
            $dlgColumn = ($GLOBALS["BO_CONF"]["DELEGATION"]) ? ", delegue" : "";
            $matriculeColumn = $GLOBALS["BO_CONF"]["MATRICULECOLUMNNAME"];
            $counterColumn = (isset($_REQUEST['counter']) && $GLOBALS['PILE_CONF']["MAIL_GUICHET_AUTHENTICATION"]) ? ', g.libelle as counter_label, g.numero as counter_number' : '';
            $leftJoins = (isset($_REQUEST['counter']) && $GLOBALS['PILE_CONF']["MAIL_GUICHET_AUTHENTICATION"]) ? (' LEFT JOIN ca_guichets g ON g.id_guichet =:counter ') : '';

            if (isset($_REQUEST['counter']) && $GLOBALS['PILE_CONF']["MAIL_GUICHET_AUTHENTICATION"]) {
                $valuesBind = array_merge(array(':counter'=>$_REQUEST['counter']),$valuesBind);
            }
            // conseiller connecté
            $qx = 'SELECT c.id_agence, c.id_conseiller, civ, nom' . $prenomColumn . ', ' . $matriculeColumn . $counterColumn . ', groupe as entite, email, receive_notifications, reinforcement, photo' . $daColumn . $fctColumn . ', c.inactif, a.id_agence as agent_agency, a.nom_agence as agent_agency_name, a.eds as agent_agency_eds, c.last_agency FROM ca_conseillers c LEFT JOIN ca_agences a ON a.id_agence =  c.id_agence' . $leftJoins . ' WHERE ' . $authentication_by . ' AND c.supp=:supp AND c.photo != :photo';
            
            // $valuesBind[] = [':supp' => 0];
            // $valuesBind[] = [':photo' => "assets/img/incognito.jpg"];
            $valuesBind[':supp'] = 0;
            $valuesBind[':photo'] = "assets/img/incognito.jpg";
            $result = excuteQuery($qx, $valuesBind);
            if ($result['status']) {
                $res = $result['stmt'];
                $nx = $res->rowCount();
                $profiles = array();
                if ($nx > 0) {
                    $conseiller = $res->fetchObject();

                    if ($GLOBALS["BO_CONF"]["CONSEILLER"]["multiple_profiles"]) {
                        // Liste de profils conseiller
                        $qy = "SELECT p.nom FROM ca_conseiller_profils cp 
                        LEFT JOIN ca_profils p ON p.id_profil = cp.id_profil 
                        WHERE id_conseiller=:id_conseiller";
                       $values = array(':id_conseiller' => $conseiller->id_conseiller);
                        $ry = excuteQuery($qy, $values);
                        $resy = $ry['stmt'];
                        $ny = $resy->rowCount();
                        $profiles = array();
                        if ($ny > 0) {
                            while ($o = $resy->fetchObject()) {
                                array_push($profiles, $o->nom);
                            }
                        }
                    }

                    $conseiller->status = 'reconnu';
                    // Récupérer le status et date dernière activité pour le conseiller dans l'agence de la pile
                    $rattache = false;
                    $qy = "SELECT status, last_active, receive_notifications, temporaire, id_fonction, id_profile, id_entite" . $dlgColumn . " FROM  ca_conseiller_agence ca WHERE id_conseiller = :id_conseiller AND id_agence = :id_agence";
                    $values = array(':id_conseiller' => $conseiller->id_conseiller, ':id_agence' => $agence->id_agence);
                    $ry = excuteQuery($qy, $values);
                    $resy = $ry['stmt'];
                    $ny = $resy->rowCount();
                    if ($ny > 0) {
                        $o = $resy->fetchObject();
                        $conseiller->last_active = $o->last_active;
                        $conseiller->receive_notifications = $o->receive_notifications;
                        $conseiller->mobility_status = $o->status; 
                        $conseiller->temporary = $o->temporaire;
                        $conseiller->entite = $o->id_entite;
                        $conseiller->id_profile = $o->id_profile;
                        $conseiller->id_fonction = $o->id_fonction;
                        if (($o->id_profile == 6 || ($GLOBALS["BO_CONF"]["DELEGATION"] && $o->delegue == 1)) && !in_array("DA", $profiles)) {
                            array_push($profiles, "DA");
                        }

                        $rattache = true;
                    } else {
                        $conseiller->status = 'non_rattache';
                        $conseiller->last_active = null;
                        $conseiller->receive_notifications = 0;
                        $conseiller->mobility_status = null;
                        $conseiller->temporary = 1;
                    }
                    $conseiller->profiles = $profiles;
                    // if (!isset($GLOBALS["USE_PERI"])){
                    if($GLOBALS["BO_CONF"]["MOBILITY"] == true || $ny > 0){
                        authentificate_conseiller($agence, $conseiller, $matricule);
                        if ($GLOBALS['PILE_CONF']["MAIL_GUICHET_AUTHENTICATION"]) {
                            $counter = $_REQUEST['counter'] ? $_REQUEST['counter'] : $_SESSION['counter'];
                            $conseiller->counter = $counter;
                            $conseiller->counter_label = $conseiller->counter_label;
                        }
                        if ($conseiller->last_agency != $agence->id_agence) {
                            $q = "UPDATE ca_conseillers SET last_agency = :last_agency WHERE id_conseiller = :id_conseiller";
                            $values = array(':last_agency' => $agence->id_agence, ':id_conseiller' => $conseiller->id_conseiller);
                            $r = excuteQuery($q, $values);
                        }

                        // CLEAR AUTH ATTEMPTS
                        if (!empty($GLOBALS["BO_CONF"]["AUTH_ATTEMPTS"]) && $GLOBALS["BO_CONF"]["AUTH_ATTEMPTS"]["ENABLED"]) {
                            clearLoginAttempts('pile');
                        }
                        updateLastActivePile($conseiller, $agence->id_agence,$conseiller->entite);
                    }
                    // }
                    
                } else {
                    $conseiller = new fakeConseiller();
                    if($GLOBALS["PILE_CONF"]["AGENT_FORM"]){
                        $conseiller->status = 'non_reconnu';
                    }else{
                        $conseiller->status = 'non_reconnu_non_agent_form';
                    }

                    // AUTH ATTEMPTS
                    if (!empty($GLOBALS["BO_CONF"]["AUTH_ATTEMPTS"]) && $GLOBALS["BO_CONF"]["AUTH_ATTEMPTS"]["ENABLED"]) {
                        list($attempts, $blocked) = getLoginAttempts('pile');
                        $attempts++;
                        updateLoginAttempts('pile', $mail, $attempts);
                        if ($blocked || (intval($attempts) >= $GLOBALS["BO_CONF"]["AUTH_ATTEMPTS"]["COUNT"])) {
                            $conseiller->blocked = 1;
                        }
                    }
                }
            } else {
                wts_die($result['stmt']->error);
            }
        } else {
            $conseiller = new fakeConseiller();
            $conseiller->status = 'non_identifie';
        }
    } else {
        $conseiller = new fakeConseiller();
        $conseiller->status = 'non_identifie';
    }
    return $conseiller;
}

function load_actions() {
    $actions = array();
    $q = "SELECT id_action, titre, code_action, is_motif FROM ca_actions WHERE is_active=1 GROUP BY id_action";
    $r = $GLOBALS['cnx']->query($q);
    while ($o = $r->fetchObject()) {
        $actions[$o->id_action] = $o;
    }
    return $actions;
}

function load_motifs($agence) {
    $motifs = array();
    $q = "SELECT m.id_motif,m.titre,m.code,m.couleur, IFNULL(ma.notif_rdv,0) as notif_rdv,  IFNULL(ma.notif_srdv,0) as notif_srdv, IF((IFNULL(ma.id_agence,0)=" . $agence->id_agence . "),1,0) as current_agency FROM ca_motifs m LEFT JOIN ca_motif_agence ma ON ma.id_motif = m.id_motif AND id_agence=:id_agence WHERE m.enabled=1 GROUP BY id_motif";
    $values = array(':id_agence' => $agence->id_agence);
    $result = excuteQuery($q, $values);
    $res = $result['stmt'];
    while ($o = $res->fetchObject()) {
        array_push($motifs, $o);
    }
    return $motifs;
}

function setAllowedAgencies() {
    $agences = array();
    $parent = $GLOBALS["BO_CONF"]["HIERARCHICAL"]["HIERARCHY"][count($GLOBALS["BO_CONF"]["HIERARCHICAL"]["HIERARCHY"]) - 2];
    if($GLOBALS["BO_CONF"]["HIERARCHICAL"]["ENABLED"]){
        $query = "SELECT id_agence FROM ca_agences a WHERE id_" . $parent . " IN (SELECT id_parent FROM ca_directeur_aps WHERE id_conseiller = :id_conseiller)";
    
        $values = array(':id_conseiller' => intval($_SESSION["id"]));
        $result = excuteQuery($query, $values);
        $res = $result['stmt'];
        while ($row = $res->fetch( PDO::FETCH_ASSOC )) {
            $agences[] = $row["id_agence"];
        }
    }

    // Rattachement
    $query = "SELECT id_agence FROM ca_conseiller_agence WHERE (temporaire = 0 OR (temporaire = 1 AND TIMESTAMPDIFF(SECOND,last_active,now()) < 15)) AND id_profile = 6 AND id_conseiller = :id_conseiller";
    $values = array(':id_conseiller' => intval($_SESSION["id"]));
    $result = excuteQuery($query, $values);
    $res = $result['stmt'];
    while ($row = $res->fetch( PDO::FETCH_ASSOC )) {
        $agences[] = $row["id_agence"];
    }
    
    //$_SESSION["agences"] = $_SESSION["agences"] ? array_merge($agences, $_SESSION["agences"]) : $agences;

    $_SESSION["agences"] = array_unique($agences);
    return implode(',', $_SESSION["agences"]);
}
function getMotifByTitle($title, $motifs) {
    foreach ($motifs as $motif) {
        if ($motif->titre == $title) {
            return $motif;
        }
    }
    return FALSE;
}

function getMotifByCode($code, $motifs) {
    foreach ($motifs as $motif) {
        if ($motif->code == $code) {
            return $motif;
        }
    }
    return FALSE;
}

function updateLastActivePile($conseiller, $id_agence, $entite) {
    $insert = false;
    // $default_status = $GLOBALS["PILE_CONF"]["DEFAULT_AGENT_STATUS"]?$GLOBALS["PILE_CONF"]["DEFAULT_AGENT_STATUS"]:0;
    $q = "SELECT count(1) AS nb FROM ca_conseiller_agence WHERE id_agence=:id_agence AND id_conseiller=:id_conseiller";
    $values = array(':id_agence' => intval($id_agence), ':id_conseiller' => intval($conseiller->id_conseiller));
    $result = excuteQuery($q, $values);
    $res = $result['stmt'];
    if ($res && $GLOBALS["BO_CONF"]["MOBILITY"]) {
        $o = $res->fetchObject();
        if ($o->nb == 0) {
            $id_entite = $entite ? $entite : 0;
            $id_entite = (isset($_REQUEST["id_entite"]) && intval($_REQUEST["id_entite"])) ? $_REQUEST["id_entite"] : 0; 
            $entite = $id_entite ? $id_entite : "(SELECT id_entite FROM ca_entites WHERE id_agence=" . intval($id_agence) . " AND supp=0 ORDER BY id_agence ASC LIMIT 1)";
            $q = "INSERT INTO ca_conseiller_agence (id_agence,id_conseiller, id_entite,id_orientation,last_active,date_creation, status, temporaire, id_fonction, id_profile) VALUES (:id_agence,:id_conseiller,".$entite.", (SELECT id_orientation FROM ca_orientations WHERE id_agence =:id_agence2 AND id_entite = :id_entite2 AND orientation = 2 ORDER BY id_entite ASC, date_creation ASC LIMIT 1), now(),now(), -1, 1, ".$conseiller->fonction.", (SELECT id_profil FROM ca_conseiller_profils WHERE id_conseiller = :id_conseiller1 ORDER BY id_profil ASC LIMIT 1))";
            $values = array(':id_agence' => intval($id_agence),
             ':id_conseiller' => intval($conseiller->id_conseiller),
              ':id_agence2' => intval($id_agence),
              ':id_entite2' => $id_entite,
              ':id_conseiller1' => intval($conseiller->id_conseiller));
            $result = excuteQuery($q, $values);
            $insert = true;
        }
    }
    if ($insert == false) {
        $entiteQ = $entite ? ", id_entite=" . $entite : "";
        $q = "UPDATE ca_conseiller_agence SET last_active=now()" . $entiteQ . " WHERE id_agence=:id_agence AND id_conseiller=:id_conseiller";
        $values = array(':id_agence' => intval($id_agence), ':id_conseiller' => intval($conseiller->id_conseiller));
        $result = excuteQuery($q, $values);
    }
}

function updateLastActivePileAFA($id_conseiller) {
    $values = array();
    if($_REQUEST["id_entite"]){
        $values[':id_entite'] = intval($_REQUEST["id_entite"]);
    }
    $entite = $_REQUEST["id_entite"] ? ", id_entite=:id_entite" : "";
    $q = "UPDATE ca_users_cc SET last_active=now()" . $entite . " WHERE id_cc=:id_cc";
    $values[':id_cc'] = intval($id_conseiller);
    $r = excuteQuery($q, $values);
}

function authentificate_conseiller($agence, $conseiller, $MATRICULE) {
    $conName = ($GLOBALS["BO_CONF"]["CONSEILLER"]["prenom"]) ? $conseiller->prenom . " " . $conseiller->nom : $conseiller->nom;
    $_SESSION['auth'] = "ok";
    $_SESSION['id'] = $conseiller->id_conseiller;
    $_SESSION['agence'] = $agence->id_agence;
    $_SESSION['nom'] = $conName;
    $_SESSION['app_id'] = "BORNE_AAA";
    $_SESSION['matricule'] = $MATRICULE;
    $_SESSION['email'] = $conseiller->email;
    $user_profiles = array();
    if (!in_array("DA", $conseiller->profiles) && ($conseiller->agent_agency == $agence->id_agence && ($conseiller->da == 1 || $conseiller->dlg == 1)))
        $user_profiles[] = "DA";
    $_SESSION['profiles'] = array_merge($user_profiles, $conseiller->profiles);
    $_SESSION['user'] = (in_array('ADMIN', $user_profiles)) ? 'admin' : 'conseiller';
    $restrictAgencies = isset($GLOBALS["BO_CONF"]["HIERARCHICAL"]["RESTRICT_AGENCIES"]) ? $GLOBALS["BO_CONF"]["HIERARCHICAL"]["RESTRICT_AGENCIES"] : true;
    if ($GLOBALS["BO_CONF"]["HIERARCHICAL"]["ENABLED"] && $restrictAgencies) {
        setAllowedAgencies();
    } else {
        $_SESSION['agences'] = $_SESSION['agences'] ? $_SESSION['agences'] : array();
        if ($_SESSION['agence'] && !in_array($_SESSION['agence'], $_SESSION['agences'])) {
            $_SESSION['agences'][] = $_SESSION['agence'];
        }
    }
    setPermissions();
}

function getReinforcementStatus($agence) {
    $q = "SELECT id,IF(status = 0 , 0, IF(TIMESTAMPDIFF(SECOND,date_intervention,now()) < " . $GLOBALS["PILE_CONF"]["REINFORCEMENTDELAY"] . ",1,-1)) as 'status',
					CONCAT(cd.civ,' ',cd.prenom,' ',cd.nom) as 'demandeur',
					CONCAT(ci.civ,' ',ci.prenom,' ',ci.nom) as 'intervenant'
			 FROM ca_renforts r
			 LEFT JOIN ca_conseillers cd ON cd.id_conseiller = r.demandeur
			 LEFT JOIN ca_conseillers ci ON ci.id_conseiller = r.intervenant
			 WHERE r.id_agence =:id_agence ORDER BY id DESC LIMIT 0,1";
             $values = array(':id_agence'=> $agence->id_agence);
    $result = excuteQuery($q, $values);
    $res = $result['stmt'];
    $o = $res->fetchObject();
    $status = ($o->status != null) ? $o->status : -1;
    $id = ($o->id != null) ? $o->id : null;
    $result = array("id" => $id, "status" => $status, "demandeur" => $o->demandeur, "intervenant" => $o->intervenant);
    return $result;
}

function setPermissions() {
    $profiles = "";
    $permissionsArray = array();
    foreach ($_SESSION['profiles'] as $value) {
        $q = "SELECT id_profil FROM ca_profils WHERE nom = :nom";
        $values = array(':nom' => $value);
        $result = excuteQuery($q, $values);
        $res = $result['stmt'];
        $id_profil = $res->fetch( PDO::FETCH_ASSOC )['id_profil'];
        $profiles .= $id_profil . ',';
    }
    if ($_SESSION['profile'] && !in_array($_SESSION['profile'], $_SESSION['profiles'])) {
        $profiles .= $_SESSION['profile'] . ',';
    }
    if ($profiles) {
        $profiles = rtrim($profiles, ',');
        $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 (:profiles)";
         $values = array(':profiles' => $profiles);
    $result = excuteQuery($query, $values);
    $permissionsResult = $result['stmt'];
        while ($perm = $permissionsResult->fetchObject()) {
            $permissionsArray[] = $perm->type_permission;
        }
    }
    $_SESSION['permissions'] = $permissionsArray;
}

function pile($SERVER, $PROJECT_TITLE) {
    // agence
    $agence = load_agence();
    $motifs = array();
    if ($agence) {
        // Conseiller (si fourni)
        $conseiller = load_conseiller($agence);
        // entites
        $entites = array();
        $entites = load_entites($agence);
        // motifs
        if ($GLOBALS["BO_CONF"]["MOTIFS"] || ($GLOBALS["BO_CONF"]["DYNAMIC_MOTIFS"] && $agence->is_motif)) {
            $motifs = load_motifs($agence);
        }
        if ($conseiller) {
            $dt = date('Y-m-d H:i:s');
            if (in_array($_REQUEST['IDA'], $GLOBALS["changeTimezone"])){
                $dt = changeTimeMG($dt);
            }
            else{
                $dtf = new DateTime($dto, new DateTimeZone('Europe/Paris'));
                $dtf->setTimezone(new DateTimeZone('Europe/Paris'));
                $dt = $dtf->format('Y-m-d H:i:s');
            }
            header("Cache-Control: no-cache");
            header("Pragma: no-cache");
            header("Expires: 0");

            if (isset($_REQUEST['action'])) {
                switch ($_REQUEST['action']) {
                    case "take":
                        $counterQ = $GLOBALS["BO_CONF"]["GUICHETS"] ? ", guichet=:counter" : "";
                        $q = "UPDATE ca_clients SET date_priseencharge=:dt " . $counterQ . ", id_action=:id_action where id_client=:id_client AND id_agence=:id_agence";
                        $stmt = $GLOBALS['cnx']->prepare($q) or wts_die(show_error());
                        if ($GLOBALS["BO_CONF"]["GUICHETS"]) {
                            $values = array(':dt'=>$dt, ':counter'=>$conseiller->counter, ':id_action'=>$conseiller->id_conseiller, ':id_client'=>$_REQUEST['id_client'], ':id_agence'=>$agence->id_agence);
                            
                        } else {
                            $values = array(':dt'=>$dt, ':id_action'=>$conseiller->id_conseiller, ':id_client'=>$_REQUEST['id_client'], ':id_agence'=>$agence->id_agence);
                        }
                        $result = excuteQuery($q, $values);
                        $r = $result['stmt'];
                        break;
                    case "finish":
                        $q = "UPDATE ca_clients SET date_cloture=:dt WHERE id_client=:id_client AND id_agence=:id_agence";
                        $values = array(':dt'=>$dt, ':id_client'=>$_REQUEST['id_client'], ':id_agence'=>$agence->id_agence);
                        $result = excuteQuery($q, $values);
                        $r = $result['stmt'];
                        break;
                    case "cancel":
                        $q = "UPDATE ca_clients SET date_cloture=:dt, cancelled=:cancelled WHERE id_client=:id_client AND id_agence=:id_agence";
                        $cancelledSql = 1;
                        $values = array(':dt'=>$dt, ':cancelled'=>$cancelledSql, ':id_client'=>$_REQUEST['id_client'], ':id_agence'=>$agence->id_agence);
                        $result = excuteQuery($q, $values);
                        $r = $result['stmt'];
                        break;
                    case "change_receive_notifications":
                    $receive_notifications = $_REQUEST['receive_notifications'] ? 1 : 0;
                        $q = "UPDATE ca_conseiller_agence SET receive_notifications=:receive_notifications WHERE id_agence=:id_agence AND id_conseiller=:id_conseiller";
                        $values = array(':receive_notifications' => $receive_notifications , ':id_agence' => $agence->id_agence, ':id_conseiller' => $conseiller->id_conseiller);
                        $r = excuteQuery($q, $values);
                        if ($conseiller->id_agence == $agence->id_agence) {
                            $q = "UPDATE ca_conseillers SET receive_notifications=:receive_notifications WHERE id_conseiller=:id_conseiller";
                            $values = array(':receive_notifications' => $receive_notifications , ':id_conseiller' => $conseiller->id_conseiller);
                            $r = excuteQuery($q, $values);
                        }
                        // mise à jour du conseiller
                        $conseiller = load_conseiller($agence);
                        break;
                    case "change_reinforcement":
                        $reinforcementStatus = $_REQUEST['reinforcement'] ? $_REQUEST['reinforcement'] : 0;
                        $q = "UPDATE ca_conseillers SET reinforcement=:reinforcement WHERE id_conseiller=:id_conseiller";
                        $values = array(':reinforcement' => $reinforcementStatus, ':id_conseiller' => $conseiller->id_conseiller);
                        $r = excuteQuery($q, $values);
                        if ($reinforcementStatus) {
                            // Insert
                            $q = "INSERT INTO ca_renforts (id_agence,demandeur,date_demande) VALUES(:id_agence,:id_conseiller,now())";
                            $values = array(':id_agence'=>$agence->id_agence, ':id_conseiller' => $conseiller->id_conseiller);
                            $r = excuteQuery($q, $values);
                        } else {
                            // Update
                            $q = "UPDATE ca_renforts SET status = 1 WHERE id_agence=" . $agence->id_agence . " AND demandeur=" . $conseiller->id_conseiller . "";
                            $values = array(':id_agence'=>$agence->id_agence, ':id_conseiller' => $conseiller->id_conseiller);
                            $r = excuteQuery($q, $values);
                        }

                        // mise à jour du conseiller
                        $conseiller = load_conseiller($agence);
                        break;

                    case "take_reinforcement":
                        $q = "UPDATE ca_renforts SET status=1, intervenant=" . $conseiller->id_conseiller . ", date_intervention=now() WHERE id_agence=" . $agence->id_agence . " AND status=0";
                        $values = array( ':id_conseiller' => $conseiller->id_conseiller, ':id_agence'=>$agence->id_agence);
                        $r = excuteQuery($q, $values);

                        $q = "UPDATE ca_conseillers SET reinforcement = 0 WHERE id_agence=" . $agence->id_agence . "";
                        $values = array(':id_agence'=>$agence->id_agence);
                        $r = excuteQuery($q, $values);

                        // mise à jour du conseiller
                        $conseiller = load_conseiller($agence);
                        break;
                }
            }

            // On calcule les stats et récupère les données après les modifications éventuelles
            $stats = getPileStatsData(date('Y-M-d'), $agence, $conseiller, $motifs);
            $data = getPileData($agence, $entites, $motifs);
        }
    }

    if (isset($_REQUEST['ajax'])) {
        header("Content-Type: application/json; charset=UTF-8");
        echo json_encode(array(
            'contenu_pile' => pileContenu($agence, $entites, $motifs, $conseiller, $data, $stats),
            'contenu_header' => headerContenu($agence, $conseiller, false, $SERVER),
            'conseiller' => $conseiller,
            'en_attente' => $data['en_attente'],
            'notif_colors' => getNotifsColors($entites, $motifs),
            'renfort' => (isset($GLOBALS["PILE_CONF"]["REINFORCEMENT"]) && $GLOBALS["PILE_CONF"]["REINFORCEMENT"]) ? getReinforcementStatus($agence) : false,
        ));
    } else {
        header("Content-Type: text/html; charset=UTF-8");
        pileHeader($agence, $conseiller, $SERVER, $PROJECT_TITLE);
        echo pileContenu($agence, $entites, $motifs, $conseiller, $data, $stats);
        $interfaced = (isset($GLOBALS["USE_PERI"]) && $GLOBALS["USE_PERI"]) ? 1 : 0;
        $mobility = (isset($GLOBALS["BO_CONF"]["MOBILITY"]) && $GLOBALS["BO_CONF"]["MOBILITY"]) ? 1 : 0;
        $afa = (basename($_SERVER['PHP_SELF']) == "pileAFA.php") ? 1 : 0;
        $notifsColors = getNotifsColors($entites, $motifs);
        $colorByEntity = (isset($GLOBALS["BO_CONF"]["COLORBYENTITY"])) ? $GLOBALS["BO_CONF"]["COLORBYENTITY"] : false;
        $notifMyst = (isset($GLOBALS["PILE_CONF"]["FORCENOTIFMYST"])) ? $GLOBALS["PILE_CONF"]["FORCENOTIFMYST"] : false;
        $renfort = (isset($GLOBALS["PILE_CONF"]["REINFORCEMENT"]) && $GLOBALS["PILE_CONF"]["REINFORCEMENT"]) ? getReinforcementStatus($agence) : false;
        $currentMotifs = array_filter($motifs, 'filterMotifs');
        $authenticatedby = ($GLOBALS["PILE_CONF"]["MAIL_GUICHET_AUTHENTICATION"]) ? 1 : 0;
        echo '<script>initPile(' . $interfaced . ',' . $mobility . ',' . json_encode($colorByEntity) . ',' . $notifsColors . ',' . json_encode($conseiller) . ',' . json_encode($data['en_attente']) . ',' . json_encode($agence) . ',"' . $notifMyst . '",' . json_encode($renfort) . ',' . json_encode($currentMotifs) . ',' . $authenticatedby . ',' . $afa . ');</script>';
        pileFooter($agence, $SERVER);
    }
}

function pileAFA($SERVER, $PROJECT_TITLE) {
    // agence
    $agence = load_agence();
    if ($agence) {
        // Conseiller (si fourni)
        $conseiller = load_user_cc($agence);
        // entites
        $entites = array();
        $entites = load_entites($agence);
        // motifs
        $motifs = array();
        if ($conseiller) {
            $dt = date('Y-m-d H:i:s');
            if (in_array($_REQUEST['IDA'], $GLOBALS["changeTimezone"])){
                $dt = changeTimeMG($dt);
            }
            else{
                $dtf = new DateTime($dto, new DateTimeZone('Europe/Paris'));
                $dtf->setTimezone(new DateTimeZone('Europe/Paris'));
                $dt = $dtf->format('Y-m-d H:i:s');
            }
            header("Cache-Control: no-cache");
            header("Pragma: no-cache");
            header("Expires: 0");

            if (isset($_REQUEST['action'])) {
                switch ($_REQUEST['action']) {
                    case "take":
                        $q = "SELECT `id_agence`, `date_arrivee`, `date_priseencharge`, `id_action`, `id_cc`, `entite`, `civ`, `nom`, `prenom`, `nfcprov`, `message`, `phone` FROM ca_pile_cc WHERE id_client_cc=:id_client_cc AND id_agence=:id_agence";
                        $values = array(':id_client_cc' => intval($_REQUEST['id_client']), ':id_agence' => $agence->id_agence);
                        $result = excuteQuery($q, $values);
                        $r = $result['stmt'];
                        while ($o = $r->fetchObject()) {
                            $q = 'INSERT INTO ca_historique_pile_cc (`id_agence`, `date_arrivee`, `date_priseencharge`, `id_action`, `id_cc`, `entite`, `civ`, `nom`, `prenom`, `nfcprov`, `message`, `phone`) VALUES 
							(:id_agence,:date_arrivee,:date_priseencharge,:id_action,:id_cc,:entite, :civ,:nom,:prenom,:nfcprov,:message,:phone) ';
                            $values = array(
                                ':id_agence' => $o->id_agence, ':date_arrivee' => $o->date_arrivee,
                                ':date_priseencharge' => $dt, ':id_action' => $o->id_action, 
                                ':id_cc' => $conseiller->id_conseiller, ':entite' => $o->entite, ':civ' => $o->civ,
                                ':nom' => $o->nom,':prenom' => $o->prenom, ':nfcprov' => $o->nfcprov,
                                ':message' => $o->message,'phone' => $o->phone
                            );
                            $stmt = excuteQuery($q, $values);
                            if ($stmt['status']) {
                                $q = "DELETE FROM ca_pile_cc WHERE id_client_cc=:id_client_cc AND id_agence=:id_agence";
                                $values = array(':id_client_cc'=>intval($_REQUEST['id_client']), ':id_agence'=>$agence->id_agence);
                                $r = excuteQuery($q, $values);
                            }
                        }
                        break;
                    case "change_receive_notifications":
                    $receive_notifications = ($_REQUEST['receive_notifications'] ? 1 : 0);
                        $q = "UPDATE ca_conseiller_agence SET receive_notifications=:receive_notifications WHERE id_agence=:id_agence AND id_conseiller=:id_conseiller";
                        $values = array(':receive_notifications' => $receive_notifications, ':id_agence'=>$agence->id_agence,
                            ':id_conseiller' => $conseiller->id_conseiller);
                        $r = excuteQuery($q, $values);
                        if ($conseiller->id_agence == $agence->id_agence) {
                            $q = "UPDATE ca_conseillers SET receive_notifications=:receive_notifications WHERE id_conseiller=:id_conseiller";
                            $values = array(':receive_notifications' => $receive_notifications,
                            ':id_conseiller' => $conseiller->id_conseiller);
                            $r = excuteQuery($q, $values);
                        }
                        // mise à jour du conseiller
                        $conseiller = load_user_cc($agence);
                        break;
                }
            }

            // On calcule les stats et récupère les données après les modifications éventuelles
            $data = array("en_attente" => listeClientsAFA($agence, $conseiller));
        }
    }
    if (!$GLOBALS["BO_CONF"]["AFA"] || !$agence->is_afa || (!$conseiller->user_cc && $conseiller->id_agence == 0)) {
        $agence = load_agence();
        pileHeader($agence, null, $SERVER, $PROJECT_TITLE, true);
        echo "<h1>Vous n'êtes pas autorisé à accéder à cette page.</h1>";
        pileFooter($agence, $SERVER);
        return;
    }
    $stats = null;
    if (isset($_REQUEST['ajax'])) {
        header("Content-Type: application/json; charset=UTF-8");
        echo json_encode(array(
            'contenu_pile' => pileContenuAFA($agence, $entites, $motifs, $conseiller, $data, $stats),
            'contenu_header' => headerContenu($agence, $conseiller, false, $SERVER),
            'conseiller' => $conseiller,
            'en_attente' => $data['en_attente'],
            'renfort' => false,
        ));
    } else {
        header("Content-Type: text/html; charset=UTF-8");
        pileHeader($agence, $conseiller, $SERVER, $PROJECT_TITLE);
        echo pileContenuAFA($agence, $entites, $motifs, $conseiller, $data, $stats);
        if ($GLOBALS["PILE_CONF"]["NOTIFS"]) {
            $interfaced = 0;
            $mobility = 0;
            $notifsColors = getNotifsColors($entites, $motifs);
            $colorByEntity = (isset($GLOBALS["BO_CONF"]["COLORBYENTITY"])) ? $GLOBALS["BO_CONF"]["COLORBYENTITY"] : false;
            $notifMyst = (isset($GLOBALS["PILE_CONF"]["FORCENOTIFMYST"])) ? $GLOBALS["PILE_CONF"]["FORCENOTIFMYST"] : false;
            $afa = (basename($_SERVER['PHP_SELF']) == "pileAFA.php") ? true : false;
            $renfort = false;
            $currentMotifs = array();
            $mailAuthentication = $GLOBALS["PILE_CONF"]["MAIL_GUICHET_AUTHENTICATION"] ? $GLOBALS["PILE_CONF"]["MAIL_GUICHET_AUTHENTICATION"] : false;
            $currentMotifs = array();
            echo '<script>initPile(' . $interfaced . ',' . $mobility . ',' . json_encode($colorByEntity) . ',' . $notifsColors . ',' . json_encode($conseiller) . ',' . json_encode($data['en_attente']) . ',' . json_encode($agence) . ',"' . $notifMyst . '",' . json_encode($renfort) . ',' . json_encode($currentMotifs) . ',' . json_encode($mailAuthentication) . ',' . $afa . ');</script>';
        }
        pileFooter($agence, $SERVER);
    }
}

function filterMotifs($v) {
    return $v->current_agency == 1;
}

function headerContenu($agence, $conseiller, $nocontent = false, $SERVER) {
    $html = $noTimer = "";
    $reinforcement = $GLOBALS["PILE_CONF"]["REINFORCEMENT"] ? getReinforcementStatus($agence) : false;
    if (!$GLOBALS["PILE_CONF"]["WHOISONLINE"]) {
        $html .= '<div id="logo"><a href="../admin/dashboard.php"><img src="/' . $agence->logo . '" border="0"/></a></div>';
    } else {
        $hidden = ' style=" display:none;"';
    }
    $html .= '<div id="timer"' . $hidden . '> </div>';
    $noTimer .= $GLOBALS['PILE_CONF']['WHOISONLINE'] ? ' no-timer' : '';
    if ($reinforcement && $reinforcement['status'] != -1) { // -1 : hidden / 0 : red / 1 : green
        if ($reinforcement['status'] == 1) {
            $html .= "<div class='reinforcement-alert green" . $noTimer . "' id='reinforcement-btn'>Demande prise en charge par " . $reinforcement["intervenant"] . "</div>";
        } else {
            $html .= "<div class='reinforcement-alert" . $noTimer . "' id='reinforcement-btn'>" . $GLOBALS["PILE_CONF"]["LABEL_REINFORCEMENT"] . "<span>Prendre en charge</span></div>";
        }
    }
    $html .= '<div id="consInfos" class="' . ((isset($agence->notifs) && $agence->notifs == true) ? "" : "no-notifs") . '">';
    $html .= $nocontent ? '' : getAgentBoxInfos($agence, $conseiller, $reinforcement, $SERVER);
    $html .= '</div>';
    $html .= $nocontent ? '' : whoIsOnlineScroller($agence, $conseiller, $reinforcement, $SERVER);
    $html .= getPileMenu($agence, $conseiller, $reinforcement, $SERVER);
    return $html;
}

function getPileMenu($agence, $conseiller, $reinforcement, $SERVER) {
    $online = $pro = $director = $accessDirector = false;
    $online = (isset($_SESSION['matricule']) && $conseiller && !($conseiller instanceof fakeConseiller)) ? true : false;
    $publicStats = (!isset($GLOBALS["PILE_CONF"]["MENU"]["STATS"]["DASHBOARD"]["PUBLIC"]) || $GLOBALS["PILE_CONF"]["MENU"]["STATS"]["DASHBOARD"]["PUBLIC"]) ? true : false;
    $transfert = (isset($GLOBALS["PILE_CONF"]["MENU"]["TRANSFERT"]) && $GLOBALS["PILE_CONF"]["MENU"]["TRANSFERT"]["ENABLED"]) ? true : false;
    $delegation = (isset($GLOBALS["BO_CONF"]["DELEGATION"]) && $GLOBALS["BO_CONF"]["DELEGATION"]) ? true : false;
    $afa = (isset($GLOBALS["BO_CONF"]["AFA"]) && $GLOBALS["BO_CONF"]["AFA"]) ? true : false;
    if ($online) {
        $pro = (isset($_SESSION['profiles']) && (in_array("PRO", $_SESSION['profiles']) || in_array("DAM", $_SESSION['profiles']))) ? true : false;
        $director = ($GLOBALS["NOTIF_CONF"]["VIEWPOPUPBUTTON"] == "ALL" || $conseiller->id_profile == 6 && ($GLOBALS["NOTIF_CONF"]["VIEWPOPUPBUTTON"] == "DA" && isset($_SESSION['profiles']) && in_array("DA", $_SESSION['profiles']))) ? true : false;
        $accessDirector = (!isset($GLOBALS["PILE_CONF"]["MENU"]["STATS"]["DASHBOARD"]["ACCESS"]) || $GLOBALS["PILE_CONF"]["MENU"]["STATS"]["DASHBOARD"]["ACCESS"] == true) ? true : false;
    }
    $html = '
					<div id="menu">
						<i class="fa fa-bars" aria-hidden="true"></i>
						<div id="menu-items" style="display:none;">
							<ul>';
    if ($online) {
        if (basename($_SERVER['PHP_SELF']) === "pileAFA.php" && $afa && $agence->is_afa) {
            if (!$conseiller->user_cc && $GLOBALS["PILE_CONF"]["MENU"]["CCM"]["ACCESS"]) {
                $html .= '<li><i class="fa fa-envelope" aria-hidden="true"></i><span><a href="/pile/?IDA=' . $agence->code_agence . "&MAT=" . $conseiller->id_agent . '">Pile Agence</a></span></li>';
            }
        } else {
            $checkTypeAgence = ($GLOBALS["BO_CONF"]["AGENCE"]["MULTIPLE_TYPES"] && $agence->type_agence == 2) ? true : false ;
            $html .= ($GLOBALS["PILE_CONF"]["NOTIFS"] && !$conseiller->user_cc && !$checkTypeAgence) ? ('<li><input type="checkbox" id="receive_notifications"' . ($conseiller->receive_notifications ? "checked" : "") . '/> <span for="receive_notifications" class="notif_label">' . (isset($GLOBALS["PILE_CONF"]["LABEL_NOTIFS"]) ? $GLOBALS["PILE_CONF"]["LABEL_NOTIFS"] : 'Recevoir les notifications des SRDV et "conseiller inconnu"') . '</span></span></li>') : "";
            if ($GLOBALS["PILE_CONF"]["REINFORCEMENT"]) {
                $html .= '<li><input type="checkbox" id="reinforcement" ' . ($conseiller->reinforcement ? "checked" : "") . '/> <label for="reinforcement" class="notif_label">' . (isset($GLOBALS["PILE_CONF"]["LABEL_REINFORCEMENT"]) ? $GLOBALS["PILE_CONF"]["LABEL_REINFORCEMENT"] : 'DEMANDE DE RENFORT') . '</label></span></li>';
            }
            if (($director || $GLOBALS["NOTIF_CONF"]["VIEWNOTIFSTATUS"] == "ALL") && $GLOBALS["NOTIF_CONF"]["MANAGER_AGENTS"] !== "NONE") {
                $html .= '<li><i class="fa fa-cog" aria-hidden="true"></i><span class="manage-notifications" id="manage-notifications" onclick="manageNotificationsPopup()">Gestion des conseillers</span></li>';
            }
            if ($GLOBALS["BO_CONF"]["MEETING"] == true && $agence->meeting && $agence->meeting == 1) {
                $html .= '<li><img src="/assets/img/meeting-icon.png" class="meeting-icon"><span><a href="pileR.php?IDA='.$agence->code_agence.$matPath.'" target="_blank">Pile invitation</a></span></li>';
            }
            if ($transfert && $director) {
                $html .= '<li><i class="fa fa-exchange" aria-hidden="true"></i><span class="manage-transferts" id="manage-transferts" onclick="manageTransfertsPopup()">Mouvements conseillers</span></li>';
            }
            if ($delegation && $director) {
                $html .= '<li><i class="fa fa-users" aria-hidden="true"></i><span class="manage-delegations" id="manage-delegations" onclick="manageDelegationsPopup(' . $agence->id_agence . ')">Délégations</span></li>';
            }
            if ($publicStats || $director) {
                if ($accessDirector) {
                    $standardStatsLink = (!empty($GLOBALS["STATS_CONF"]["STANDARD_V2"]) && $GLOBALS["STATS_CONF"]["STANDARD_V2"]) ? ("/statistiques/charts/standard.php?filter_level=agence_" . $agence->id_agence) : ("/statistiques/?filter_level=agence_" . $agence->id_agence);
                    $html .= '<li><i class="fa fa-bar-chart" aria-hidden="true"></i><span><a target="_blank" href="' . $standardStatsLink . '">Rapport standard</a></span></li>';
                }
                if ($GLOBALS["PILE_CONF"]["STATS"]["DCC"]) {
                    $html .= '<li><i class="fa fa-table" aria-hidden="true"></i><span><a target="_blank" href="/statistiques/dcc/?agency=' . $agence->eds . '">Rapport détaillé</a></span></li>';
                }
                if ($GLOBALS["STATS_CONF"]["DAILY"]["ACCESS"] == "ALL") {
                    $html .= '<li><i class="fa fa-bar-chart" aria-hidden="true"></i><span><a target="_blank" href="/statistiques/charts/">Statistiques journalières</a></span></li>';
                }
                if ($GLOBALS["STATS_CONF"]["YEARLY"]["ACCESS"] == "ALL" || $GLOBALS["STATS_CONF"]["MONTHLY"]["ACCESS"] == "ALL" || $GLOBALS["STATS_CONF"]["WEEKLY"]["ACCESS"] == "ALL") {
                    $html .= '<li><i class="fa fa-pie-chart" aria-hidden="true"></i><span><a target="_blank" href="/statistiques/charts/weekly_chart.php">Statistiques an-mois-semaine</a></span></li>';
                }
                if ($GLOBALS["STATS_CONF"]["RECAP"]["ACCESS"] == "ALL") {
                    $html .= '<li><i class="fa fa-table" aria-hidden="true"></i><span><a target="_blank" href="/statistiques/charts/recap_table.php">Récapitulatif clients</a></span></li>';
                }
                if (isset($GLOBALS["PILE_CONF"]["MENU"]["DASHBOARD"]["ACCESS"]) && $GLOBALS["PILE_CONF"]["MENU"]["DASHBOARD"]["ACCESS"] == "DA" && $director) {
                    $html .= '<li><i class="fa fa-key" aria-hidden="true"></i><span><a target="_blank" href="/admin/dashboard.php">Administration</a></span></li>';
                }
            }

            if ($afa && $agence->is_afa && !$conseiller->user_cc && $GLOBALS["PILE_CONF"]["MENU"]["CCM"]["ACCESS"]) {
                $rappel_text = $GLOBALS["PILE_CONF"]["MENU"]["RAPPEL_TEXT"] ? $GLOBALS["PILE_CONF"]["MENU"]["RAPPEL_TEXT"] : 'Rappels';
                $html .= '<li><i class="fa fa-envelope" aria-hidden="true"></i><span><a href="/pile/pileAFA.php?IDA=' . $agence->code_agence . "&MAT=" . $conseiller->id_agent . '">'.$rappel_text.'</a></span></li>';
            }

            if ($pro) {
                $html .= '<li><span class="early-connection" id="early-connection" onclick="earlyConnectionPopup()">Connexion par anticipation</span></li>';
            }
        }
        $html .= '<li><i class="fa fa-sign-out" aria-hidden="true"></i><span><a href="./close.php?IDA=' . $agence->code_agence . '">Déconnexion</a></span></li>';
    } else {
        $html .= '<li><i class="fa fa-sign-in" aria-hidden="true"></i><span onclick="login(\'' . $agence->code_agence . '\')">Connexion</span></li>';
        if ($publicStats) {
            $html .= '<li><i class="fa fa-bar-chart" aria-hidden="true"></i><span><a href="/statistiques">Rapport standard</a></span></li>';
        }
    }
    $html .= '</ul>
						</div>
					</div>';
    return $html;
}

function getNotifsColors($entites, $motifs, $json = true) {
    $colors = $GLOBALS["PILE_CONF"]["COLORS"];
    foreach ($colors as $key => $color) {
        $colors[$key] = str_replace("#", "", $color);
    }
    if ($GLOBALS["BO_CONF"]["COLORBYENTITY"]) {
        foreach ($entites as $key => $entite) {
            $colors["ENTITE_" . $entite->id_entite] = str_replace("#", "", $entite->pile_color);
        }
    }
    if ($GLOBALS["BO_CONF"]["MOTIFSCOLORS"]) {
        foreach ($motifs as $key => $motif) {
            $colors["MOTIF_" . $motif->id_motif] = $motif->couleur ? str_replace("#", "", $motif->couleur) : $GLOBALS["PILE_CONF"]["COLORS"]["SRDV"];
        }
    }
    return $json ? json_encode($colors) : $colors;
}

function objetVenue($agence, $o, $forPile = 0, $motifs = NULL) {
    $afa_motifs = (isset($GLOBALS["BO_CONF"]["AFA_MOTIFS"]) && $GLOBALS["BO_CONF"]["AFA_MOTIFS"]) ? true : false;
    $dynamic_motifs = (isset($GLOBALS["BO_CONF"]["DYNAMIC_MOTIFS"]) && $GLOBALS["BO_CONF"]["DYNAMIC_MOTIFS"]) ? true : false;
    if (isset($agence->is_afa) && $agence->is_afa && $o->rdv_type == 1 && !$afa_motifs) {
        $actions = load_actions();
        $action = $actions[$o->rdv_type];
        if($dynamic_motifs){
            $objet = ($forPile && isset($GLOBALS["PILE_CONF"]["TITLE_NOTIFS_MOTIFS"]) && $GLOBALS["PILE_CONF"]["TITLE_NOTIFS_MOTIFS"]) ? $o->titres_motifs : $o->motif;
            $sep = (isset($GLOBALS["PILE_CONF"]["MOTIFS_SEPARATOR"]) && $GLOBALS["PILE_CONF"]["MOTIFS_SEPARATOR"]) ? $GLOBALS["PILE_CONF"]["MOTIFS_SEPARATOR"] : ' ';
            return str_replace("|", $sep, $objet);
        }
        return $action->titre;
    }
    $objet = ($forPile && isset($GLOBALS["PILE_CONF"]["TITLE_NOTIFS_MOTIFS"]) && $GLOBALS["PILE_CONF"]["TITLE_NOTIFS_MOTIFS"]) ? $o->titres_motifs : $o->motif;
    $sep = (isset($GLOBALS["PILE_CONF"]["MOTIFS_SEPARATOR"]) && $GLOBALS["PILE_CONF"]["MOTIFS_SEPARATOR"]) ? $GLOBALS["PILE_CONF"]["MOTIFS_SEPARATOR"] : ' ';
    return str_replace("|", $sep, $objet);
}

function getPileData($agence, $entites, $motifs) {
    return array(
        'en_attente' => listeClients($agence, $entites, "en_attente", $motifs),
        'pris_en_charge' => listeClients($agence, $entites, "pris_en_charge", $motifs),
        'traites' => listeClients($agence, $entites, "traites", $motifs),
    );
}

function listeClientsAFA($agence, $conseiller) {
    $liste = array();
    $afa_motifs = ((isset($GLOBALS["BO_CONF"]["AFA_MOTIFS"]) && $GLOBALS["BO_CONF"]["AFA_MOTIFS"]) || (isset($GLOBALS["BO_CONF"]["DYNAMIC_MOTIFS"]) && $GLOBALS["BO_CONF"]["DYNAMIC_MOTIFS"])) ? true : false;
	$custom_recall = (!empty($GLOBALS["BORNE_CONF"]["CUSTOM_RECALL"])) ? ', creneau' : '';	
	$custom_recall_order = (!empty($GLOBALS["BORNE_CONF"]["CUSTOM_RECALL"])) ? 't.creneau ASC,' : '';
    $filter = $conseiller->user_cc ? "" : " AND id_agence = " . intval($agence->id_agence);
    $q = "SELECT `id_client_cc`, `id_agence`, `date_arrivee`, `date_priseencharge`, `date_cloture`, `id_action`, `id_cc`, `entite`, `civ`, `nom`, `prenom`, `nfcprov`, `message`, `phone`, `id_motif`, '0' as taken ".$custom_recall.", IF(date_priseencharge = '0000-00-00 00:00:00' OR date_priseencharge IS NULL, 0, 1) as pec, TIMESTAMPDIFF(SECOND,date_arrivee,now()) waiting_time 
	FROM ca_pile_cc WHERE (date_cloture IS NULL OR date_cloture = '0000-00-00 00:00:00')" . $filter . "
	UNION
	SELECT `id_client_cc`, `id_agence`, `date_arrivee`, `date_priseencharge`, `date_cloture`, `id_action`, `id_cc`, `entite`, `civ`, `nom`, `prenom`, `nfcprov`, `message`, `phone`, `id_motif`, '1' as taken ".$custom_recall.", IF(date_priseencharge = '0000-00-00 00:00:00' OR date_priseencharge IS NULL, 0, 1) as pec, TIMESTAMPDIFF(SECOND,date_arrivee,now()) waiting_time 
	FROM ca_historique_pile_cc WHERE (date_cloture IS NULL OR date_cloture = '0000-00-00 00:00:00')" . $filter;
    $q = "SELECT t.*" . ($conseiller->user_cc ? ", a.nom_agence" : "") . ", m.titre as motif,  act.titre as titre_action FROM (" . $q . ")t LEFT JOIN ca_actions act ON act.id_action = t.id_action";

    if ($conseiller->user_cc) {
        $q .= " LEFT JOIN ca_agences a ON a.id_agence = t.id_agence ";
    }
    if ($afa_motifs) {
        $q .= " LEFT JOIN ca_motifs m ON m.id_motif = t.id_motif";
    }

    $q .= " ORDER BY waiting_time DESC";
    $result = excuteQuery($q);
	$res = $result['stmt'];
	if($result['status']){
		while ($o = $res->fetchObject()) {
			$liste[$o->id_action][] = $o;
		}
	}
    return $liste;
}

function listeClients($agence, $entites, $type, $motifs) {
    $liste = array();
    $additionalColumns = "";
    $additionalColumns .= ($GLOBALS["BO_CONF"]["CLIENT"]["prenom"]) ? ", cl.prenom" : "";
    $additionalColumns .= ($GLOBALS["BO_CONF"]["CLIENT"]["company"]) ? ", cl.company" : "";
    $additionalColumns .= ($GLOBALS["BO_CONF"]["CONSEILLER"]["prenom"]) ? ", cs.prenom as conseillerPrenom" : "";
    $additionalColumns .= (($GLOBALS["BO_CONF"]["MOTIFS"] || ($GLOBALS["BO_CONF"]["DYNAMIC_MOTIFS"] && $agence->is_motif)) && $GLOBALS["PILE_CONF"]["STATS"]["showMotifs"]) ? ", group_concat(COALESCE(m.code,m.titre) ORDER BY m.id_motif ASC SEPARATOR '|') as motif, group_concat(m.titre SEPARATOR '|') as titres_motifs, group_concat(m.id_motif SEPARATOR '|') as motifs_ids" : "";
    $additionalColumns .= ($GLOBALS["BO_CONF"]["ENTITIES"] || $GLOBALS["BO_CONF"]["COLORBYENTITY"]) ? ", cl.entite" : "";
    $additionalColumns .= $GLOBALS["BO_CONF"]["AFA"] ? ", a.is_afa" : "";
    $additionalColumns .= ($GLOBALS["BO_CONF"]["DOUBLEAGENCE"]) ? ", cl.id_borne" : "";
    $additionalColumns .= isset($GLOBALS["BORNE_CONF"]["CLIENT_TYPE"]) ? ", cl.client" : "";
    $additionalColumns .= ($GLOBALS["BO_CONF"]["GUICHETS"]) ? ", cl.ticket, cl.guichet" : "";
    
    $leftJoins = (($GLOBALS["BO_CONF"]["MOTIFS"] || ($GLOBALS["BO_CONF"]["DYNAMIC_MOTIFS"] && $agence->is_motif)) && $GLOBALS["PILE_CONF"]["STATS"]["showMotifs"]) ? " LEFT JOIN ca_client_motifs cm ON cl.id_client=cm.id_client LEFT JOIN ca_motifs m ON cm.id_motif=m.id_motif" : "";
    $leftJoins .= $GLOBALS["BO_CONF"]["AFA"] ? " LEFT OUTER JOIN ca_agences a ON a.id_agence=cl.id_agence" : "";
    $meetingFilter = ($GLOBALS["BO_CONF"]["MEETING"] && isset($agence->meeting)) ? " AND rdv != 2" : "";

    $groupByClPrenom = ($GLOBALS["BO_CONF"]["CLIENT"]["prenom"]) ? ", prenom" : "";
    $groupByConsPrenom = ($GLOBALS["BO_CONF"]["CONSEILLER"]["prenom"]) ? ", conseillerPrenom" : "";
    $groupByDoubleBorne = ($GLOBALS["BO_CONF"]["DOUBLEAGENCE"]) ? ", id_borne" : "";
    $condition = " AND cl.rdv IN(0,1,5)";
    if ($type == "en_attente") {
        if (count($entites) > 1 && ($GLOBALS["PILE_CONF"]["MULTICOLUMNS"] == true)) {
            $i = 0;
            foreach ($entites as $entite) {
                $lnkEntite = ($GLOBALS["BO_CONF"]["ENTITELINKBYID"]) ? $entite->id_entite : $entite->entite;
                $q = "SELECT cl.id_client, cl.nbr, DATE_FORMAT(cl.date_arrivee, '%Hh%i') as date_arrivee,date_priseencharge, cl.date_cloture, cl.rdv, cl.rdv_type, cl.civ, cl.nom, cl.id_conseiller, cs.nom as conseillerNom" . $additionalColumns . "
					FROM ca_clients cl
					" . $leftJoins . "
					LEFT OUTER JOIN ca_conseillers cs ON cl.id_conseiller=cs.id_conseiller
					WHERE cl.date_arrivee >= CURRENT_DATE()
					AND cl.date_priseencharge='0000-00-00 00:00:00'
					AND cl.entite=:entite
					AND cl.id_agence=:id_agence
					".$meetingFilter.$condition;
				if($GLOBALS["PILE_CONF"]["ATTACHINCONNU"] && $i==0){
					$q .= " UNION
								SELECT cl.id_client, cl.nbr, DATE_FORMAT(cl.date_arrivee, '%Hh%i') as date_arrivee,date_priseencharge, cl.date_cloture, cl.rdv, cl.rdv_type, cl.civ, cl.nom, cl.id_conseiller, cs.nom as conseillerNom".$additionalColumns."
								FROM ca_clients cl
                                LEFT OUTER JOIN ca_agences a ON a.id_agence=cl.id_agence
								LEFT OUTER JOIN ca_conseillers cs ON cl.id_conseiller=cs.id_conseiller
								WHERE c.date_arrivee >= CURRENT_DATE()
								AND cl.date_priseencharge='0000-00-00 00:00:00'
								AND cl.id_agence=:id_agence
								".$meetingFilter.$condition;
                    $i++;
                }
                $q .= " GROUP BY id_client, nbr, date_arrivee, date_priseencharge, date_cloture, rdv, rdv_type, civ, nom" . $groupByClPrenom . ", id_conseiller, conseillerNom" . $groupByConsPrenom . $groupByDoubleBorne . "
						ORDER BY date_priseencharge ASC";
                        $values = array(':entite' => intval($lnkEntite),':id_agence' => intval($agence->id_agence));
                $result = excuteQuery($q, $values);
                $res = $result['stmt'];
                $tmp = array();
                while ($o = $res->fetchObject()) {
                    if(($GLOBALS["BO_CONF"]["MOTIFS"] || ($GLOBALS["BO_CONF"]["DYNAMIC_MOTIFS"] && $agence->is_motif))){
                        $o->objetVenue = objetVenue($agence, $o);
                        $o->objetVenuePile = objetVenue($agence, $o, 1, $motifs);
                    }
                    array_push($tmp, $o);
                }
                array_push($liste, $tmp);
            }
        } else if ($GLOBALS["PILE_CONF"]["RDV_SRDV_COLUMNS"] == true) {
            $choices = array("Sans Rendez-vous" => 0, "Rendez-vous" => "1", "Livraison" => "5");
            foreach ($choices as $choice) {
                $q = "SELECT cl.id_client, cl.nbr, DATE_FORMAT(cl.date_arrivee, '%Hh%i') as date_arrivee,date_priseencharge, cl.date_cloture, cl.rdv, cl.rdv_type, cl.civ, cl.nom, cl.id_conseiller, cs.nom as conseillerNom" . $additionalColumns . "
					FROM ca_clients cl
					" . $leftJoins . "
					LEFT OUTER JOIN ca_conseillers cs ON cl.id_conseiller=cs.id_conseiller
					WHERE cl.date_arrivee >= CURRENT_DATE()
					AND cl.date_priseencharge='0000-00-00 00:00:00'
					AND cl.rdv=:choice
					AND cl.id_agence=:id_agence
					".$meetingFilter.$condition;
				if($GLOBALS["PILE_CONF"]["ATTACHINCONNU"] && $i==0){
					$q .= " UNION
								SELECT cl.id_client, cl.nbr, DATE_FORMAT(cl.date_arrivee, '%Hh%i') as date_arrivee,date_priseencharge, cl.date_cloture, cl.rdv, cl.rdv_type, cl.civ, cl.nom, cl.id_conseiller, cs.nom as conseillerNom".$additionalColumns."
								FROM ca_clients cl
                                LEFT OUTER JOIN ca_agences a ON a.id_agence=cl.id_agence
								LEFT OUTER JOIN ca_conseillers cs ON cl.id_conseiller=cs.id_conseiller
								WHERE c.date_arrivee >= CURRENT_DATE()
								AND cl.date_priseencharge='0000-00-00 00:00:00'
								AND cl.id_agence=:id_agence
								" . $meetingFilter .$condition;
                    $i++;
                }
                $q .= " GROUP BY id_client, nbr, date_arrivee, date_priseencharge, date_cloture, rdv, rdv_type, civ, nom" . $groupByClPrenom . ", id_conseiller, conseillerNom" . $groupByConsPrenom . $groupByDoubleBorne . "
						ORDER BY date_priseencharge ASC";
                $values = array(':choice'=>intval($choice), ':id_agence' => intval($agence->id_agence));
                $result = excuteQuery($q, $values);
                $res = $result['stmt'];
                $tmp = array();
                while ($o = $res->fetchObject()) {
                    if(($GLOBALS["BO_CONF"]["MOTIFS"] || ($GLOBALS["BO_CONF"]["DYNAMIC_MOTIFS"] && $agence->is_motif))){
                        $o->objetVenue = objetVenue($agence, $o);
                        $o->objetVenuePile = objetVenue($agence, $o, 1, $motifs);
                    }
                    array_push($tmp, $o);
                }
                array_push($liste, $tmp);
            }
        } else {
            $q = "SELECT cl.id_client, cl.nbr, DATE_FORMAT(cl.date_arrivee, '%Hh%i') as date_arrivee,date_priseencharge, cl.date_cloture, cl.rdv, cl.rdv_type, cl.civ, cl.nom, cl.id_conseiller, cs.nom as conseillerNom" . $additionalColumns . "
				FROM ca_clients cl
				" . $leftJoins . "
				LEFT OUTER JOIN ca_conseillers cs ON cl.id_conseiller=cs.id_conseiller
				WHERE cl.date_arrivee >= CURRENT_DATE()
				AND cl.date_priseencharge='0000-00-00 00:00:00'
				AND cl.id_agence=:id_agence
				".$meetingFilter.$condition."
				GROUP BY id_client, nbr, date_arrivee, date_priseencharge, date_cloture, rdv, rdv_type, civ, nom".$groupByClPrenom.", id_conseiller, conseillerNom".$groupByConsPrenom.$groupByDoubleBorne."
				ORDER BY cl.date_priseencharge ASC";
            $values = array(':id_agence' => intval($agence->id_agence));
            $result = excuteQuery($q, $values);
            $res = $result['stmt'];
            $tmp = array();
            while ($o = $res->fetchObject()) {
                if(($GLOBALS["BO_CONF"]["MOTIFS"] || ($GLOBALS["BO_CONF"]["DYNAMIC_MOTIFS"] && $agence->is_motif))){
                    $o->objetVenue = objetVenue($agence, $o);
                    $o->objetVenuePile = objetVenue($agence, $o, 1, $motifs);
                }
                array_push($tmp, $o);
            }
            array_push($liste, $tmp);
        }
    } else if ($type == "pris_en_charge") {
        $q = "SELECT cl.id_client, cl.nbr, DATE_FORMAT(cl.date_arrivee, '%Hh%i') as date_arrivee,DATE_FORMAT(cl.date_priseencharge, '%Hh%i') as date_priseencharge, cl.date_cloture, cl.rdv, cl.rdv_type, cl.civ, cl.nom, cl.id_conseiller, cs.nom as conseillerNom, cl.id_action, csa.civ as civ_conseiller_action, csa.nom as nom_conseiller_action, csa.prenom as prenom_conseiller_action" . $additionalColumns . "
			FROM ca_clients cl
			" . $leftJoins . "
            LEFT OUTER JOIN ca_conseillers cs ON cl.id_conseiller=cs.id_conseiller
            LEFT OUTER JOIN ca_conseillers csa ON cl.id_action=csa.id_conseiller
			WHERE cl.date_arrivee >= CURRENT_DATE()
			AND cl.date_priseencharge!='0000-00-00 00:00:00'
			AND cl.date_priseencharge > cl.date_arrivee
			AND cl.date_cloture='0000-00-00 00:00:00'
			AND cl.id_agence=:id_agence
			".$meetingFilter.$condition."
			GROUP BY id_client, nbr, date_arrivee, date_priseencharge, date_cloture, rdv, rdv_type, civ, nom".$groupByClPrenom.", id_conseiller, conseillerNom".$groupByConsPrenom.$groupByDoubleBorne."
			ORDER BY cl.date_priseencharge ASC";
            $values = array(':id_agence' => intval($agence->id_agence));
        $result = excuteQuery($q, $values);
        $res = $result['stmt'];
        while ($o = $res->fetchObject()) {
            if(($GLOBALS["BO_CONF"]["MOTIFS"] || ($GLOBALS["BO_CONF"]["DYNAMIC_MOTIFS"] && $agence->is_motif))){
                $o->objetVenue = objetVenue($agence, $o);
                $o->objetVenuePile = objetVenue($agence, $o, 1, $motifs);
            }
            array_push($liste, $o);
        }
    } else if ($type == "traites") {
        if ($GLOBALS["PILE_CONF"]["AFFTAKEN"]) {
            $q = "SELECT cl.id_client, cl.nbr, DATE_FORMAT(cl.date_arrivee, '%Hh%i') as date_arrivee,DATE_FORMAT(cl.date_priseencharge, '%Hh%i') as date_priseencharge, cl.date_cloture, cl.rdv, cl.rdv_type, cl.civ, cl.nom, cl.id_conseiller, cs.nom as conseillerNom" . $additionalColumns . "
				FROM ca_clients cl
				" . $leftJoins . "
				LEFT OUTER JOIN ca_conseillers cs ON cl.id_conseiller=cs.id_conseiller
				WHERE cl.date_arrivee >= CURRENT_DATE()
				AND cl.date_priseencharge != '0000-00-00 00:00:00'
				AND cl.date_priseencharge > cl.date_arrivee
				AND cl.date_cloture != '0000-00-00 00:00:00'
				AND cl.id_agence=:id_agence
				".$meetingFilter.$condition."
				GROUP BY id_client, nbr, date_arrivee, date_priseencharge, date_cloture, rdv, rdv_type, civ, nom".$groupByClPrenom.", id_conseiller, conseillerNom".$groupByConsPrenom.$groupByDoubleBorne."
				ORDER BY cl.date_priseencharge DESC LIMIT 15";
            $values = array(':id_agence' => intval($agence->id_agence));
            $result = excuteQuery($q, $values);
            $res = $result['stmt'];
            while ($o = $res->fetchObject()) {
                if(($GLOBALS["BO_CONF"]["MOTIFS"] || ($GLOBALS["BO_CONF"]["DYNAMIC_MOTIFS"] && $agence->is_motif))){
                    $o->objetVenue = objetVenue($agence, $o);
                    $o->objetVenuePile = objetVenue($agence, $o, 1, $motifs);
                }
                array_push($liste, $o);
            }
        }
    }
    // var_dump($liste);
    return $liste;
}

function getEntityColors($entites) {
    $entityColors = array();
    if ($GLOBALS["BO_CONF"]["COLORBYENTITY"]) {
        // GENERATE COLORS ARRAY
        foreach ($entites as $key => $entite) {
            $entityColors[] = "entite" . intval($entite->id_entite);
        }
    } else if ($GLOBALS["BO_CONF"]["ENTITIES"] && !$GLOBALS["BO_CONF"]["COLORBYENTITY"]) {
        $entityColors = $GLOBALS["PILE_CONF"]["ENTITYCOLORS"];
    } else {
        $entityColors = array("red");
    }
    return $entityColors;
}

function getAttenteColumns($agence, $attenteData, $entites, $motifs) {
    $columns = "";
    $column = "";
    $entityColors = getEntityColors($entites);
    $comp = 0;
    
    foreach ($attenteData as $key => $columnData) {
        $column .= '
		<td class="pile-column attente" id="attente-column">

		<div id="attente">';

        $column .= "<div id='colonne1' valign='top'><span id='nbWaiting' class='nbWaiting title-" . $entityColors[$key] . "'>";
        if (count($attenteData) == 1 && $GLOBALS["PILE_CONF"]["MULTICOLUMNS"] == false) {
            // 	$column .= "	Clients en attente";
        } else if ($GLOBALS["PILE_CONF"]["RDV_SRDV_COLUMNS"] == true) {
            $choices = array("Sans Rendez-vous", "Rendez-vous", "Livraison");
            $column .= $choices[$key];
            $column .= " 	(" . count($columnData) . ")</span>";
        } else if (count($entites) == 1 && $GLOBALS["PILE_CONF"]["AFFTABS"] == true) {
            $column .= "    Clients en attente (" . count($columnData) . ")</span>";
        }  else {
            $column .= "" . $entites[$key]->libelle;
            $column .= " 	(" . count($columnData) . ")</span>";
        }
        $column .= "</div>
			<div id='wrapper1'>";

        $i = 0;
        foreach ($columnData as $o) {
            $cliType = "SANS RDV";
            $cliClass = "srdv";
            $btClass = "bt";
            $cliProgressBar = "orange";
            if ($o->rdv == 1) {
                // $cliClass = $entityColors[$comp];
                $indice = ($GLOBALS["BO_CONF"]["ENTITIES"] && count($entites) > 1) ? getEntiteIndiceByID($entites, $o->entite) : 0;
                $cliClass = $entityColors[$indice];
                if ($o->id_conseiller == 0) {
                    $cliType = "";
                    if ($GLOBALS["BO_CONF"]["GUICHETS"]) {
                        $cliType .= "Ticket : " . $o->ticket . "<br/>";
                    }
                    if ($GLOBALS["BO_CONF"]["AGENCE"]["MULTIPLE_TYPES"] && $agence->type_agence == 2) { // Type Borne RH
                        $cliType = "RDV | Votre interlocuteur n'est pas présent sur la borne";
                    } else {
                        $cliType = "RDV | Conseiller inconnu";
                    }

                    $cliClass = "myst";
                } else {
                    $cliType = "";
                    if ($GLOBALS["BO_CONF"]["GUICHETS"]) {
                        $cliType .= "Ticket : " . $o->ticket . "<br/>";
                    }
                    $cliType .= "RDV | ";
                    if ($GLOBALS["BO_CONF"]["CONSEILLER"]["prenom"])
                        $cliType .= $o->conseillerPrenom . " ";
                    $cliType .= $o->conseillerNom;
                }
            } else if ($o->rdv == 0) {
                // $cliClass = "myst";

                if ($GLOBALS["BO_CONF"]["GUICHETS"]) {
                    $cliType = "Ticket : " . $o->ticket . "<br/>SANS RDV";
                }
                $m = $o->objetVenue ? $o->objetVenue : $o->objetVenuePile;
                $dm = $GLOBALS["BO_CONF"]["DYNAMIC_MOTIFS"] && $agence->is_motif;
                if ((($GLOBALS["BO_CONF"]["MOTIFS"] || $dm)) && $m != ""){
                    if (!isset($GLOBALS["PILE_CONF"]["PANEL"]["MOTIF_TITLE"]) || !$GLOBALS["PILE_CONF"]["PANEL"]["MOTIF_TITLE"]) {
                        $cliType .= " : " . $m;
                    } else {
                        $cliType .= " : ";
                        $cliMotifs = explode(" ", $m);
                        foreach ($cliMotifs as $key => $value) {
                            $climotif = getMotifByCode($value, $motifs);
                            if (!$climotif) {
                                $brReplace = str_replace('<br/>',', ',$value);
                                $brReplace = str_replace('<br>',', ',$brReplace);
                                $cliType .= strip_tags($brReplace) . " ";
                            } else {
                                $brReplace = str_replace('<br/>',', ',$climotif->titre);
                                $brReplace = str_replace('<br>',', ',$brReplace);
                                $cliType .= strip_tags($brReplace) . " ";
                            }
                        }
                    }
                    $motif = getMotifByTitle($o->objetVenuePile, $motifs);
                    if ($GLOBALS["BO_CONF"]["MOTIFSCOLORS"]) {
                        if ($motif->id_motif) {
                            $cliClass = "motif" . $motif->id_motif;
                        } else {
                            $cliClass = "srdv";
                        }
                    }
                }

                if ($o->is_afa && $o->rdv_type == '1' && !$dm) {
                    $actions = load_actions();
                    $action = $actions[$o->rdv_type];
                    $cliType .= " | ".$action->titre;
                }
            }else if ($o->rdv == 5) {
                //Livraison
                $cliClass = 'ship';
                if ($GLOBALS["BO_CONF"]["GUICHETS"]) {
                    $cliType .= "Ticket : " . $o->ticket . "<br/>";
                }
                $cliType = "LIVRAISON";
            } else {
                // $cliClass = "meeting";
                $cliType = "Salle de réunion";
            }
            
            if($o->rdv != 5){
                $cliNomClient = str_replace("_", " & ", $o->civ);
                if ($GLOBALS["BO_CONF"]["CLIENT"]["prenom"])
                    $cliNomClient .= " " . $o->prenom;
                $cliNomClient .= " " . $o->nom;
            }else{
                $cliNomClient = '';
            }
            if ($GLOBALS["BO_CONF"]["CLIENT"]["company"] && $o->company)
                $cliNomClient .= " - " . $o->company . " ";

            if (isset($GLOBALS["BORNE_CONF"]["CLIENT_TYPE"]) && $GLOBALS["BORNE_CONF"]["CLIENT_TYPE"]) {
                $clientType = ($o->client == 1) ? "Client" : "Prospect";
                $cliNomClient .= ($agence->type_agence == 1) ? (" (" . $clientType . ")") : "";
                if ($o->client == 0)
                    $cliClass = strtolower($clientType);
            }

            $heure_serveur = date('H\hi');
            $da = ((substr($o->date_arrivee, 0, 2) * 3600) + (substr($o->date_arrivee, 3, 2) * 60));
            $ds = ((substr($heure_serveur, 0, 2) * 3600) + (substr($heure_serveur, 3, 2) * 60));
            $diff = ($ds - $da);
            $attente = "";
            $attente = round($diff / 60);
            if ($attente < 1) {
                $attente = "";
            } else {
                if ($attente > 59) {
                    $h = floor($attente / 60);
                    $m = ($attente % 60);
                    if ($m < 10)
                        $m = "0" . $m;
                    $attente = "Attente : " . $h . "h" . $m . "m ";
                } else {
                    $attente = "Attente : " . $attente . "m ";
                }
            }
            $MAXWAITTIME = $GLOBALS["PILE_CONF"]["MAXDURATIONWAIT"] ? $GLOBALS["PILE_CONF"]["MAXDURATIONWAIT"] : 600;
            $pct = ($diff / $MAXWAITTIME) * 280;  // 600 pour 10 minutes
            if ($pct > 280)
                $pct = 280;

            $pctId = "clt" . $o->id_client;

            // AGENCE DOUBLES
            if ($GLOBALS["BO_CONF"]["DOUBLEAGENCE"] && $o->id_borne > 0)
                $cliNomClient .= "&nbsp;[" . $o->id_borne . "]";
            $column .= "<table id='CWT" . $o->id_client . "' align='center' cellspacing='0' cellspacing='0' class='" . $cliClass . "'>
					<tr>
						<td width='50%' class='" . $cliClass . "top'>Clt " . ($i + 1) . " - Arriv&#233;e : " . $o->date_arrivee . "</td>
						<td class='" . $cliClass . "topright' width='50%' align='right'>" . $attente . "</td>
					</tr>
					<tr>
						<td style=\"max-height:6px;overflow:hidden;height:6px !important;\" colspan='2'>";
            if ($pct == 280) {
                $column .= "<img src='./images/pile_barre2.gif' width='100%'/>";
            } else {
                $column .= "<div id='indicator" . ($i + 1) . "' style=\"display:block;width:" . $pct . "px !important;background-color:#b7b7b7;margin:0;border:1px solid #b7b7b7;\"></div>";
            }
            $column .= "</td>
					</tr>
					<tr class='sep'>
						<td colspan='2' align='center' class='" . $cliClass . "bot2'>" . $cliNomClient . "</td>
					</tr>
					<tr class='sep'>
						<td colspan='2' align='center' class='" . $cliClass . "bot'>" . $cliType . "</td>
					</tr>
					<tr>
						<td colspan='2' class='tdBt' align='center'>";
            $column .= "<a href='#' onclick='update(" . json_encode(array("action" => "take", "id_client" => $o->id_client, "id_agence" => $agence->id_agence, "data" => json_encode($o, JSON_HEX_QUOT | JSON_HEX_APOS))) . ");' class='" . $btClass . "'>Prendre en charge</a>";
            $column .= "<br/></td>
					</tr>
				</table>";
            $i++;
        }
        $column .= '</div></div></td>';

        $columns .= $column;
        $column = "";
        $comp++;
    }
    return $columns;
}

function getEntiteIndiceByID($entites, $entite) {
    if ($GLOBALS["BO_CONF"]["ENTITELINKBYID"]) {
        for ($i = 0; $i < count($entites); $i++) {
            if ($entites[$i]->id_entite == $entite) {
                return $i;
            }
        }
    } else {
        return $entite - 1;
    }
}

function pileContenuAFA($agence, $entites, $motifs, $conseiller, $data, $stats){
    $html = $tablePhones = $tableMsgs  = "";
    if($conseiller->id_conseiller){
        $afa_motifs = (isset($GLOBALS["BO_CONF"]["AFA_MOTIFS"]) && $GLOBALS["BO_CONF"]["AFA_MOTIFS"]) ? true : false;
        $motifCol = $afa_motifs ? "<th>Motif</th>" : "";
        $pending = array();
        foreach($data["en_attente"] as $action => $clients){
            $agenceCol = $conseiller->user_cc ? "<th>Agence</th>" : "";
            $prenomCol = $GLOBALS["BO_CONF"]["CLIENT"]["prenom"] ? "<th>Prénom</th>" : "";
            $creneauCol = $GLOBALS["BORNE_CONF"]["CUSTOM_RECALL"] ? "<th>Créneau</th>" : "";
            if($action == 2 || $action == 4){ // Phone
              if($clients){
                foreach($clients as $client){
                    $creneauTime = $client->creneau ? new DateTime($client->creneau) : false;
                    $arriveeTime = $client->date_arrivee ? new DateTime($client->date_arrivee) : false;
                    $hour = 0;
                    if($creneauTime){
                        $hour = $creneauTime->format('H'); $hour++;
                    }
                    $now = new DateTime();
                    if($action == 4 && $creneauTime){
                        if($creneauTime >= $now){
                            $pending[] = $client;
                            continue;
                        }else{
                            $q = "UPDATE ca_pile_cc SET id_action = 2 WHERE id_client_cc = ".$client->id_client_cc;
                            $r = excuteQuery($q);
                        }
                    }
                    $agenceColRow = $conseiller->user_cc ? ("<td class='left'>".$client->nom_agence."</td>") : "";
                    $prenomColRow = $prenomCol ? ("<td class='left'>".$client->prenom."</td>") : "";
                    $tablePhones .= "<tr id='afa-row-".$client->id_client_cc."'>".$agenceColRow."
                        <td class='left'>".$client->nom."</td>
                        ".$prenomColRow."
                        <td>".$arriveeTime->format('d-m-Y H:i:s')."</td>
                        <td>".sec2hms($client->waiting_time)."</td>
                        <td>".$client->phone."</td>";
                    $tablePhones .= $afa_motifs ? "<td>".$client->motif."</td>" : "";
                    $tablePhones .= $creneauTime ? "<td>".$creneauTime->format('d-m-Y H\hi')." - ".$hour."h00</td>" : "";
                    $tablePhones .= "
                        <td><input class='cc_pec_check' data-cid='".$client->id_client_cc."' type='checkbox'".(($client->pec == "1") ? "checked" : "").(($client->taken == "1") ? " disabled" : "")."></td>
                        <td><input class='cc_take_check' data-cid='".$client->id_client_cc."' type='checkbox'".(($client->taken == "1") ? "checked" : ""). (($client->pec == "0") ? "disabled" : "")."></td>
                    </tr>";
                }
              }
            }
            else if($action == 3){ // Message
                $tableMsgs .= "<table class='afa_table'><thead>".$agenceCol."<th>Nom</th>".$prenomCol."<th>Date d'arrivée</th><th>Durée d'attente</th><th>Message</th><th>Pris en charge</th><th>Traité</th></thead>";
                foreach($clients as $client){
                    $agenceColRow = $conseiller->user_cc ? ("<td>".$client->nom_agence."</td>") : "";
                    $prenomColRow = $prenomCol ? ("<td class='left'>".$client->prenom."</td>") : "";
                    $arriveeTime = $client->date_arrivee ? new DateTime($client->date_arrivee) : false;
                    $tableMsgs .= "<tr id='afa-row-".$client->id_client_cc."'>".$agenceColRow."
                        <td class='left'>".$client->nom."</td>
                        ".$prenomColRow."
                        <td>".$arriveeTime->format('d-m-Y H:i:s')."</td>
                        <td>".sec2hms($client->waiting_time)."</td>
                        <td>".$client->message."</td>
                        <td><input class='cc_pec_check' data-cid='".$client->id_client_cc."' type='checkbox'".(($client->pec == "1") ? "checked " : "")."></td>
                        <td><input class='cc_take_check' data-cid='".$client->id_client_cc."' type='checkbox'".(($client->taken == "1") ? "checked disabled" : "")."></td>
                    </tr>";
                }
                $tableMsgs .= "</table>";
            }
        }
        $tablePhones = $tablePhones ? "<table class='afa_table'><thead>".$agenceCol."<th>Nom</th>".$prenomCol."<th>Date d'arrivée</th><th>Durée d'attente</th><th>Numéro de téléphone</th>".$motifCol.$creneauCol."<th title='Pris en charge'>Pris en charge</th><th>Traité</th></thead>".$tablePhones."</table>" : '';
                
        $html .= $tablePhones;
        $html .= $tableMsgs;
        
        if(!empty($GLOBALS["BORNE_CONF"]["CUSTOM_RECALL"])){
            if(count($pending)){
                
                $prenomCol = $GLOBALS["BO_CONF"]["CLIENT"]["prenom"] ? "<th>Prénom</th>" : "";
                $html .= "<table class='afa_table future'><thead>".$agenceCol."<th>Nom</th>".$prenomCol."<th>Date d'arrivée</th><th>Durée d'attente</th><th>Numéro de Téléphone</th>".$motifCol."<th>Créneau</th></thead>";
                foreach($pending as $client){
                    $time = strtotime($client->creneau);
                    $hour = date('H',$time);
                    $min = date('i',$time);
                    $arriveeTime = $client->date_arrivee ? new DateTime($client->date_arrivee) : false;
                    $creneau = date('H\hi',$time) . ' - ' . ($hour+1).'h'.$min;
                    $agenceCol = $conseiller->user_cc ? ("<td>".$client->nom_agence."</td>") : "";
                    $prenomCol = $prenomCol ? ("<td class='left'>".$client->prenom."</td>") : "";
                    $html .= "<tr id='afa-row-".$client->id_client_cc."'>".$agenceCol."
                        <td class='left'>".$client->nom."</td>
                        ".$prenomCol."
                        <td>".$arriveeTime->format('d-m-Y H:i:s')."</td>
                        <td>".sec2hms($client->waiting_time)."</td>
                        <td>".$client->phone."</td>";
                    $html .= $afa_motifs ? "<td>".$client->motif."</td>" : "";
                    $html .= "<td>".date('d-m-Y', $time). ' ' . $creneau ."</td>";
                    $html .= "</tr>";
                }
                $html .= "</table>";
            }
        }
    }
    return $html;
}

function pileContenu($agence, $entites, $motifs, $conseiller, $data, $stats) {
    $hidden = "";
    $entityColors = getEntityColors($entites);
    $quarter = (count($data["en_attente"]) == 2) ? ' quarter' : '';

        $matPath = ($conseiller && !($conseiller instanceof fakeConseiller)) ? '&MAT='.$_SESSION['matricule'] : "";
    
    if ($GLOBALS["PILE_CONF"]["AFFTABS"] == true) {
        $hidden = ' style="display:none;';
        $html .= '<table class="pileContentTable" align="center">
                        <tr>';
                            
        $html .= getAttenteColumns($agence, $data["en_attente"], $entites, $motifs);
        $html .= '<td class="pile-column" id="encours-column" '.$hidden.'>
                                    <div id="encours">';

        $html .= "<div id='colonne2'>Clients pris en charge <span id='nbTaken' class='nbTaken'>(".count($data['pris_en_charge']).")</span></div><div id='wrapper2'>";
    }else{
        $pec_header = "<div id='colonne2'>Clients pris en charge <span id='nbTaken' class='nbTaken'>(" . count($data['pris_en_charge']) . ")</span></div>";
        $stat_header = $GLOBALS["PILE_CONF"]["AFFSTATS"] ? "<div id='colonne3'>Statistiques</div>" : "";
        $attente_header = "<div id='colonne1' valign='top'><span id='nbWaiting' class='nbWaiting title'>Clients en attente " . (count($data["en_attente"]) == 1 ? "(" . count($data["en_attente"][0]) . ")" : "") . "</div>";
        $html = "";
        
        $noStats = $GLOBALS["PILE_CONF"]["AFFSTATS"] ? "" : "no-stats";
        $html .= '<table class="pileContentTable' . $quarter . ' '.$noStats.'" align="center">';
        $html .= '<thead><tr><th colspan="' . count($data["en_attente"]) . '">' . $attente_header . '</th><th>' . $pec_header . '</th><th>' . $stat_header . '</th></tr></thead>';
        $html .= '<tr>';
        $html .= getAttenteColumns($agence, $data["en_attente"], $entites, $motifs);
        $html .= '<td class="pile-column" id="encours-column" ' . $hidden . '><div id="encours">';
        $html .= "<div id='wrapper2'>";
    }

    

    $i = 0;
    foreach ($data['pris_en_charge'] as $o) {
        $heure_serveur = date('H\hi');
        $da = ((substr($o->date_arrivee, 0, 2) * 3600) + (substr($o->date_arrivee, 3, 2) * 60));
        $ds = ((substr($o->date_priseencharge, 0, 2) * 3600) + (substr($o->date_priseencharge, 3, 2) * 60));
        $diff = ($ds - $da);
        $attente = "";
        $attente = round($diff / 60);
        if ($attente < 1) {
            $attente = "";
        } else {
            if ($attente > 59) {
                $h = floor($attente / 60);
                $m = ($attente % 60);
                if ($m < 10)
                    $m = "0" . $m;
                $attente = "Attente : " . $h . "h" . $m . "m ";
            } else {
                $attente = "Attente : " . $attente . "m ";
            }
        }

        $cliNomClient = "";
        $cliType = "SANS RDV";
        $classAppend = "encours1";
        if ($i % 2 != 0)
            $classAppend = "encours2";
        if ($o->rdv == 1) {
            $cliType = "";
            $indice = (count($entites) > 1) ? getEntiteIndiceByID($entites, $o->entite) : 0;
            $cliClass = $entityColors[$indice] . "G " . $classAppend;

            if ($GLOBALS["BO_CONF"]["GUICHETS"]) {
                $cliType .= "Ticket : " . $o->ticket . "<br/>";
            }
            if ($o->id_conseiller == 0) {
                if ($GLOBALS["BO_CONF"]["AGENCE"]["MULTIPLE_TYPES"] && $agence->type_agence == 2) { // Type Borne RH
                    $cliType .= "RDV | Votre interlocuteur n'est pas présent sur la borne";
                } else {
                    $cliType .= "RDV | Conseiller inconnu";
                }
            } else {
                $cliType .= "RDV | ";
                if ($GLOBALS["BO_CONF"]["CONSEILLER"]["prenom"])
                    $cliType .= $o->conseillerPrenom . " ";
                $cliType .= $o->conseillerNom;
            }
        } else if ($o->rdv == 0) {
            if ($GLOBALS["BO_CONF"]["GUICHETS"]) {
                $cliType = "Ticket : " . $o->ticket . "<br/>SANS RDV";
            }
            $cliClass = "srdvG " . $classAppend;
            $m = $o->objetVenue ? $o->objetVenue : $o->objetVenuePile;
            $dm = $GLOBALS["BO_CONF"]["DYNAMIC_MOTIFS"] && $agence->is_motif ? true : false;
            if (($GLOBALS["BO_CONF"]["MOTIFS"] || $dm) && $m != ""){
                if (!isset($GLOBALS["PILE_CONF"]["PANEL"]["MOTIF_TITLE"]) || !$GLOBALS["PILE_CONF"]["PANEL"]["MOTIF_TITLE"]) {
                    $cliType .= " : " . $m;
                } else {
                    $cliType .= " : ";
                    $cliMotifs = explode(" ", $m);
                    foreach ($cliMotifs as $key => $value) {
                        $climotif = getMotifByCode($value, $motifs);
                        if (!$climotif) {
                            $brReplace = str_replace('<br/>',', ',$value);
                            $brReplace = str_replace('<br>',', ',$brReplace);
                            $cliType .= strip_tags($brReplace) . " ";
                        } else {
                            $brReplace = str_replace('<br/>',', ',$climotif->titre);
                            $brReplace = str_replace('<br>',', ',$brReplace);
                            $cliType .= strip_tags($brReplace) . " ";
                        }
                    }
                }
                $motif = getMotifByTitle($o->objetVenuePile, $motifs);
                if ($GLOBALS["BO_CONF"]["MOTIFSCOLORS"]) {
                    if ($motif->id_motif) {
                        $cliClass = "motif" . $motif->id_motif . "G " . $classAppend;
                    } else {
                        $cliClass = "srdvG " . $classAppend;
                    }
                }
            }
            if ($o->is_afa && $o->rdv_type == '1' && !$dm) {
                $actions = load_actions();
                $action = $actions[$o->rdv_type];
                $cliType .= " | ".$action->titre;
            }
        } else if ($o->rdv == 5) {
            $cliClass = "shipG " . $classAppend;
            $cliType = "LIVRAISON";
        } else {
            $cliClass = "meetingG " . $classAppend;
            $cliType = "Salle de réunion";
        }
        if($o->rdv != 5){
            $cliNomClient = str_replace("_", " & ", $o->civ) . " ";
            if ($GLOBALS["BO_CONF"]["CLIENT"]["prenom"])
                $cliNomClient .= $o->prenom . " ";
            $cliNomClient .= $o->nom;
        }
        $PCT = "";


        if (isset($GLOBALS["BORNE_CONF"]["CLIENT_TYPE"]) && $GLOBALS["BORNE_CONF"]["CLIENT_TYPE"]) {
            $clientType = ($o->client == 1) ? "Client" : "Prospect";
            $cliNomClient .= ($agence->type_agence == 1) ? (" (" . $clientType . ")") : "";
            if ($o->client == 0)
                $cliClass = strtolower($clientType) . "G " . $classAppend;
        }
        $cnsActionInfos = "";
        $isMyst = ($o->rdv == 1 && $o->id_conseiller == 0) ? " mystFinishBtn" : "";
        if($o->id_action && ($GLOBALS["PILE_CONF"]["PANEL"]["RDV"]["CNS_ACTION"]["PEC"] || $o->rdv == 0 || ($o->rdv == 1 && $o->id_conseiller == 0))){
            $cnsActionInfos = "<tr><td colspan='2' align='center'>PEC : " . $o->prenom_conseiller_action . " " . $o->nom_conseiller_action . "</td></tr>";
        }
        $html .= "<table id='CTK" . $o->id_client . "' align='center' cellspacing='0' cellspacing='0' class='" . $cliClass . "'><tr><td colspan='2' class='" . $cliClass . "top' align='center'>HA : " . $o->date_arrivee . " - HP : " . $o->date_priseencharge . " - " . $attente . "</td></tr> <tr><td colspan='2' align='center' class='" . $cliClass . "bot2'>" . $cliNomClient . "</td></tr> <tr><td colspan='2' align='center' class='" . $cliClass . "bot'>" . $cliType . "</td></tr> ".$cnsActionInfos." <tr><td colspan='2' class='tdBt2' align='center'>";
        $html .= $GLOBALS["PILE_CONF"]["RECALL_CLIENT"] ? ("&nbsp;<a href='#' onclick='update(" . json_encode(array("action" => "recall", "id_agence" => $agence->id_agence, "id_client" => $o->id_client, "data" => json_encode($o, JSON_HEX_QUOT | JSON_HEX_APOS))) . ");' class='bt-recall' title='Rappeler'><i class='fa fa-bell'></i></a>") : '';
        $html .= "<a class='bt2".$isMyst."' href='#' onclick='update(" . json_encode(array("action" => "finish", "id_agence" => $agence->id_agence, "id_client" => $o->id_client, "data" => json_encode($o, JSON_HEX_QUOT | JSON_HEX_APOS))) . ");'>Terminer l'entretien</a>";
        $html .= $GLOBALS["PILE_CONF"]["CANCEL_CLIENT"] ? ("&nbsp;<a href='#' onclick='update(" . json_encode(array("action" => "cancel", "id_agence" => $agence->id_agence, "id_client" => $o->id_client, "data" => json_encode($o, JSON_HEX_QUOT | JSON_HEX_APOS))) . ");' class='bt-cancel' title= \"Annuler l'entretien\"><i class='fa fa-times'></i></a>") : '';
        $html .= "</td></tr></table>";
        $i++;
    }
    $html .= "</div>";
    $html .= '</div>
							</td>';

    if ($GLOBALS["PILE_CONF"]["AFFTAKEN"]) {
        $html .= '<td class="pile-column" id="stats-column" ' . $hidden . '>
					<div id="historique">';

						$q = "SELECT count(id_client) as nb FROM ca_clients WHERE id_agence=:id_agence AND date_cloture != '0000-00-00 00:00:00' AND `date_arrivee` > '".date('Y-m-d')." 00:00:00' ";
						$values = array(':id_agence' => intval($agence->id_agence));
                        $result = excuteQuery($q, $values);
                        $res = $result['stmt'];
						$nb = $res->fetch( PDO::FETCH_ASSOC )['nb'];
						$html .= "<div id='colonne3'>Clients traités <span id='nbTaken' class='nbTaken'>(".count($data['traites']).")</span></div><div id='wrapper3'>";

						$i = 0;
						foreach ($data['traites'] as $o){
							$heure_serveur = date('H\hi');
							$da = ((substr($o->date_arrivee,0,2) * 3600) + (substr($o->date_arrivee,3,2) * 60));
							$ds = ((substr($o->date_priseencharge,0,2) * 3600) + (substr($o->date_priseencharge,3,2) * 60));
							$diff = ($ds - $da);
							$attente = "";
							$attente = round($diff / 60);
							if ($attente < 1) {
								$attente = "";
							} else {
								if ($attente > 59) {
									$h = floor($attente/60);
									$m = ($attente % 60);
									if ($m < 10) $m = "0".$m;
									$attente = "Attente : ".$h."h".$m."m ";
								} else {
									$attente = "Attente : ".$attente."m ";
								}
							}

							$cliNomClient = "";
							$cliType = "SANS RDV";
							$cliClass = "termines1";
							if ($i % 2 != 0) $cliClass = "termines2";
							if ($o->rdv == 1) {
								$cliType ="RDV | ".$o->conseillerNom;
							}
							$cliNomClient = str_replace("_"," & ",$o->civ)." ".$o->nom;

							if($GLOBALS["BO_CONF"]["GUICHETS"]){
								$cliType .= "<br/>Ticket : ".$o->ticket;
							}

							$PCT = "";

							$html .= "<table id='CTK".$o->id_client."' align='center' cellspacing='0' cellspacing='0' class='".$cliClass."'><tr><td colspan='2' class='".$cliClass."top' align='center'>HA : ".$o->date_arrivee." - HP : ".$o->date_priseencharge." - ".$attente."</td></tr> <tr><td colspan='2' align='center' class='".$cliClass."bot2'>".$cliNomClient."</td></tr> <tr><td colspan='2' align='center' class='".$cliClass."bot'>".$cliType."</td></tr></table>";
							$i++;
						}
						$html .= '</div>
					</div>
				</td>';
    }
    if ($GLOBALS["PILE_CONF"]["AFFSTATS"]) {
		$stats_title = $GLOBALS["PILE_CONF"]["AFFTABS"]?'<div id="colonne3">Statistiques</div>':'';
        $html .= '<td class="pile-column" id="stats-column" ' . $hidden . '>
									<div id="stats">
                                        '.$stats_title.'
										<br/>
										<table style="font-size:14px;text-align:left;margin-left:10px;">
											<tr>
												<td class="agence-conseiller">';
        $html .= '<span class="nom-agence">' . $agence->nom_agence . '</span>';
        $html .= "<br/>";
        if ($conseiller->id_agent) {
            $noPhoto = '';
            if (strpos($conseiller->photo, 'incognito') == true || strpos($conseiller->photo, 'photo_homme') == true || strpos($conseiller->photo, 'photo_femme') == true || $conseiller->photo == "") {
                $noPhoto = 'noPhoto';
            }
        }
        $html .= '</td>
										</tr>
										<tr>
											<td>
												<b>Nombre de clients de la journée : ' . $stats->nb_pris_en_charge . '</b>
												<br/>
											</td>
										</tr>
										<tr valign="top">
											<td valign="top">
												<br/>
												<table class="stats-column">
													<tr>
														<th>
														</th>';
        if ($conseiller->id_agent) {
            $html .= '<th>Vous</th>';
        }
        $html .= '<th>Agence</th></tr>';

        function stats_line($agence, $conseiller, $title, $valueConseiller, $valueAgence, $motifs) {
            $html = '<tr>';
            $html .= '	<td>' . $title . ' :</td>';
            if ($conseiller->id_agent) {
                $html .= '	<td class="data">' . $valueConseiller . '</td>';
            }
            $html .= '	<td class="data">' . $valueAgence . '</td>';
            $html .= '</tr>';
            return $html;
        }

        $html .= '<tr> <td class="section">Rendez-vous :</td>';
        if ($conseiller->id_agent || (isset($conseiller->matricule) && $conseiller->matricule)) {
            $html .= '<td></td>';
        }
        $html .= '<td></td></tr>';
        $html .= stats_line($agence, $conseiller, "Nombre", $stats->nb_pris_en_charge_rdv_agent, $stats->nb_pris_en_charge_rdv, $motifs);
        $html .= stats_line($agence, $conseiller, "Temps d'attente", sec2hms($stats->da_rdv_agent), sec2hms($stats->da_rdv), $motifs);
        $html .= '<tr> <td> <br/> </td> <td> <br/> </td> </tr> ';

        if (!$GLOBALS["BO_CONF"]["AGENCE"]["MULTIPLE_TYPES"] || $agence->type_agence == 1 || $agence->type_agence == 3) {
            $html .= '<tr> <td class="section"> Sans Rendez-vous : </td>';
            if ($conseiller->id_agent || (isset($conseiller->matricule) && $conseiller->matricule)) {
                $html .= '<td></td>';
            }
            $html .= '<td></td></tr>';
            $html .= stats_line($agence, $conseiller, "Nombre", $stats->nb_pris_en_charge_srdv_agent, $stats->nb_pris_en_charge_srdv, $motifs);
            $html .= stats_line($agence, $conseiller, "Temps d'attente", sec2hms($stats->da_srdv_agent), sec2hms($stats->da_srdv), $motifs);
            if ($GLOBALS["PILE_CONF"]["STATS"]["showMotifs"]) {
                $html .= '<tr> <td> <br/> </td> <td> <br/> </td> </tr> <tr>';
                $html .= '<td class="section"> Motifs Sans Rendez-vous : </td>';
                for ($i = 0; $i < count($motifs); $i++) {
                    if ($motifs[$i]->current_agency == 1) {
                        $motifTitle = $GLOBALS["PILE_CONF"]["STATS"]["showMotifsCode"] ? $motifs[$i]->code : strip_tags($motifs[$i]->titre);
                        $html .= stats_line($agence, $conseiller, $motifTitle, $stats->{"nb_pris_en_charge_motif_" . $motifs[$i]->id_motif . "_agent"}, $stats->{"nb_pris_en_charge_motif_" . $motifs[$i]->id_motif}, $motifs);
                    }
                }
                // AFA action is motif
                $afa_motifs = (isset($GLOBALS["BO_CONF"]["AFA_MOTIFS"]) && $GLOBALS["BO_CONF"]["AFA_MOTIFS"]) ? true : false;
                $dynamic_motifs = (isset($GLOBALS["BO_CONF"]["DYNAMIC_MOTIFS"]) && $GLOBALS["BO_CONF"]["DYNAMIC_MOTIFS"]) ? true : false;
                if ($GLOBALS["BO_CONF"]["AFA"] && $agence->is_afa && !$afa_motifs && !$dynamic_motifs) {
                    $actions = load_actions();
                    foreach ($actions as $action) {
                        if ($action->is_motif == "1") {
                            $html .= stats_line($agence, $conseiller, $action->titre, $stats->{"nb_pris_en_charge_motif_action_" . $action->id_action . "_agent"}, $stats->{"nb_pris_en_charge_motif_action_" . $action->id_action}, $motifs);
                        };
                    }
                }
            }
        }
        $shipSats = false;
        if($GLOBALS["BO_CONF"]["AGENCE"]["SIEGE"] && $GLOBALS["BO_CONF"]["AGENCE"]["SIEGE"]["CHOICES"]){
            foreach ($GLOBALS["BO_CONF"]["AGENCE"]["SIEGE"]["CHOICES"] as $choice) {
                if($choice == 'shipping')
                    $shipSats = true;
            }
        }
        if($shipSats){
            $html .= '<tr><td class="section"><br /> Livraison : </td>';
            if ($conseiller->id_agent || (isset($conseiller->matricule) && $conseiller->matricule)) {
                $html .= '<td></td>';
            }
            $html .= '<td></td></tr>';
            $html .= stats_line($agence, $conseiller, "Nombre", $stats->nb_pris_en_charge_ship_agent, $stats->nb_pris_en_charge_ship, $motifs);
            $html .= stats_line($agence, $conseiller, "Temps d'attente", sec2hms($stats->da_ship_agent), sec2hms($stats->da_ship), $motifs);
        }

        $NOMPDF = $conseiller->id_agent ? ($agence->nom_agence . "-" . $conseiller->nom . "-" . $conseiller->prenom) : $agence->nom_agence;

        // Mélange de conversion HTML -> texte, supression de caractères spéciaux, (mauvaise) suppression des accents
        $replace = array('&lt;' => '', '&gt;' => '', '&#039;' => '', '&amp;' => '',
            '&quot;' => '', 'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'Ae',
            '&Auml;' => 'A', 'Å' => 'A', 'Ā' => 'A', 'Ą' => 'A', 'Ă' => 'A', 'Æ' => 'Ae',
            'Ç' => 'C', 'Ć' => 'C', 'Č' => 'C', 'Ĉ' => 'C', 'Ċ' => 'C', 'Ď' => 'D', 'Đ' => 'D',
            'Ð' => 'D', 'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'Ē' => 'E',
            'Ę' => 'E', 'Ě' => 'E', 'Ĕ' => 'E', 'Ė' => 'E', 'Ĝ' => 'G', 'Ğ' => 'G',
            'Ġ' => 'G', 'Ģ' => 'G', 'Ĥ' => 'H', 'Ħ' => 'H', 'Ì' => 'I', 'Í' => 'I',
            'Î' => 'I', 'Ï' => 'I', 'Ī' => 'I', 'Ĩ' => 'I', 'Ĭ' => 'I', 'Į' => 'I',
            'İ' => 'I', 'IJ' => 'IJ', 'Ĵ' => 'J', 'Ķ' => 'K', 'Ł' => 'K', 'Ľ' => 'K',
            'Ĺ' => 'K', 'Ļ' => 'K', 'Ŀ' => 'K', 'Ñ' => 'N', 'Ń' => 'N', 'Ň' => 'N',
            'Ņ' => 'N', 'Ŋ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O',
            'Ö' => 'Oe', '&Ouml;' => 'Oe', 'Ø' => 'O', 'Ō' => 'O', 'Ő' => 'O', 'Ŏ' => 'O',
            'Œ' => 'OE', 'Ŕ' => 'R', 'Ř' => 'R', 'Ŗ' => 'R', 'Ś' => 'S', 'Š' => 'S',
            'Ş' => 'S', 'Ŝ' => 'S', 'Ș' => 'S', 'Ť' => 'T', 'Ţ' => 'T', 'Ŧ' => 'T',
            'Ț' => 'T', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'Ue', 'Ū' => 'U',
            '&Uuml;' => 'Ue', 'Ů' => 'U', 'Ű' => 'U', 'Ŭ' => 'U', 'Ũ' => 'U', 'Ų' => 'U',
            'Ŵ' => 'W', 'Ý' => 'Y', 'Ŷ' => 'Y', 'Ÿ' => 'Y', 'Ź' => 'Z', 'Ž' => 'Z',
            'Ż' => 'Z', 'Þ' => 'T', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a',
            'ä' => 'ae', '&auml;' => 'ae', 'å' => 'a', 'ā' => 'a', 'ą' => 'a', 'ă' => 'a',
            'æ' => 'ae', 'ç' => 'c', 'ć' => 'c', 'č' => 'c', 'ĉ' => 'c', 'ċ' => 'c',
            'ď' => 'd', 'đ' => 'd', 'ð' => 'd', 'è' => 'e', 'é' => 'e', 'ê' => 'e',
            'ë' => 'e', 'ē' => 'e', 'ę' => 'e', 'ě' => 'e', 'ĕ' => 'e', 'ė' => 'e',
            'ƒ' => 'f', 'ĝ' => 'g', 'ğ' => 'g', 'ġ' => 'g', 'ģ' => 'g', 'ĥ' => 'h',
            'ħ' => 'h', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'ī' => 'i',
            'ĩ' => 'i', 'ĭ' => 'i', 'į' => 'i', 'ı' => 'i', 'ij' => 'ij', 'ĵ' => 'j',
            'ķ' => 'k', 'ĸ' => 'k', 'ł' => 'l', 'ľ' => 'l', 'ĺ' => 'l', 'ļ' => 'l',
            'ŀ' => 'l', 'ñ' => 'n', 'ń' => 'n', 'ň' => 'n', 'ņ' => 'n', 'ʼn' => 'n',
            'ŋ' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'oe',
            '&ouml;' => 'oe', 'ø' => 'o', 'ō' => 'o', 'ő' => 'o', 'ŏ' => 'o', 'œ' => 'oe',
            'ŕ' => 'r', 'ř' => 'r', 'ŗ' => 'r', 'š' => 's', 'ù' => 'u', 'ú' => 'u',
            'û' => 'u', 'ü' => 'ue', 'ū' => 'u', '&uuml;' => 'ue', 'ů' => 'u', 'ű' => 'u',
            'ŭ' => 'u', 'ũ' => 'u', 'ų' => 'u', 'ŵ' => 'w', 'ý' => 'y', 'ÿ' => 'y',
            'ŷ' => 'y', 'ž' => 'z', 'ż' => 'z', 'ź' => 'z', 'þ' => 't', 'ß' => 'ss',
            'ſ' => 'ss', 'ый' => 'iy', 'А' => 'A', 'Б' => 'B', 'В' => 'V', 'Г' => 'G',
            'Д' => 'D', 'Е' => 'E', 'Ё' => 'YO', 'Ж' => 'ZH', 'З' => 'Z', 'И' => 'I',
            'Й' => 'Y', 'К' => 'K', 'Л' => 'L', 'М' => 'M', 'Н' => 'N', 'О' => 'O',
            'П' => 'P', 'Р' => 'R', 'С' => 'S', 'Т' => 'T', 'У' => 'U', 'Ф' => 'F',
            'Х' => 'H', 'Ц' => 'C', 'Ч' => 'CH', 'Ш' => 'SH', 'Щ' => 'SCH', 'Ъ' => '',
            'Ы' => 'Y', 'Ь' => '', 'Э' => 'E', 'Ю' => 'YU', 'Я' => 'YA', 'а' => 'a',
            'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ё' => 'yo',
            'ж' => 'zh', 'з' => 'z', 'и' => 'i', 'й' => 'y', 'к' => 'k', 'л' => 'l',
            'м' => 'm', 'н' => 'n', 'о' => 'o', 'п' => 'p', 'р' => 'r', 'с' => 's',
            'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'c', 'ч' => 'ch',
            'ш' => 'sh', 'щ' => 'sch', 'ъ' => '', 'ы' => 'y', 'ь' => '', 'э' => 'e',
            'ю' => 'yu', 'я' => 'ya'
        );

        $params = array(
            "nom" => str_replace(' ', '_', strtoupper(str_replace(array_keys($replace), $replace, $NOMPDF))),
            "agence" => str_replace(' ', '_', $agence->nom_agence),
            "eds" => $agence->eds,
            "code_agence" => $agence->code_agence,
            "type_agence" => $agence->type_agence,
            "afa" => (isset($agence->is_afa) && $agence->is_afa) ? $agence->is_afa : 0,
            "is_motif" =>  ($GLOBALS["BO_CONF"]["DYNAMIC_MOTIFS"] && $agence->is_motif) ? 1 : 0,
            "coffre" => (isset($agence->coffre) && $agence->coffre) ? $agence->coffre : 0,
            "rdv_agent" => $stats->nb_rdv_agent,
            "rdv_agence" => $stats->nb_pris_en_charge_rdv,
            "srdv_agent" => $stats->nb_srdv_agent,
            "srdv_agence" => $stats->nb_pris_en_charge_srdv,
            "ship_agent" => $stats->nb_ship_agent,
            "ship_agence" => $stats->nb_pris_en_charge_ship,
            "da_agent" => str_replace(':', '-', sec2hms($stats->da_agent)),
            "da_agence" => str_replace(':', '-', sec2hms($stats->da)),
            "da_srdv_agence" => sec2hms($stats->da_srdv),
            "da_srdv_agent" => sec2hms($stats->da_srdv_agent),
            "da_rdv_agence" => sec2hms($stats->da_rdv),
            "da_rdv_agent" => sec2hms($stats->da_rdv_agent),
            "da_ship_agence" => sec2hms($stats->da_ship),
            "da_ship_agent" => sec2hms($stats->da_ship_agent),
            "nb_clt" => $stats->nb_pris_en_charge,
            "nfc" => $agence->nfc,
        );
        if ($GLOBALS["PILE_CONF"]["STATS"]["showMotifs"]) {
            $nbprestasclts = array();
            for ($i = 0; $i < count($motifs); $i++) {
                if ($motifs[$i]->current_agency == 1) {
                    $nbprestasclts["NBCLISRDV-" . $motifs[$i]->id_motif] = array("code" => $motifs[$i]->code, "titre" => strip_tags(str_replace('<br/>',', ',$motifs[$i]->titre)), "nb_agence" => $stats->{"nb_pris_en_charge_motif_" . $motifs[$i]->id_motif}, "nb_agent" => $stats->{"nb_pris_en_charge_motif_" . $motifs[$i]->id_motif . "_agent"});
                }
            }
            $afa_motifs = (isset($GLOBALS["BO_CONF"]["AFA_MOTIFS"]) && $GLOBALS["BO_CONF"]["AFA_MOTIFS"]) ? true : false;
            $dynamic_motifs = isset($GLOBALS["BO_CONF"]["DYNAMIC_MOTIFS"]) && $GLOBALS["BO_CONF"]["DYNAMIC_MOTIFS"] ? true : false;
            if ($GLOBALS["BO_CONF"]["AFA"] && $agence->is_afa && !$afa_motifs && !($dynamic_motifs && $agence->is_motif)) {
                $actions = load_actions();
                foreach ($actions as $action) {
                    if ($action->is_motif) {
                        $nbprestasclts["NBCLISRDV-" . $action->id_action . "-ACTION"] = array("code" => "", "titre" => $action->titre, "nb_agence" => $stats->{"nb_pris_en_charge_motif_action_" . $action->id_action}, "nb_agent" => $stats->{"nb_pris_en_charge_motif_action_" . $action->id_action . "_agent"});
                    }
                }
            }
            $nbprestasclts = array("MOTIFS" => json_encode($nbprestasclts));
            $params = array_merge($params, $nbprestasclts);
        }
        if ($conseiller->id_agent) {
            $params['nomcons'] = $conseiller->prenom . '_' . $conseiller->nom;
            $params['matricule'] = $conseiller->id_agent;
        }

        $link = "libs/tcpdf/examples/generatePDF.php?" . implode("&", array_map(function($key, $value) {
                            return "$key=" . urlencode($value);
                        }, array_keys($params), $params));
        $html .= '</table>
												<br/><br/>
												<div><center><a href="' . htmlspecialchars($link) . '" target="_blank" id="pdfButton"><img src="./images/pdf.jpg" width="150"/></a></center></div>';
        if (!$GLOBALS["PILE_CONF"]["WHOISONLINE"]) {
            if (isset($_SESSION['profiles']) && (in_array("DR", $_SESSION['profiles']) || in_array("DS", $_SESSION['profiles']) || in_array("DA", $_SESSION['profiles']) || in_array("PRO", $_SESSION['profiles']) || in_array("DAM", $_SESSION['profiles']))) {
                $html .= '<div style="text-align:center"><br/><br/><a href="../admin/dashboard.php" class="encours2top" style="padding:1em; margin:1em" target="_blank">>> Administration</a></div>';
            }
        }
        $html .= '</td>';
    }
    $html .= '
										</tr>
									</table>
								</div>
							</td>
						</tr>
					</table>';
    return $html;
}

function getAgentsList($agence, $conseiller) {
	$dla = date('Y-m-d');
    if ((basename($_SERVER['PHP_SELF']) == "pileAFA.php" && (!$conseiller->id_conseiller || $GLOBALS["PILE_CONF"]["MENU"]["CCM"]["ACCESS"])) || (isset($conseiller->user_cc) && $conseiller->user_cc)) {
        if (!$GLOBALS["PILE_CONF"]["WHOISONLINE_CCM"]) {
            return "";
        }
		$lastActiveOrder = ($GLOBALS["BO_CONF"]["MOBILITY"])?"IF(ca.last_active LIKE '".$dla."%',1,0), status DESC,":"";
        $q = 'SELECT id_cc, civ, nom, prenom, "0" "status", TIMESTAMPDIFF(SECOND,last_active,now()) last_active_sec , IF(civ = "Mme", "assets/img/femme.png", "assets/img/homme.png") photo
		FROM ca_users_cc c
		WHERE supp IS NULL AND is_active = "1" AND id_cc != '.intval($conseiller->id_conseiller).'
		ORDER BY '.$lastActiveOrder.', nom, prenom ASC';
	}
	else{
        $values = array(':supp' => 0);
		$prenomColumn = ($GLOBALS["BO_CONF"]["CONSEILLER"]["prenom"]) ? ", prenom" : "";
		$dlgColumn = ($GLOBALS["BO_CONF"]["CONSEILLER"]["dlg"]) ? ", dlg" : "";
		$profilsJoin = 'LEFT JOIN ca_conseiller_agence ca ON ca.id_conseiller = c.id_conseiller AND ca.id_agence = '.intval($agence->id_agence);
        $statusColumn = ($GLOBALS["BO_CONF"]["MOBILITY"])?', ca.status':'';
        if($GLOBALS["BO_CONF"]["CONSEILLER"]["multiple_profiles"]){
            $agenceFilter = '';
        }else{
            $agenceFilter = 'AND ca.id_agence=:id_agence1';
            $values[':id_agence1'] = intval($agence->id_agence);
        }
        $values[':inactif'] = 0;
		$temporaryColumn = ($GLOBALS["BO_CONF"]["MOBILITY"])?", ca.temporaire":"";
		$lastActiveColumn = ($GLOBALS["BO_CONF"]["MOBILITY"])?", ca.last_active":"";
		$lastActiveSecColumn = ($GLOBALS["BO_CONF"]["MOBILITY"])?", TIMESTAMPDIFF(SECOND,ca.last_active,now()) last_active_sec":"";
		//$lastActiveOrder = ($GLOBALS["BO_CONF"]["MOBILITY"])?"IF(TIMESTAMPDIFF(SECOND,ca.last_active,now())<15,1,0) DESC,":"";
		$lastActiveOrder = ($GLOBALS["BO_CONF"]["MOBILITY"])?"IF(ca.last_active LIKE '".$dla."%',1,0) DESC, status DESC,":"";
        $values[':id_agence2'] = intval($agence->id_agence);
        if($GLOBALS["BO_CONF"]["MOBILITY"]){
            $whereActivity = " ((c.id_agence=:id_agence2) OR (ca.id_agence=:id_agence3))";
            $values[':id_agence3'] = intval($agence->id_agence);
            
        }else{
            $whereActivity = 'c.id_agence=:id_agence2';
        }//($GLOBALS["BO_CONF"]["MOBILITY"])?" OR (TIMESTAMPDIFF(SECOND,ca.last_active,now())<=".$GLOBALS["PILE_CONF"]["KEEPALIVE"].")":"";
		//$orderLastActive = $lastActiveSecColumn ? "-last_active_sec DESC," : "";

		$q = 'SELECT c.id_conseiller, civ, nom'.$prenomColumn.$statusColumn.', c.receive_notifications, photo, inactif'.$temporaryColumn.$lastActiveColumn.$dlgColumn.$lastActiveSecColumn.', IF(ca.last_active LIKE "'.$dla.'%",1,0) active_today
		FROM ca_conseillers c
		' . $profilsJoin . '
		WHERE c.supp=:supp ' . $agenceFilter . '
		AND c.inactif = :inactif 
		AND '.$whereActivity.'
			AND c.id_conseiller != :id_conseiller
		ORDER BY '.$lastActiveOrder.'nom ASC';
	}
    $values[':id_conseiller'] = intval($conseiller->id_conseiller);
    $result = excuteQuery($q, $values);
    $res = $result['stmt'];
	$list = "";
	while($row = $res->fetchObject()){
    $connected_once = ($row->last_active_sec == null)?false:true;
	  $last_active =  !empty($row->last_active_sec)?$row->last_active_sec:0;
		//$active = $connected_once && isset($last_active) && $last_active <= 15; // Connecté au moins une fois et sa durée d'activité est inférieure au temps du reloading
		$active = $row->active_today == 1 ? true : false; // Connecté au moins une fois et sa durée d'activité est inférieure au temps du reloading		
		$statusColor = $active ? ' online' : ' offline';
		$isDA = (isset($_SESSION['profiles']) && (in_array("DA",$_SESSION['profiles']) || in_array("DAM",$_SESSION['profiles'])|| in_array("DS",$_SESSION['profiles']) || in_array("DR",$_SESSION['profiles'])))?true:false;

		if(!($row->temporaire && !$active)){ // do not show temporary agents that are not active
			if ($row->status == -1){ // Selon la connexion
	      $showBorneStatus = $active; //$connected_once && isset($last_active) && $last_active <= $_GLOBALS["PILE_CONF"]["KEEPALIVE"];
	    }
	    else{
	      $showBorneStatus = ($row->status == 1) ? 0 : 1;
	    }
			$showBorne = ($showBorneStatus == 1) ? " shown" : " not-shown";
	    $shownTitle = ($showBorneStatus == 1) ? "Affiché sur la borne" : "Pas affiché sur la borne";
			$onlineTitle = $active ? "connecté".(($row->civ == "Mme")?"e":"")." à la pile" : "pas connecté".(($row->civ == "Mme")?"e":"")." à la pile";
			$updAction = "";//$isDA?' onclick = updateAgent("'.$row->id_conseiller.'")':'';
            $src_img = '/'.$row->photo;
			$list .= '<div class="cnsItem'.$statusColor.'" title="'.$row->prenom.' '.$row->nom.' '.$onlineTitle.'"'.$updAction.'><img src="'.$src_img.'"/><span title="'.$shownTitle.'" class="borne-status-indicator'.$showBorne.'"></span></div>';
		}
	}
	return $list;
}

function getAgentBoxInfos($agence, $conseiller, $reinforcement, $SERVER) {
    $data = "";
    $disableReinforcement = ''; //(($reinforcement["status"] == 0) && !$conseiller->reinforcement)?"disabled":"";
    $src_img = $conseiller->photo;
    if ($GLOBALS["PILE_CONF"]["WHOISONLINE"]) {
        if (isset($_SESSION['matricule']) && $conseiller && !($conseiller instanceof fakeConseiller)) {
            if (isset($conseiller->photo)) {
                $showBorneStatus = ($conseiller->mobility_status == 1) ? 0 : 1;
                $showBorne = ($showBorneStatus == 1) ? " shown" : " not-shown";
                $shownTitle = ($showBorneStatus == 1) ? "Affiché sur la borne" : "Pas affiché sur la borne";
                $data .= '<img style="background-color:' . $GLOBALS["BORNE_CONF"]["COLORS"]["PRIMARYCOLOR"] . '" src="/' . $src_img . '" height="45" width="auto"><div title="' . $shownTitle . '" class="borne-status-indicator' . $showBorne . '"></div>';
            }
            $data .= "<span>" . $conseiller->civ . " " . $conseiller->prenom . " " . $conseiller->nom . "</span>";
        }
    } else {
        if (isset($_SESSION['matricule']) && $conseiller && !($conseiller instanceof fakeConseiller)) {
            if (isset($conseiller->photo)) {
                $data .= '<img style="background-color:' . $GLOBALS["BORNE_CONF"]["COLORS"]["PRIMARYCOLOR"] . '" src="/' . $src_img . '" height="45" width="auto">';
            }
            $data .= '<span>' . $conseiller->civ . " " . $conseiller->prenom . " " . $conseiller->nom . '
			<span style="margin-left:130px;"><a href="./close.php?IDA=' . $agence->code_agence . '">Déconnexion</a></span>';
            if ($agence->type_agence !== '2' || $GLOBALS["PILE_CONF"]["RECEIVE_NOTIFS_FOR_AGC"])
                $data .= '<br/><input type="checkbox" id="receive_notifications" ' . ($conseiller->receive_notifications ? "checked" : "") . '/> <label for="receive_notifications" class="notif_label">' . (isset($GLOBALS["PILE_CONF"]["LABEL_NOTIFS"]) ? $GLOBALS["PILE_CONF"]["LABEL_NOTIFS"] : 'Recevoir les notifications des SRDV et "conseiller inconnu"') . '</label>';

            if ($reinforcement && $reinforcement["status"] != 0) {
                $data .= '<br/><input type="checkbox" id="reinforcement" ' . ($conseiller->reinforcement ? "checked" : "") . " data-id='" . (($reinforcement["status"] == 0) ? $reinforcement["id"] : '') . "' " . $disableReinforcement . '/> <label for="reinforcement" class="notif_label">' . (isset($GLOBALS["PILE_CONF"]["LABEL_REINFORCEMENT"]) ? $GLOBALS["PILE_CONF"]["LABEL_REINFORCEMENT"] : 'DEMANDE DE RENFORT') . '</label></span>';
            }
            $data .= '</span>';
            if ($GLOBALS["NOTIF_CONF"]["VIEWPOPUPBUTTON"] == "ALL" || ($GLOBALS["NOTIF_CONF"]["VIEWPOPUPBUTTON"] == "DA" && isset($_SESSION['profiles']) && in_array("DA", $_SESSION['profiles']))) {
                $data .= '<br/><span class="manage-notifications" id="manage-notifications" onclick="manageNotificationsPopup()">Notifications conseillers</span>';
            }
            if (isset($_SESSION['profiles']) && (in_array("PRO", $_SESSION['profiles']) || in_array("DAM", $_SESSION['profiles']))) {
                $data .= '<br/><span class="early-connection" id="early-connection" onclick="earlyConnectionPopup()">Connexion par anticipation</span>';
            }
        } else {
            $data .= '
			<form method="GET" style="line-height:22px;margin-top:1em;">
				<label style="font-weight:bold">Conseiller non reconnu !</label><br/>
				<label>Veuillez saisir votre matricule:</label>
				<input type="hidden" name="IDA" id="IDA" value="' . $agence->code_agence . '"/>
				<input type="text" name="MAT" placeholder="Entrer ici votre matricule" value="" /><input type="submit" value="Valider"/>
			</form>';
        }
    }
    return $data;
}

function getPileRattachementBtn($agentID,$aid,$newaid) {
    $btnSelfRattachement = "";
    if ($GLOBALS["PILE_CONF"]["SELFRATTACHEMENTPILE"]["enabled"]) {
            $texteSelfRattachement = (isset($GLOBALS["PILE_CONF"]["SELFRATTACHEMENTPILE"]["text"]) && $GLOBALS["PILE_CONF"]["SELFRATTACHEMENTPILE"]["text"] != "") ? $GLOBALS["PILE_CONF"]["SELFRATTACHEMENTPILE"]["text"] : "default text ! ";
            $sql = 'SELECT * FROM ca_conseiller_agence as ca
                    LEFT JOIN ca_agences as a ON ca.id_agence=a.id_agence
                    LEFT JOIN ca_entites as e ON ca.id_entite=e.id_entite
                    LEFT JOIN ca_conseillers c ON ca.id_conseiller=c.id_conseiller 
                    WHERE c.id_agence = :id_agence AND c.id_conseiller= :id';
            $values = array(':id_agence' => intval($aid),':id' => intval($agentID));
            $res = excuteQuery($sql, $values);
            $result = $res['stmt'];
            $o = $result->fetchObject();
            $NOMAGENCE = str_replace("'", ' ', $o->nom_agence);
            $NOMC = $o->nom . " " . $o->prenom;
            $NOMCONSEILLER = str_replace("'", ' ', $NOMC);
            $btnSelfRattachement = ' <button class="btn" type="button" onclick=\'selfRattachement("' . $o->id_agent . '","' . $o->id_conseiller . '","' . $NOMCONSEILLER . '","' . $newaid . '","' . $o->id_profile . '","' . $o->id_fonction . '", "' . $redirectOnClose . '");\'>' . $texteSelfRattachement . '</button>';
        }
        return $btnSelfRattachement;
}

    
function whoIsOnlineScroller($agence, $conseiller, $reinforcement, $SERVER) {
    $html = "";
    if ($GLOBALS["PILE_CONF"]["WHOISONLINE"]) {
        $agentsList = getAgentsList($agence, $conseiller);
        if ($agentsList && (!$reinforcement || $reinforcement['status'] == -1)) {
            $html .= '
					<div id="cnsListWrapper" class="cns-list">
						<i class="fa fa-angle-left" id="leftArrow" aria-hidden="true"></i>
						<div id="viewContainer">
							<div id="cnsList">' . $agentsList . '</div>
						</div>
						<i class="fa fa-angle-right" id="rightArrow" aria-hidden="true"></i>
					</div>';
        }
    }
    return $html;
}

function pileHeader($agence, $conseiller, $SERVER, $PROJECT_TITLE, $nocontent = false) {
    $cssVersion = $GLOBALS["APP_CONF"]["ASSETS_VERSION"] ? $GLOBALS["APP_CONF"]["ASSETS_VERSION"] : "1.2.1";
    ?>
    <!DOCTYPE html>
    <html>
        <head>
            <?php /* Vraiment utile? */ ?>
            <meta name=viewport content="width=device-width, initial-scale=1, maximum-scale=1">
            <meta name="apple-mobile-web-app-capable" content="yes">
            <meta name="mobile-web-app-capable" content="yes">
            <meta charset="UTF-8">
            <title><?php echo $PROJECT_TITLE; ?> - Pile</title>
            <style>
                :root {
                    --main-bg-color: white;
                    --rdv-color: <?php echo $GLOBALS["PILE_CONF"]["COLORS"]["RDV"] ? $GLOBALS["PILE_CONF"]["COLORS"]["RDV"] : '#eb292f'; ?>;
                    --srdv-color: <?php echo $GLOBALS["PILE_CONF"]["COLORS"]["SRDV"] ? $GLOBALS["PILE_CONF"]["COLORS"]["SRDV"] : '#009bc9'; ?>;
                    --meeting-color: <?php echo $GLOBALS["PILE_CONF"]["COLORS"]["MEETING"] ? $GLOBALS["PILE_CONF"]["COLORS"]["MEETING"] : '#0D80B1'; ?>;
                    --myst-color: <?php echo $GLOBALS["PILE_CONF"]["COLORS"]["MYST"] ? $GLOBALS["PILE_CONF"]["COLORS"]["MYST"] : '#666666'; ?>;
                }
                <?php
                if ($GLOBALS["BORNE_CONF"]["CLIENT_TYPE"]) {
                    $color = $GLOBALS["PILE_CONF"]["COLORS"]["PROSPECT"];
                    echo "
			.prospect 			{border:1px solid " . $color . ";width:280px;height:65px;margin-top:5px;background-color:#ffffff;color:" . $color . ";margin-left:auto;margin-right:auto;font-size:12px;}
			.prospecttop			{font-size:13px;padding:0px;padding-left:5px;background-color:" . $color . ";color:#ffffff;}
			.prospecttopright	{font-size:13px;padding:0px;padding-right:5px;background-color:" . $color . ";color:#ffffff;}
			.prospectbot			{font-size:11px;padding:0px;padding-left:5px;padding-right:5px;background-color:#ffffff;color:" . $color . ";}
			.prospectbot2		{padding:0px;background-color:#ffffff;color:" . $color . ";border-top:1px solid " . $color . ";font-weight:bold;}
			.prospectG a.bt2 {background: " . $color . ";color:#fff;}";
                }
                ?>
            </style>
            <link rel="stylesheet" type="text/css" href="<?php echo $SERVER; ?>admin/css/cans/jquery-ui-1.8.17.custom.css" />
            <link rel="stylesheet" href="css/font-awesome.min.css">
            <link rel="stylesheet" href="css/globalcolors.php?v=<?=$cssVersion?>" />
            <link rel="stylesheet" href="css/pilestats.css?v=<?=$cssVersion?>" />
            <link rel="stylesheet" href="css/pile.css?v=<?=$cssVersion?>" />
            <?php if ($GLOBALS["PILE_CONF"]["WHOISONLINE"]) { ?>
                <link rel="stylesheet" href="css/scroller.css?v=<?=$cssVersion?>" />
            <?php } ?>
            <?php if ($GLOBALS["BO_CONF"]["MOTIFSCOLORS"]) { ?>
                <link rel="stylesheet" href="css/motifs.php?v=<?=$cssVersion?>" />
            <?php } ?>
            <?php if ($GLOBALS["BO_CONF"]["COLORBYENTITY"]) { ?>
                <link rel="stylesheet" href="css/entites.php?AID=<?php echo $agence->id_agence; ?>" />
            <?php } ?>
            <?php if ($GLOBALS["PILE_CONF"]["AFFTABS"]) { ?>
                <link rel="stylesheet" href="css/tabs.css?v=<?=$cssVersion?>" />
            <?php } ?>
            <style>
                @media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
                    div#consInfos span, div.no-notifs#consInfos span {
                        margin-top: -15px;
                    }
                    div#consInfos img {
                        margin-top: 10px;
                    }
                    #consInfos .borne-status-indicator {
                        display: inline-flex;
                        position: relative;
                        left: 20px;
                        top: -17px;
                    }
                }
            </style>

            <script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
            <script type="text/javascript" src="js/progress.min.js"></script>
            <script type="text/javascript" src="js/jquery-ui-1.8.22.custom.min.js"></script>
            <script type="text/javascript" src="js/jquery.validate.min.js"></script>
            <script type="text/javascript" src="js/pile.js?v=<?=$cssVersion?>"></script>
            <?php if ($GLOBALS["PILE_CONF"]["WHOISONLINE"]) { ?>
                <script type="text/javascript" src="js/scroller.js?v=<?=$cssVersion?>"></script>
            <?php } ?>
            <?php if (isset($GLOBALS["PILE_CONF"]["USE_SOCKET"]) && $GLOBALS["PILE_CONF"]["USE_SOCKET"] === true) { ?>
                <script type="text/javascript" src="js/socket.io.min.js?v=<?=$cssVersion?>"></script>
                <script>
                    var socket = io.connect('//<?= $_SERVER['SERVER_NAME'] ?>:<?php echo NODEJS_PORT; ?>');

                    socket.on('connect', function () {
                        socket.id = "<?= $agence->id_agence; ?>";
                        console.log('connected');
                    });
                    socket.on('init', function () {
                        socket.emit('setTvInfos', getTvInfos());
                    });
                    socket.on('disconnect', function () {
                        console.log('disconnected');
                    });
                </script>
            <?php } ?>
        </head>

        <body>
            <?php /* A quoi ça sert? */ ?>
            <input type="hidden" id="IDA" value="<?php echo $agence->code_agence; ?>"/>
            <input type="hidden" id="matricule" value="<?php echo isset($_SESSION['matricule']) ? $_SESSION['matricule'] : ''; ?>"/>
            <input type="hidden" id="IDAGENCE" value="<?php echo $agence->id_agence; ?>"/>
            <input type="hidden" id="ENTITY" value="<?php echo $_REQUEST['id_entite']; ?>"/>
            <div id="pileHeader">
                <?php echo headerContenu($agence, $conseiller, $nocontent, $SERVER); ?>
            </div>
            <table width="100%">
                <tr>
                    <td>
                        <?php if (basename($_SERVER['PHP_SELF']) != "pileAFA.php") { ?>
                            <div class="titlePile">
                                Pile : 
                                <?php
                                echo $agence->nom_agence;
                                if ($GLOBALS['PILE_CONF']["MAIL_GUICHET_AUTHENTICATION"]) {
                                    echo ' - ' . $conseiller->counter_label;
                                }
                                ?>
                            </div>
                        <?php } ?>
                        <?php
                        if ($GLOBALS["PILE_CONF"]["AFFTABS"] == true) {
                            $hidden = ' style="display:none;';
                            echo '<ul id="tabs"><li id="tab-attente" class="active">Clients en attente</li><li id="tab-encours">Clients pris en charge</li></ul>';
                        }
                        ?>
                    </td>
                </tr>
                <tr>
                    <td class="pileContent">
                        <?php
                    }

                    function pileFooter($agence, $SERVER) {
                        date_default_timezone_set('Europe/France');
                        ?>
                    </td>
                </tr>
            </table>
            <div id="pileFooter" width="100%" valign="bottom">
                <div id="pileFooterNetisse">
                    <span id="datePile" class="date"><?php echo date("d/m/Y H:i"); ?></span>
                    <span class="copyright">Copyright ® </span>
                    <img class="logo" src="../admin/img/netisse.png" border="0"/>
                </div>
            </div>

        </body>
    </html>
    <?php
}
?>