<?php
/****************************************************************************************
 * SMI (Services Maintenance Interventions) est une gestion libre de maintenance et de SAV
 *
 * Version 1.0.0
 *
 * Copyright (C) 2006-2014  Sylvain FATOME
 * This program is free software; you can redistribute it and/or modify it under the terms
 * of the GNU General Public License as published by the Free Software Foundation;
 * either version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program
 * (in the directory docs);
 * if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA  02110-1301, USA.
 *
 * Contact : galawa@free.fr
 *
 * Web : http://smi.no-ip.org
 ****************************************************************************************/


// vérification des tentatives de hack
$pos = strpos($_SERVER['PHP_SELF'], "inc.php");
if ($pos === FALSE)
    $ok_inc = TRUE;
else
    $ok_inc = FALSE;
if ($ok_inc == FALSE) header("Location: ../index.php");

include_once("../inc/func.inc.php");
include_once("../inc/func_geo.inc.php");
include_once("../inc/func_txt.inc.php");
include_once("../inc/fic_cli.inc.php");
include_once("../inc/fic_dos.inc.php");
include_once("../inc/fic_droits.inc.php");
include_once("../inc/fic_hum.inc.php");
include_once("../inc/fic_int.inc.php");
include_once("../inc/fic_loc.inc.php");
include_once("../inc/fic_ot.inc.php");
include_once("../inc/lst.inc.php");
include_once("../classes/ezSQL/shared/ez_sql_core.php");
include_once("../classes/ezSQL/mysqli/ez_sql_mysqli.php");
include_once("../inc/func_sql.inc.php");
Archivelog(@$_SESSION["code_log"]);
// Variables Formulaire
fix_magic_quotes();
$_POST = clean_str($_POST);
$_GET = clean_str($_GET);

$codecli = "";
if (isset($_GET['cc']))
    $codecli = @$_GET['cc'];
else {
    if (@$_POST["val"] == _("Valider"))
        $codecli = @$_POST['cc'];
}

$enr_ok = FALSE;
$pbm_cli = FALSE;

if ($codecli <> "") {
    $row = lit_enr_cli($codecli, TRUE);
    if (is_array($row)) {
        $row = encode_str($row);
        extract($row);
        if (@$_POST["val"] == _("Valider")) {
            // On se connecte a la base
            $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);

            $lst_chx = $_POST["lstchx"];
            if (count($lst_chx) > 0) {
                // On ajoute les nouveaux entrants
                foreach ($lst_chx as $key => $value) {
                    $rech = "SELECT COUNT(*) FROM `" . TBRCLI . "` WHERE rcli_maitre='" . $cli_code . "' AND rcli_esclave='" . $value . "'";
                    $nbres = $db->get_var($rech);

                    if ($nbres == 0) // N'existe pas...on ajoute
                    {
                        $rech2 = "INSERT INTO `" . TBRCLI . "`";
                        $rech2 .= " (rcli_maitre,rcli_esclave) VALUES";
                        $rech2 .= " ('$cli_code','$value')";
                        $db->query($rech2);
                    }
                }

                // On supprime les sortants
                $rech = "DELETE FROM `" . TBRCLI . "` WHERE (";
                foreach ($lst_chx as $key => $value) {
                    $rech .= " rcli_esclave <> '" . $db->escape($value) . "' AND";
                }
                // Suppression du dernier 'AND'
                $rech = substr($rech, 0, strlen($rech) - 4);
                $rech .= ")";

                $rech .= " AND rcli_maitre = '" . $db->escape($cli_code) . "'";

                $db->query($rech);

            } else {
                // On supprime tout car rien de sélectionné
                $rech = "DELETE FROM `" . TBRCLI . "` WHERE";
                $rech .= " rcli_maitre = '" . $db->escape($cli_code) . "'";

                $db->query($rech);
            }
            $enr_ok = TRUE;
            $db->disconnect();
        }
    } else
        $pbm_cli = TRUE;
} else
    $pbm_cli = TRUE;
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>SMI - <?PHP echo _("ESPACE PRIVE"); ?> : <?PHP echo _("Regroupement Clients"); ?></title>

    <?PHP include_once("../inc/header.inc.php"); ?>

    <?PHP if (($pbm_cli == FALSE) AND ($enr_ok == FALSE)) { ?>
    <script type="text/javascript">
        <!--
        function move_select(idsel1, idsel2) {
            var objsel1 = document.getElementById(idsel1);
            var objsel2 = document.getElementById(idsel2);
            var objsel1_lng = objsel1.length;
            var i;
            for (i = (objsel1_lng - 1); i >= 0; i--) {
                if (objsel1.options[i]) {
                    if (objsel1.options[i].selected && (objsel1.options[i].value != '')) {
                        objsel2.options[objsel2.length] = new Option(objsel1.options[i].text, objsel1.options[i].value);
                        objsel1.options[i] = null;
                    }
                }
            }
        }

        function del_selected(idsel) {
            var update = false;
            var objsel = document.getElementById(idsel);
            // On supprime les lignes
            var objsel_lng = objsel.length;
            var i;
            for (i = (objsel_lng - 1); i >= 0; i--) {
                if (objsel.options[i]) {
                    if (objsel.options[i].selected && (objsel.options[i].value != '')) {
                        objsel.options[i] = null;
                        update = true;
                    }
                }
            }

            // On réactualise la lise de choix uniquement s'il y a eu une modification
            if (update == true) {
                var val_rech = $("#rech").val();
                if (val_rech.length > 2) {
                    var $lstcli = $("#lstcli");
                    $lstcli.empty();

                    var $lst_chx = $("#cc").val();

                    var $lstchx = $("#lstchx");
                    if ($lstchx.length > 0) {
                        $lstchx.find("option").each(function () {
                            if (this.value != '') {
                                $lst_chx = $lst_chx + '-' + this.value;
                            }
                        });
                    }
                    $lst_chx = encodeURIComponent($lst_chx);

                    $.ajax({
                        url: "<?PHP echo $rep_appli.'/ajax/'; ?>recupcli.php",
                        data: "txt=" + val_rech + '_' + $lst_chx,
                        type: "GET",
                        success: function (data) {
                            if (data != "") {
                                var options = data.split(";");
                                var opt_val;
                                for (var i = 0; i < options.length; i++) {
                                    opt_val = options[i].split("="); // value = text
                                    $lstcli.append('<option value="' + opt_val[0] + '">' + opt_val[1] + '</option>');
                                }
                            }
                        }
                    });
                }
            }
        }

        function all_selected(idsel) {
            var objsel = document.getElementById(idsel);
            var objsel_lng = objsel.length;
            // var i = 0;
            for (var i = 0; i < objsel_lng; i++) {
                objsel.options[i].selected = true;
            }
        }

        function sort_select(idsel, inverse) {
            var objsel = document.getElementById(idsel);
            var objsel_lng = objsel.length;

            // On construit la liste des valeurs du select
            var liste = [];
            //var i = 0;
            for (var i = 0; i < objsel_lng; i++) {
                liste[i] = [];
                liste[i][0] = objsel.options[i].text;
                liste[i][1] = objsel.options[i].value;
                liste[i][2] = objsel.options[i].selected;
            }

            // On trie
            liste = liste.sort();
            if (inverse == true)
                liste = liste.reverse();

            // On réaffiche
            for (var i = 0; i < objsel_lng; i++) {
                objsel.options[i].text = liste[i][0];
                objsel.options[i].value = liste[i][1];
                objsel.options[i].selected = liste[i][2];
            }
        }

        function init_all() {
            init_Body();
            init_ajax_cli();
            add_func_click('quit', 'sclose','');
            Focus_first();
        }

        $(document).ready(function () {
            init_all();
        });

        //-->
    </script>

</head>

<body>
<p align="center"><span class="titrepage"><?PHP echo _("Regroupement de clients"); ?></span></p>

<p align="center"><span class="titre_gras"><?PHP echo _("Pour le client"); ?> : <?php echo $cli_ste; ?> </span></p>
<table width="890" border="0">
    <tr>
        <td width="33%">&nbsp;</td>
        <td width="33%" align="center" class="annot_petit_it">
            <div id="oblig">(<img src="../img/oblig.png" align="absmiddle" alt="<?PHP echo _("Champ obligatoire"); ?>">
                : <?PHP echo _("Saisie obligatoire"); ?>)
            </div>
        </td>
        <td width="33%" align="right">
            <input name="quit" type="button" class="bton_std" id="quit" value="<?PHP echo _("Quitter"); ?>"
                   style="text-decoration: none; font-size: 11px; color:White ;font-weight:bold;background-color: #666666;">
        </td>
    </tr>
</table>
<form name="rcli_maj" method="post" action="rcli_maj.php" onSubmit="all_selected('lstchx');return true;">
    <input name="cc" type="hidden" id="cc" value="<?PHP echo $codecli ?>">
    <table width="890" border="0">
        <tr>
            <td width="160" height="40" class="rubfrm" id="f_rech" align="right"><?PHP echo _("Filtrer sur société"); ?> </td>
            <td>
                <input name="rech" type="text" id="rech" value="" size="50" maxlength="50">
                <img src="../img/oblig.png" align="absmiddle" alt="<?PHP echo _("Champ obligatoire"); ?>">

                <div class="annot_petit_it"><?PHP echo _("Saisir au moins 3 caractères"); ?></div>
            </td>
        </tr>
    </table>
    <table width="890" border="0">
        <tr>
            <td colspan="2" class="annot_petit_it" align="center">
                <?PHP echo _("Utilisez les icônes ci-dessous pour déplacer vos sélections ou double cliquez sur une ligne pour la déplacer"); ?>
            </td>
        </tr>
        <tr>
            <td class="rubfrm" id="f_lstcli" align="center" colspan="2"><?PHP echo _("Clients non gérés"); ?></td>
        </tr>
        <tr>
            <td width="20" valign="middle">
                <img src="../img/tri_haut.png" onClick="sort_select('lstcli',false);" alt="<?PHP echo _("Tri croissant"); ?>"
                     title="<?PHP echo _("Tri croissant"); ?>">
                <br /><br /><br />
                <img src="../img/tri_bas.png" onClick="sort_select('lstcli',true);" alt="<?PHP echo _("Tri décroissant"); ?>"
                     title="<?PHP echo _("Tri décroissant"); ?>">
            </td>
            <td>
                <?PHP
                echo '<select multiple="multiple" class="annot_petit" name="lstcli" id="lstcli" style="width:870px;" size="20" OnDblClick="move_select(this.id,\'lstchx\');">';
                echo '</select>';
                ?>
            </td>
        </tr>
        <tr>
            <td align="center" colspan="2">
                <img src="../img/selall_dn.png"
                     onClick="all_selected('lstcli');move_select('lstcli','lstchx');" alt="selall_dn"
                     title="<?PHP echo _("Tout vers les clients non gérés"); ?>">
                <img src="../img/none.gif" height="16" width="50">
                <img src="../img/sel_dn.png" onClick="move_select('lstcli','lstchx');" alt="sel_dn"
                     title="<?PHP echo _("Sélection vers les clients gérés"); ?>">
                <img src="../img/none.gif" height="16" width="100">
                <img src="../img/sel_up.png" onClick="del_selected('lstchx');" alt="sel_up"
                     title="<?PHP echo _("Sélection vers les clients non gérés"); ?>">
                <img src="../img/none.gif" height="16" width="50">
                <img src="../img/selall_up.png" onClick="all_selected('lstchx');del_selected('lstchx');"
                     alt="selall_up" title="<?PHP echo _("Tout vers les clients non gérés"); ?>">
            </td>
        </tr>
        <tr>
            <td class="rubfrm" id="f_lstchx" align="center" colspan="2"><?PHP echo _("Clients gérés"); ?></td>
        </tr>
        <tr>
            <td width="20" valign="middle">
                <img src="../img/tri_haut.png" onClick="sort_select('lstchx',false);" alt="<?PHP echo _("Tri croissant"); ?>"
                     title="<?PHP echo _("Tri croissant"); ?>">
                <br /><br /><br />
                <img src="../img/tri_bas.png" onClick="sort_select('lstchx',true);" alt="<?PHP echo _("Tri décroissant"); ?>"
                     title="<?PHP echo _("Tri décroissant"); ?>">
            </td>
            <td align="center">
                <?PHP
                echo '<select multiple="multiple" class="annot_petit" name="lstchx[]" id="lstchx" style="width:870px;" size="20" OnDblClick="del_selected(this.id);">';
                // On se connecte a la base
                $db = open_database(DBUSER, DBPASS, DBNAME, DBHOST);
                $rech = "SELECT rcli_esclave FROM `" . TBRCLI . "` WHERE rcli_maitre='" . $cli_code . "'";

                $rows = $db->get_results($rech, ARRAY_A);
                if ($rows) {
                    foreach ($rows as $row) {
                        $row = encode_str($row);
                        extract($row);
                        $rech2 = "SELECT * FROM `" . TBCLI . "` WHERE `cli_code` = '" . $rcli_esclave . "'";
                        $row2 = $db->get_row($rech2, ARRAY_A);

                        if ($row2) {
                            extract($row2);
                            // On ne prend que les comptes actifs
                            $rech3 = "SELECT COUNT(*) FROM `" . TBPW . "` WHERE `pw_code` = '" . $cli_code . "' AND `pw_actif` = '0'";
                            $nbres3 = $db->get_var($rech3);
                            if ($nbres3 == 0) {
                                $txtres = $cli_ste . ", " . $cli_adr1;
                                if (trim($cli_adr2) <> "")
                                    $txtres .= ", " . $cli_adr2;
                                $txtres .= ", " . Retournecp_Id($cli_ville, FALSE) . " " . Retourneville_Id($cli_ville, FALSE);
                                echo '<option value="' . $cli_code . '"';
                                echo '>' . $txtres . '</option>';
                            }
                        }
                    }
                }
                $db->disconnect();
                echo '</select>';
                ?>
            </td>
        </tr>
    </table>
    <p align="center">
        <input name="val" type="submit" class="bton_std" id="val" value="<?PHP echo _("Valider"); ?>">
    </p>
</form>
<?PHP
}
else
    close_fen_auto('', '');
?>
</body>
</html>
