<?php
require("functions.php");

$ISADMIN = (isset($_SESSION['profil']) && ($_SESSION['profil'] == 100 || $_SESSION['profil'] == 70) && $_SESSION["user"] != "conseiller") ? true : false;
$SUB = "";
$MAT = "";
$NOM = "";
$DATA = "";
$FILTER = "";
if (isset($_REQUEST["sub"]))
$SUB = $_REQUEST["sub"];
if (isset($_REQUEST["mat"]))
$MAT = $_REQUEST["mat"];
if (isset($_REQUEST["nom"]))
$NOM = $_REQUEST["nom"];
//echo "<li>SUB=".$SUB." | MAT=".$MAT." | NOM=".$NOM."</li>";

$forPile = false;
if (strpos($_SERVER["REQUEST_URI"], '/pile/') !== false) {
    $forPile = true;
}

$showTempTable = ($GLOBALS["BO_CONF"]["TRANSFERT_TEMPORAIRE"] && $_SESSION["profil"] == 100 && $_SESSION["user"] == "admin") ? true : false;
if ($SUB != "") {
    $valuesBind = array(':supp1' => 0, ':supp2' => 0);

    if (($MAT != "") || ($NOM != "")) {
        if ($NOM != "") {
            $FILTER .= " AND (c.nom LIKE CONCAT('%',:nom1,'%') OR c.prenom LIKE CONCAT('%',:nom2,'%') OR CONCAT(c.nom,' ', c.prenom) LIKE CONCAT('%',:nom3,'%'))";
            $valuesBind[':nom1'] = $NOM;
            $valuesBind[':nom2'] = $NOM;
            $valuesBind[':nom3'] = $NOM;
        }
        if ($MAT != "") {
            $typesBind = "ii";
            $FILTER .= " AND c.id_agent=:id_agent";
            $valuesBind[':id_agent'] = $MAT;
        }

    }
    $TempFilter = "";
    if (!$showTempTable) {
        $TempFilter = " AND ca.temporaire = :temporaire";
        $valuesBind[':temporaire'] = 0;
    }

    $q = "SELECT    c.id_conseiller, e.libelle, ca.id_agence, ca.temporaire, ca.receive_notifications, ca.status, a.nom_agence, c.id_agent, c.nom, c.prenom, c.photo, c.inactif, c.fonction, created_from,DATE_FORMAT(c.date_creation, '%d/%m/%Y') as date_creation_conseiller, DATE_FORMAT(ca.date_creation, '%d/%m/%Y') as date_creation, DATE_FORMAT(c.date_modification, '%d/%m/%Y') as date_modification, IF(c.id_agence = ca.id_agence,1,0) agence_affectation, IF(TIMESTAMPDIFF(SECOND,ca.last_active,now())<=15,1,0) AS online, (SELECT id_profil FROM ca_conseiller_profils cp WHERE cp.id_conseiller = ca.id_conseiller ORDER BY cp.id_profil ASC LIMIT 1) as profil
                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.supp=:supp1 AND a.supp=:supp2" . $FILTER . "
                " . $TempFilter . "
                ORDER BY c.nom ASC";
// echo "<li>".$q;

    $stmt = excuteQuery($q, $valuesBind);
    if ($stmt['status']) {
        $DATA = "";
        $result = $stmt['stmt'];
        while ($o = $result->fetchObject()) {
            $datecrea = $o->date_creation;
            if ($datecrea == "00/00/0000") {
                $datemodif = $o->date_modification;
                if ($datemodif == "00/00/0000") {
                    $datecreacons = $o->date_creation_conseiller;
                    if ($datecreacons == "00/00/0000") {
                        $datecrea = ' - ';
                    } else {
                        $datecrea = $datecreacons;
                    }
                }
            }


            $NOMAGENCE = str_replace("'", ' ', $o->nom_agence);
            $NOMC = $o->nom . " " . $o->prenom;
            $ENTITE = $o->libelle;
            $NOMCONSEILLER = str_replace("'", ' ', $NOMC);
            $CONSLINK = ($o->agence_affectation && $ISADMIN) ? "<a target='_blank' href='".$SERVER."admin/cnsUpd.php?aid=" . $o->id_agence . "&cid=" . $o->id_conseiller . "'>" . $o->nom . " " . $o->prenom . "</a>" : $o->nom . " " . $o->prenom;
            $CONSMAT = ($o->agence_affectation && $ISADMIN) ? "<a target='_blank' href='".$SERVER."admin/cnsUpd.php?aid=" . $o->id_agence . "&cid=" . $o->id_conseiller . "'>" . $o->id_agent . "</a>" : $o->id_agent;
            $PROFIL = $o->profil ? $o->profil : null;
            //echo "<li>NOMC=".$NOMC." | NOMCONSEILLER=".$NOMCONSEILLER;
            // if ($TempFilter == "" && (($o->status == -1 && $o->agence_affectation == 0) || ($o->status == -1 && $o->agence_affectation))) {
            if($TempFilter == "" && $o->temporaire){
                $online = $o->online ? "green" : "red";
                if ($o->status == -1) {
                    $showBorne = $o->online;
                } else {
                    $showBorne = ($o->status == 1) ? 0 : 1;
                }
                $borneColor = ($showBorne == 1) ? "green" : "red";
                $TEMPS .= "<tr class='agent-row' data-agent='" . $o->id_conseiller . "'>
                  <td>" . $CONSLINK . "</td>
                  <td>" . $CONSMAT . "</td>
                  <td>" . $o->nom_agence . "</td>";
                $TEMPS .= ($GLOBALS["BO_CONF"]["ENTITIES"]) ? "<td> " . $ENTITE . " </td>" : "";
                $TEMPS .= "<td class='online-status-flag'><span class='square " . $online . "'></span></td>";
                $TEMPS .= ($GLOBALS["BO_CONF"]["MOBILITY"]) ? "<td class='manage-conseiller-status'><select name='pile_status' class='pile_status' data-agence='" . $o->id_agence . "' data-fonction='". $o->fonction ."' data-temporary='" . $o->temporaire . "' data-id='" . $o->id_conseiller . "'><option value='0' " . ($o->status == 0 ? "selected" : "") . ">Toujours affiché</option><option value='1' " . ($o->status == 1 ? "selected" : "") . ">Jamais affiché</option><option value='-1' " . ($o->status == -1 ? "selected" : "") . ">Affiché suivant connexion</option></select></td>" : "";
                $TEMPS .= ($GLOBALS["BO_CONF"]["MOBILITY"]) ? "<td class='borne-status-flag'><span class='square " . $borneColor . "'></span></td>" : "";
                $TEMPS .= "<td><input type='checkbox' class='manage-conseiller-notification' data-agence='" . $o->id_agence . "' data-rh='" . $o->agence_affectation . "' data-id='" . $o->id_conseiller . "' " . ($o->receive_notifications ? "checked" : "") . "></td></tr>";
            }
            // if(!($o->status == -1 && $o->agence_affectation == 0)){
            if (!$o->temporaire) {
                $o->created_from == 1 ? $has_star_icon = ' <span style="color: red;font-size: 12px;position: absolute;font-weight: bold;">*</span>': $has_star_icon = '';
                $DATA .= "<tr>
              <td>" . $CONSLINK . "</td>
              <td>" . $CONSMAT . "</td>
              <td>" . $o->nom_agence . "</td>";
                $DATA .= ($GLOBALS["BO_CONF"]["ENTITIES"]) ? "<td> " . $ENTITE . " </td>" : "";
                $DATA .= "<td>" . $o->date_creation_conseiller .$has_star_icon. " </td>";
                $DATA .= "<td>" . $datecrea . " </td>";
                $DATA .= "<td>";
                $DATA .= $o->agence_affectation ? "<a href='#' onclick='transfert(\"" . $o->id_agent . "\"," . $o->id_conseiller . ",\"" . $NOMCONSEILLER . "\"," . $o->id_agence . ",\"" . $NOMAGENCE . "\",\"" . $o->fonction . "\",\"" . $o->profil . "\")'><input type='button' style='cursor:pointer' value='->'/></a>" : "";
                $DATA .= "</td>";
                $DATA .= "<td>";
                $DATA .= $o->agence_affectation ? "<a href='#' onclick='ajout(\"" . $o->id_agent . "\"," . $o->id_conseiller . ",\"" . $NOMCONSEILLER . "\"," . $o->id_agence . ",\"" . $NOMAGENCE . "\",\"" . $o->fonction . "\",\"" . $o->profil . "\")'><input type='button' style='cursor:pointer' value='+'/></a>" : "";
                $DATA .= "</td>";
                $DATA .= "<td>";
                $DATA .= $o->agence_affectation ? "" : ($o->online ? "<font color='green'>En ligne</font>" : "<a href='#' onclick='suppression(\"" . $o->id_agent . "\"," . $o->id_conseiller . ",\"" . $NOMCONSEILLER . "\"," . $o->id_agence . ",\"" . $NOMAGENCE . "\")'><input type='button' style='cursor:pointer' value='-'/></a>");
                $DATA .= "</td>
                 </tr>";
            }
        }
    }
}
?>

<div id="panels">
    <form name="formCnsTrf" id="formCnsTrf" action="cnsTrf.php" method="post">
        <input type="hidden" name="sub" id="sub" value="1"/>
        <div>
            Matricule <input type="text" name="mat" id="mat" size="10" tabindex="1" value="<?php echo $MAT; ?>"/>
            |
            Nom / Prénom <input type="text" name="nom" id="nom" size="15" tabindex="2" value="<?php echo $NOM; ?>"/>
            <input type="submit" class="formNav" id="submit-btn-trf" value="Rechercher" tabindex="3"/>
        </div>
    </form>
</div>

<div id="panelContent">
    <h3>Rattachements</h3>
    <?php if ($GLOBALS["PILE_CONF"]["AGENT_FORM"]) { ?>
    <p style="color: red;">(<span style="font-weight: bold;">*</span>) Conseiller créé à partir de la pile</p>
    <?php } ?>
    <table cellpadding="0" cellspacing="0" border="0" class="display" id="AdminsDataTable" class="transferts-dataTable">
        <thead>
            <tr>
                <td>Nom</td>
                <td>Matricule</td>
                <td>Agence</td>
                <?php if ($GLOBALS["BO_CONF"]["ENTITIES"]) { ?><td>Entité</td><?php } ?>
                <td>Date de création</td>
                <td>Date de transfert</td>
                <td>Transférer</td>
                <td>Ajouter</td>
                <td>Supprimer</td>
            </tr>
        </thead>
        <tbody>
            <?php
            echo $DATA;
            ?>
        </tbody>
    </table>

    <?php if ($showTempTable) {
     ?>
        <h3>Rattachements Temporaires</h3>
        <table cellpadding="0" cellspacing="0" border="0" class="display" id="TempsDataTable" class="temps-dataTable">
            <thead>
                <tr>
                    <td>Nom</td>
                    <td>Matricule</td>
                    <td>Agence</td>
                    <?php if ($GLOBALS["BO_CONF"]["ENTITIES"]) { ?><td>Entité</td><?php } ?>
                    <td>Connecté Pile</td>
                    <td>Affichage</td>
                    <td>Affiché Borne</td>
                    <td>Notifs</td>
                </tr>
            </thead>
            <tbody>
                <?php
                echo $TEMPS;
                ?>
            </tbody>
        </table>
    <?php } ?>

    <script type="text/javascript">
        $(document).ready(function () {
            oTable = $('#AdminsDataTable').dataTable({
                "iDisplayLength": 10000,
                "bJQueryUI": true,
                "sPaginationType": "full_numbers",
                "sDom": '<"H"Tfr>t<"F"ip>',
                "oTableTools": {
                    "sSwfPath": "./swf/copy_csv_xls_pdf.swf",
                    "aButtons": [
                        {
                            "sExtends": "xls",
                            "sButtonText": "Excel"
                        },
                        {
                            "sExtends": "pdf",
                            "sButtonText": "PDF"
                        }
                    ]
                },
                "oLanguage": {
                    "sProcessing": "Traitement en cours...",
                    "sLengthMenu": "Afficher _MENU_ &eacute;l&eacute;ments",
                    "sZeroRecords": "Aucun &eacute;l&eacute;ment &agrave; afficher",
                    "sInfo": "Affichage : _START_ &agrave; _END_ sur _TOTAL_ &eacute;l&eacute;ments",
                    "sInfoEmpty": "Affichage de l'&eacute;lement 0 &agrave; 0 sur 0 &eacute;l&eacute;ments",
                    "sInfoFiltered": "(filtr&eacute; de _MAX_ &eacute;l&eacute;ments au total)",
                    "sInfoPostFix": "",
                    "sSearch": "Rechercher&nbsp;/&nbsp;Filtrer&nbsp;:",
                    "sLoadingRecords": "T&#233;l&#233;chargement...",
                    "sUrl": "",
                    "oPaginate": {
                        "sFirst": "Premier",
                        "sPrevious": "Pr&eacute;c&eacute;dent",
                        "sNext": "Suivant",
                        "sLast": "Dernier"
                    }
                }
            });
            if ($('#TempsDataTable').length) {
                oTable = $('#TempsDataTable').dataTable({
                    "iDisplayLength": 10000,
                    "bJQueryUI": true,
                    "sPaginationType": "full_numbers",
                    "sDom": '<"H"Tfr>t<"F"ip>',
                    "oTableTools": {
                        "sSwfPath": "./swf/copy_csv_xls_pdf.swf",
                        "aButtons": [
                            {
                                "sExtends": "xls",
                                "sButtonText": "Excel"
                            },
                            {
                                "sExtends": "pdf",
                                "sButtonText": "PDF"
                            }
                        ]
                    },
                    "oLanguage": {
                        "sProcessing": "Traitement en cours...",
                        "sLengthMenu": "Afficher _MENU_ &eacute;l&eacute;ments",
                        "sZeroRecords": "Aucun &eacute;l&eacute;ment &agrave; afficher",
                        "sInfo": "Affichage : _START_ &agrave; _END_ sur _TOTAL_ &eacute;l&eacute;ments",
                        "sInfoEmpty": "Affichage de l'&eacute;lement 0 &agrave; 0 sur 0 &eacute;l&eacute;ments",
                        "sInfoFiltered": "(filtr&eacute; de _MAX_ &eacute;l&eacute;ments au total)",
                        "sInfoPostFix": "",
                        "sSearch": "Rechercher&nbsp;/&nbsp;Filtrer&nbsp;:",
                        "sLoadingRecords": "T&#233;l&#233;chargement...",
                        "sUrl": "",
                        "oPaginate": {
                            "sFirst": "Premier",
                            "sPrevious": "Pr&eacute;c&eacute;dent",
                            "sNext": "Suivant",
                            "sLast": "Dernier"
                        }
                    }
                });
            }
        });

        function reload(response) {
            var forPile = window.location.href.indexOf("/pile/") > -1;
            if (forPile) {
                $.ajax({
                    type: "POST",
                    url: "./ajax/cnsTransferts.php?sub=1&mat=" + response.mat,
                    data: $("#formCnsTrf").serialize(),
                    success: function (data) {
                        $('#cns-trf-wrapper').html(data);
                    }
                });
            } else {
                if (response.html == 'reload') {
                    document.location.href = 'cnsTrf.php?sub=1&mat=' + response.mat;
                }
            }
        }

        function getTransfertEntities(elem) {
            $("#entite-transfert-container").remove();
            $.post('ajax/cnsTrfActions.php', {action: 'entitesAgence', aid: $(elem).val()}, getTransfertEntitiesCB, 'json');
        }

        function getTransfertEntitiesCB(response) {
            $("#transfert-container").append(response.content);
        }

        function transfert(mat, cid, cn, aid, an, fn , pr) {
            //alert('TRANSFERT : '+cid+" | "+cn+" | "+aid+" | "+an);
            $.post('ajax/cnsTrfActions.php', {action: 'transfertAgence', mat: mat, cid: cid, cn: cn, aid: aid, an: an, fn:fn, pr:pr}, transfertCB, 'json');
        }
        function transfertCB(response) {
            //alert('TRANSFERT CB');
            POP = $('<div></div>').html("<div class='mails'>" + response.html + "</div>").dialog({autoOpen: false, title: 'Transfert vers une autre agence'});
            POP.dialog({zIndex: 10000, autoOpen: false, modal: true, draggable: true, width: 'auto', dialogClass: 'ModalWindowDisplayMeOnTop', close: function (ev, ui) {
                    $(this).empty().remove();
                }});
            POP.dialog("open");
        }
        function transfertGo(mat, aid, cid, cn, newaid, fn , pr) {
            //alert("TRANSFERTGO : cid="+cid+" | newaid="+newaid);
            var eid = $("#entite-transfert").val();
            $.post('ajax/cnsTrfActions.php', {action: 'transfert', mat: mat, aid: aid, eid: eid, cid: cid, cn: cn, newaid: newaid, fn:fn, pr:pr}, reload, 'json');
            closeClosestPopup($("#move-trf-btn"));
        }
        //################################@
        function ajout(mat, cid, cn, aid, an, fn, pr) {
            //alert('TRANSFERT : '+cid+" | "+cn+" | "+aid+" | "+an);
            $.post('ajax/cnsTrfActions.php', {action: 'ajoutAgence', mat: mat, cid: cid, cn: cn, aid: aid, an: an, fn: fn, pr: pr, pa:<?php echo ($forPile ? "$('#IDAGENCE').val()" : 0); ?>}, ajoutCB, 'json');
        }
        function ajoutCB(response) {
            //alert("AJOUT CB");
            POP = $('<div></div>').html("<div class='mails'>" + response.html + "</div>").dialog({autoOpen: false, title: 'Ajout d\'une agence'});
            POP.dialog({zIndex: 10000, autoOpen: false, modal: true, draggable: true, width: 'auto', dialogClass: 'ModalWindowDisplayMeOnTop', close: function (ev, ui) {
                    $(this).empty().remove();
                }});
            POP.dialog("open");
        }
        function ajoutGo(mat, cid, cn, newaid, fn, pr) {
            var eid = $("#entite-transfert").val();
            //console.log(newaid,$(".add-trf-agencies").val());//var newid = $("#newaid").val();
            $.post('ajax/cnsTrfActions.php', {action: 'ajout', mat: mat, cid: cid, cn: cn, newaid: newaid, eid: eid, fn: fn, pr:pr}, reload, 'json');
            closeClosestPopup($("#add-trf-btn"));
        }
        //################################@
        function suppression(mat, cid, cn, aid, an) {
            //alert('TRANSFERT : '+cid+" | "+cn+" | "+aid+" | "+an);
            $.post('ajax/cnsTrfActions.php', {action: 'suppConfirmation', mat: mat, cid: cid, cn: cn, aid: aid, an: an}, suppressionCB, 'json');
        }
        function suppressionCB(response) {
            if (response.online) {
                content = "<p>Suppression impossible !<br/><br/>Le conseiller est connecté à la pile.</p>"
            } else {
                content = response.html;
            }
            POP = $('<div></div>').html("<div class='mails'>" + content + "</div>").dialog({autoOpen: false, title: 'Suppression du rattachement'});
            POP.dialog({zIndex: 10000, autoOpen: false, modal: true, draggable: true, width: 'auto', dialogClass: 'ModalWindowDisplayMeOnTop', close: function (ev, ui) {
                    $(this).empty().remove();
                }});
            POP.dialog("open");
        }
        function suppressionGo(mat, aid, cid, cn) {
            //alert("AJOUTGO : cid="+cid+" | newaid="+newaid);
            $.post('ajax/cnsTrfActions.php', {action: 'suppConfirmee', mat: mat, aid: aid, cid: cid, cn: cn}, reload, 'json');
            closeClosestPopup($("#delete-trf-btn"));
        }
        //################################@


    </script>
</div>