<?php
require_once("../inc/confNetisse.php");

session_start();

class fakeConseiller {

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

}

function load_agence() {
    $q = "SELECT id_agence, code_agence, nom_agence, eds, meeting FROM ca_agences WHERE code_agence=:code_agence";
    $stmt = $GLOBALS["cnx"]->prepare($q) or wts_die(show_error());
    $values = [':code_agence' => $_REQUEST['IDA']];
    $result = excuteQuery($q, $values);
    $res = $result['stmt'];
    $agence = $res->fetchObject();
    $n = $res->rowCount();
    if ($n != 1) {
        // XXX message pas à jour?
        echo "<html><head><style type=\"text/css\">body {font-family:Arial,sans-serif;font-size:14px;color:#000;}</style></head><body><center><img src=\"images/ca_logo.jpg\" width=\"110\" height=\"90\" alt=\"Credit Agricole\" title=\"Credit Agricole\"/><br/><br/>Modification de la pile.<br/>Veuillez fermer cet onglet de votre navigateur et relancer la pile depuis le Portail Boreal.<br/>Merci.</html>";
        exit;
    }
    return $agence;
}

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

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 updateLastActivePile($conseiller, $id_agence) {
    $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) {
        $o = $res->fetchObject();
        if ($o->nb == 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) {
        $entite = $_REQUEST["id_entite"] ? ", id_entite=" . intval($_REQUEST["id_entite"]) : "";
        $q = "UPDATE ca_conseiller_agence SET last_active=now()" . $entite . " 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 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 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"])){
                    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);
                } 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 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 pile() {
    // agence
    $agence = load_agence();
    // Conseiller (si fourni)
    $conseiller = load_conseiller($agence);
    $motifs = array();
    // entites
    $entites = array();
    if ($GLOBALS["PILE_CONF"]["HASENTITIES"]) {
        $entites = load_entites($agence);
    }

    header("Cache-Control: no-cache");
    header("Pragma: no-cache");
    header("Expires: 0");
    $dt = date('Y-m-d H:i:s');
    if (in_array($_REQUEST['IDA'], $GLOBALS["changeTimezone"]))
                $dt = changeTimeMG($dt);
    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 "change_receive_notifications":
            $receive_notifications = $_REQUEST['receive_notifications'] ? 1 : 0;
                $q = "UPDATE ca_conseillers SET receive_notifications=:receive_notifications WHERE id_conseiller=:id_conseiller";
                $values = [':receive_notifications' => $receive_notifications,':id_conseiller' => $conseiller->id_conseiller];
                $result = excuteQuery($q, $values);
                // mise à jour du conseiller
                $conseiller = load_conseiller($agence);
                break;
        }
    }

    $data = getPileData($agence);

    if (isset($_REQUEST['ajax'])) {
        header("Content-Type: application/json; charset=UTF-8");
        echo json_encode(array(
            'contenu_pile' => pileContenu($agence, $conseiller, $data),
            'conseiller' => $conseiller,
            'en_attente' => $data['en_attente'],
            'notif_colors' => getNotifsColors($entites, $motifs),
        ));
    } else {
        header("Content-Type: text/html; charset=UTF-8");

        pileHeader($agence, $conseiller);
        echo pileContenu($agence, $conseiller, $data);
        $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();
        $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);
    }
}

function objetVenue($o) {
    $list = explode(",", $o->motif);
    return implode(" ", $list);
}

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

function getNotifsColors($entites, $motifs, $json = true) {
    $colors = array('#0D80B1');
    foreach ($colors as $key => $color) {
        $colors[$key] = str_replace("#", "", $color);
    }
    return $json ? json_encode($colors) : $colors;
}

function listeClients($agence, $type) {
    $liste = array();
    $additionalColumns = "";
    $additionalColumns .= ($GLOBALS["BO_CONF"]["CLIENT"]["prenom"]) ? ", cl.prenom" : "";
    $additionalColumns .= ($GLOBALS["BO_CONF"]["CONSEILLER"]["prenom"]) ? ", cs.prenom as conseillerPrenom" : "";
    $additionalColumns .= ($GLOBALS["BO_CONF"]["MOTIFS"]) ? ", group_concat(m.titre SEPARATOR ',') as motif" : "";
    $additionalColumns .= ($GLOBALS["BO_CONF"]["ENTITIES"]) ? ", cl.entite" : "";
    $additionalColumns .= ($GLOBALS["BO_CONF"]["DOUBLEAGENCE"]) ? ", cl.id_borne" : "";

    $groupByClPrenom = ($GLOBALS["BO_CONF"]["CLIENT"]["prenom"]) ? ", prenom" : "";
    $groupByConsPrenom = ($GLOBALS["BO_CONF"]["CONSEILLER"]["prenom"]) ? ", conseillerPrenom" : "";
    $groupByDoubleBorne = ($GLOBALS["BO_CONF"]["DOUBLEAGENCE"]) ? ", id_borne" : "";

    $leftJoins = ($GLOBALS["BO_CONF"]["MOTIFS"]) ? " 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" : "";

    if ($type == "en_attente") {
        $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 DATEDIFF(cl.date_arrivee,now())=0
			AND cl.date_priseencharge='0000-00-00 00:00:00'
			AND cl.id_agence=:id_agence
			AND rdv = 2
			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 = [':id_agence' => $agence->id_agence];
        $result = excuteQuery($q, $values);
        $res = $result['stmt'];
        $tmp = array();
        while ($o = $res->fetchObject()) {
            if ($GLOBALS["BO_CONF"]["MOTIFS"])
                $o->objetVenue = objetVenue($o);
            array_push($liste, $o);
        }
    }
    else {
        $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 DATEDIFF(cl.date_arrivee,now())=0
			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
			AND rdv = 2
			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 = [':id_agence' => $agence->id_agence];
        $result = excuteQuery($q, $values);
        $res = $result['stmt'];
        while ($o = $o = $res->fetchObject()) {
            if ($GLOBALS["BO_CONF"]["MOTIFS"])
                $o->objetVenue = objetVenue($o);
            array_push($liste, $o);
        }
    }
    return $liste;
}

$IDA = "";
$IDA = $_REQUEST["IDA"];
$MATRICULE = "0";
if (isset($_REQUEST["MAT"])) {
    $MATRICULE = $_REQUEST["MAT"];
}

function pileContenu($agence, $conseiller, $data) {
    $html = "";
    $html = '<table class="pileContentTable" align="center">
						<tr>';

    $html .= '<td class="pile-column attente"><div>';
    $html .= "<div id='colonne1' valign='top'><span id='nbWaiting' class='nbWaiting title-meeting'>";
    $html .= "	Clients en attente";

    $html .= " 	(" . count($data['en_attente']) . ")</span>";
    $html .= "</div>
		<div id='wrapper1'>";

    $i = 0;
    foreach ($data['en_attente'] as $o) {
        $cliType = "SANS RDV";
        $cliClass = "srdv";
        $btClass = "bt";
        $cliProgressBar = "orange";
        if ($o->rdv == 1) {
            $cliClass = 'grey';
            if ($o->id_conseiller == 0) {
                $cliType = "RDV | Conseiller inconnu";
            } else {
                $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"]["MOTIFS"] && $o->objetVenue != "")
                $cliType .= " : " . $o->objetVenue;
        } else {
            $cliClass = "meeting";
            $cliType = "Salle de réunion";
        }

        $cliNomClient = $o->civ . " ";
        if ($GLOBALS["BO_CONF"]["CLIENT"]["prenom"])
            $cliNomClient .= $o->prenom . " ";
        $cliNomClient .= $o->nom;

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

        $pct = ($diff / 600) * 280;  // 600 pour 10 minutes
        if ($pct > 280)
            $pct = 280;

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

        // AGENCE DOUBLES
        if ($o->id_borne > 0)
            $cliNomClient .= "&nbsp;[" . $o->id_borne . "]";


        $html .= "<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) {
            $html .= "<img src='./images/pile_barre2.gif'/>";
        } else {
            $html .= "<div id='indicator" . ($i + 1) . "' style=\"display:block;width:" . $pct . "px !important;background-color:#b7b7b7;margin:0;border:1px solid #b7b7b7;\"></div>";
        }
        $html .= "</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'><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><br/></td>
				</tr>
			</table>";
        $i++;
    }
    $html .= '</div></div></td>';
    $html .= '<td class="pile-column">
				<div id="encours">';
    $html .= "		<div id='colonne2'><span id='nbTaken' class='nbTaken'>Clients pris en charge (" . count($data['pris_en_charge']) . ")</span></div><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 = "RDV | ";
            if ($GLOBALS["BO_CONF"]["CONSEILLER"]["prenom"])
                $cliType .= $o->conseillerPrenom . " ";
            $cliType .= $o->conseillerNom;
        } else {
            if ($GLOBALS["BO_CONF"]["MOTIFS"] && $o->objetVenue != "")
                $cliType .= " : " . $o->objetVenue;
        }
        if ($o->rdv == 1) {
            $cliClass = "G " . $classAppend;
            if ($o->id_conseiller == 0) {
                $cliType = "RDV | Conseiller inconnu";
            } else {
                $cliType = "RDV | ";
                if ($GLOBALS["BO_CONF"]["CONSEILLER"]["prenom"])
                    $cliType .= $o->conseillerPrenom . " ";
                $cliType .= $o->conseillerNom;
            }
        } else if ($o->rdv == 0) {
            $cliClass = "mystG " . $classAppend;
            if ($GLOBALS["BO_CONF"]["MOTIFS"] && $o->objetVenue != "")
                $cliType .= " : " . $o->objetVenue;
        } else {
            $cliClass = "meetingG " . $classAppend;
            $cliType = "Salle de réunion";
        }

        $cliNomClient = $o->civ . " " . $o->prenom . " " . $o->nom;


        $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> <tr><td colspan='2' class='tdBt2' align='center'><a class='bt2' href='#' onclick='update(" . json_encode(array("action" => "finish", "id_client" => $o->id_client)) . ");'>Terminer l'entretien</a></td></tr></table>";
        $i++;
    }
    $html .= "</div>";
    $html .= '</div>
							</td>
										</tr>
									</table>
								</div>
							</td>
						</tr>		
					</table>';
    return $html;
}

function pileHeader($agence, $conseiller) {
    ?>	
    <!DOCTYPE html>
    <html>
        <head>
            <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>	
            <link rel="stylesheet" href="css/globalcolors.php?v=<?php echo $GLOBALS['version']; ?>" />
            <link rel="stylesheet" href="css/pilestats.css" />
            <link rel="stylesheet" href="css/pile.css?v=<?php echo $GLOBALS['version']; ?>" />
            <!-- <link rel="stylesheet" href="new.css" /> -->
            <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=<?php echo $GLOBALS['version']; ?>"></script>
            <?php if ($GLOBALS["PILE_CONF"]["WHOISONLINE"]) { ?>
                <script type="text/javascript" src="js/scroller.js?v=<?php echo $GLOBALS['version']; ?>"></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=<?php echo $GLOBALS['version']; ?>"></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>
        <?php $isOnline = (isset($_SESSION['matricule']) && $conseiller && !($conseiller instanceof fakeConseiller))?" online":""; ?>
        <body class="pileR<?php echo $isOnline; ?>">	
            <?php /* A quoi ça sert? */ ?>
            <input type="hidden" id="IDA" value="<?php echo $agence->code_agence; ?>"/>
            <div id="pileHeader">
                <div id="logo"><a href="../admin/dashboard.php"><img src="../admin/img/logo.png" border="0"/></a></div>
                <div id="timer"> </div>
                <?php if ($GLOBALS["PILE_CONF"]["AFFSTATS"] == false) { ?>
                    <div id="consInfos">
                        <?php if (isset($_SESSION['matricule']) && $conseiller && !($conseiller instanceof fakeConseiller)) { ?>
                            <?php if (isset($conseiller->photo)) { ?><img src="/<?php echo $conseiller->photo; ?>" height="45" width="auto"><?php } ?> 
                            <span class="consName"><?php echo $conseiller->civ." ".$conseiller->prenom." ".$conseiller->nom; ?>
                            <span><a href="./close.php?IDA=<?php echo $agence->code_agence;?>" class="logout">Déconnexion</a></span>
                            <?php
                        } else {
                            echo "<h3 style='color:#E30613;' class='noCns'>Conseiller non reconnu !</h3>";
                        }
                        ?>
                    </div>
                <?php } ?>
            </div>
            <table width="100%">
                <tr>
                    <td>
                        <div class="titlePile"><span class="title-meeting">Pile Invitation</span> : <?php echo $agence->nom_agence; ?></div>
                    </td>
                </tr>
                <tr>
                    <td class="pileContent">
                        <?php
                    }

                    function pileFooter($agence) {
                        ?>
                    </td>
                </tr>
            </table>

            <div id="pileFooter" width="100%" valign="bottom">
                <div id="pileFooterNetisse">
                    <span class="date"><?php echo $agence->nom_agence . " - " . date("d/m/Y H:i:s"); ?></span>
                    <img class="logo" src="../admin/img/netisse.png" border="0"/>
                </div>
            </div>
        </body>

    </html>
    <?php
}

pile();
?>