<?php
/****************************************************************************************
SMI (Services Maintenance Interventions) est une gestion libre de maintenance et de SAV

Version 0.9.9

Copyright (C) 2006-2009  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://smitst.homelinux.com
****************************************************************************************/


// 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_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");
Archivelog(@$_SESSION["code_log"]);

$codecli="";
if (isset($_GET['cc']))
	$codecli = strip_tags(trim(@$_GET['cc']));
else
{
	if (strip_tags(trim(@$_POST["val"])) == html_entity_decode($but_valider))
		$codecli = strip_tags(trim(@$_POST['cc']));
}

$enr_ok=FALSE;
$pbm_cli=FALSE;
$msg1_err_type=$ajx_saistc;
if ($codecli <> "")
{
	$row = lit_enr_cli($codecli,TRUE);
	if (is_array($row))
	{
		extract ($row);
		if (strip_tags(trim(@$_POST["val"])) == html_entity_decode($but_valider))
		{
			// On se connecte a la base
			$conn = mysql_connect(DBHOST, DBUSER, DBPASS);
			mysql_select_db(DBNAME);
			
			$lst_chx=$_POST["lstchx"];
			if (count($lst_chx)>0)
			{
				// On ajoute les nouveaux entrants
				foreach($lst_chx as $key=>$value)
				{
					$rech = "SELECT rcli_id FROM ".TBRCLI." WHERE rcli_maitre='".$cli_code."' AND rcli_esclave='".$value."'";
					
					$rs = mysql_query($rech) or die(mysql_error());
					if (mysql_num_rows($rs)==0) // N'existe pas...on ajoute
					{
						$rech2 = "INSERT INTO " .TBRCLI;
						$rech2.= " (rcli_maitre,rcli_esclave) VALUES";
						$rech2.= " ('$cli_code','$value')";
						$rs2 = mysql_query($rech2) or die(mysql_error());
					}
				}
				
				// On supprime les sortants
				$rech = "DELETE FROM `" .TBRCLI. "` WHERE (";
				foreach($lst_chx as $key=>$value)
				{
					$rech .= " rcli_esclave <> '".str_escape(trim($value))."' AND";
				}
				// Suppression du dernier 'AND'
				$rech = substr($rech,0,strlen($rech)-4);
				$rech .= ")";
					
				$rech .= " AND rcli_maitre = '".str_escape(trim($cli_code))."'";
				
				$rs = mysql_query($rech) or die(mysql_error());
				
			}
			else
			{
				// On supprime tout car rien de sélectionné
				$rech = "DELETE FROM `" .TBRCLI. "` WHERE";
				$rech .= " rcli_maitre = '".str_escape(trim($cli_code))."'";
				
				$rs = mysql_query($rech) or die(mysql_error());
			}
			$enr_ok=TRUE;
			mysql_close();
		}
	}
	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=iso-8859-1">
<title>SMI - <?PHP echo $title_esp_prive; ?> : Regroupement Clients</title>

<!-- Feuille de style pour les affichages courants -->
<link href="../css/smi.css" rel="stylesheet" type="text/css">

<!-- Scripts Javascript pour fenêtres -->
<script language="JavaScript" src="../jscript/fen.js"></script>

<!-- Scripts Javascript pour alertes -->
<script language="JavaScript" src="../jscript/alertes.js"></script>

<!-- Scripts Javascript divers -->
<script language="JavaScript" src="../jscript/divers.js"></script>

<!-- Scripts Javascript pour vérifications des champs -->
<script language="JavaScript" src="../jscript/verif_field.js"></script>

<!-- Scripts Ajax -->
<script type="text/javascript" src="../ajax/util.js"></script>
<script type="text/javascript" src="../ajax/SelectUpdater3.js"></script>

<?PHP if (($pbm_cli==FALSE) AND ($enr_ok==FALSE)) { ?>
<script type="text/javascript">
<!--        
function updateCli()
{
	cliUpdater = new SelectUpdater3("lstcli", "<?PHP echo $rep_appli.'/ajax/'; ?>recupcli.php?txt=", "attn1", "msg1");
	var ex_rech = "";
	document.getElementById("rech").onkeyup = function() {
		var val_rech = document.getElementById("rech").value;
		if (val_rech.length > 2)
		{
			if (val_rech != ex_rech)
			{
				// on récupère la liste des clients déjà choisis (on y inclus le compte actuel)
				var client = document.getElementById("cc").value;
				var objsel2 = document.getElementById("lstchx");
				var lst_chx = client+'-';

				for (i=0; i < objsel2.length ; i++)
				{
					if (objsel2.options[i])
					{
						if (objsel2.options[i].value!='')
						{
							lst_chx+=objsel2.options[i].value+'-';
						}
					}
				}
				lst_chx = encodeURIComponent(lst_chx);
				// Faire l'appel Ajax
				cliUpdater.run(val_rech+'_'+lst_chx);
				ex_rech = val_rech;
			}
		}
		else
		{
			// Remettre la liste a vide et annuler l'appel eventuel
			cliUpdater.reset();
			ex_rech = "";
			// Remise en place texte d'alerte
			document.getElementById("attn1").innerHTML='';
			document.getElementById("msg1").innerHTML='<?PHP echo $msg1_err_type; ?>';
		}
	}
}

function move_select(idsel1,idsel2)
{
	var objsel1 = document.getElementById(idsel1);
	var objsel2 = document.getElementById(idsel2);
	var objsel1_lng = objsel1.length;
	for (i=(objsel1_lng-1); i >= 0 ; i--)
	{
		if (objsel1.options[i])
		{
			if (objsel1.options[i].selected && (objsel1.options[i].value!=''))
			{
				nouvel_element = new Option(objsel1.options[i].text,objsel1.options[i].value);
				objsel2.options[objsel2.length] = nouvel_element;
				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;
	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)
	{
		cliUpdater = new SelectUpdater3("lstcli", "<?PHP echo $rep_appli.'/ajax/'; ?>recupcli.php?txt=", "attn1", "msg1");
		var val_rech = document.getElementById("rech").value;
		if (val_rech.length > 2)
		{
			// on récupère la liste des clients déjà choisis
			var client = document.getElementById("cc").value;
			var objsel = document.getElementById("lstchx");
			var lst_chx = client+'-';
	
			for (i=0; i < objsel.length ; i++)
			{
				if (objsel.options[i])
				{
					if (objsel.options[i].value!='')
					{
						lst_chx+=objsel.options[i].value+'-';
					}
				}
			}
			lst_chx = encodeURIComponent(lst_chx);
			// Faire l'appel Ajax
			cliUpdater.run(val_rech+'_'+lst_chx);
		}
		else
		{
			// Remettre la liste a vide et annuler l'appel eventuel
			cliUpdater.reset();
			// Remise en place texte d'alerte
			document.getElementById("attn1").innerHTML='';
			document.getElementById("msg1").innerHTML='<?PHP echo $msg1_err_type; ?>';
		}
	}
}

function all_selected(idsel)
{
	var objsel = document.getElementById(idsel);
	var objsel_lng = objsel.length;
	for (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= new Array();
	for(i=0;i<objsel_lng;i++)
	{
		liste[i]=new Array();
		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(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];
	}
}

//-->
</script>

</head>
<?PHP
echo "<body onLoad=\"updateCli();metFocus();\">";

?>
<p align="center"> <span class="titrepage">Regroupement de clients</span></p>
<p align="center"><span class="titre_gras">Pour le client : <?php echo $cli_ste; ?> </span></p>
<table width="890"  border="0">
<tr>
	<td width="33%">&nbsp;</td>
	<td width="33%">
	<div align="center"><span class="annot_std_it">(<img src="../img/oblig.png" align="absmiddle" alt="<?PHP echo $alt_chp_oblig; ?>"> : <?PHP echo $txt_div_saisoblg; ?>) </span></td>
	<td width="33%" align="right">
    <input name="quit" type="button" class="bton_std" id="quit" value="<?PHP echo $but_quit; ?>" style="text-decoration: none; font-size: 11px; color:White ;font-weight:bold;background-color: #666666;" onClick="javascript:; self.close('fscomp');">
	</td>
</tr>
</table>
<form name="rcli_maj" method="post" action="rcli_maj.php" onSubmit="javascript: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 $txt_chp_filtsoc; ?> </td>
	<td>
		<input name="rech" type="text" id="rech" value="" size="50" maxlength="50">
		<img src="../img/oblig.png" align="absmiddle" alt="<?PHP echo $alt_chp_oblig; ?>">
		<span id="attn1"></span><span id="msg1" style="background-color:#FF0000; color:#FFFF00; font-weight:bold"><?PHP echo htmlspecialchars($msg1_err_type); ?></span><br />
		<div class="annot_petit_it">Saisir au moins 3 caract&egrave;res</div>
	</td>
</tr>
</table>
<table width="890"  border="0">
<tr>
	<td colspan="2" class="annot_petit_it" align="center">
	Utilisez les ic&ocirc;nes ci-dessous pour d&eacute;placer vos s&eacute;lections ou double cliquez sur une ligne pour la d&eacute;placer.
	</td>
</tr>
<tr>
	<td class="rubfrm" id="f_lstcli" align="center" colspan="2"><?PHP echo $txt_chp_cling; ?></td>
</tr>
<tr>
	<td width="20" valign="middle">
	<img src="../img/tri_haut.png" onClick="javascript:sort_select('lstcli',false);" alt="Tri croissant" title="Tri croissant">
	<br /><br /><br />
	<img src="../img/tri_bas.png" onClick="javascript:sort_select('lstcli',true);" alt="Tri d&eacute;croissant" title="Tri d&eacute;croissant">
	</td>
	<td>
		<?PHP
			echo '<select multiple="multiple" class="annot_petit" name="lstcli" id="lstcli" style="width:870px;" size="20" OnDblClick="javascript:move_select(this.id,\'lstchx\');">';
			echo '</select>';
		?>
	</td>
</tr>
<tr>
	<td align="center" colspan="2">
	<img src="../img/selall_dn.png" onClick="javascript:all_selected('lstcli');move_select('lstcli','lstchx');" alt="selall_dn" title="Tout vers les clients non g&eacute;r&eacute;s">
	<img src="../img/none.gif" height="16" width="50">
	<img src="../img/sel_dn.png" onClick="javascript:move_select('lstcli','lstchx');" alt="sel_dn" title="S&eacute;lection vers les clients g&eacute;r&eacute;s">
	<img src="../img/none.gif" height="16" width="100">
	<img src="../img/sel_up.png" onClick="javascript:del_selected('lstchx');" alt="sel_up" title="S&eacute;lection vers les clients non g&eacute;r&eacute;s">
	<img src="../img/none.gif" height="16" width="50">
	<img src="../img/selall_up.png" onClick="javascript:all_selected('lstchx');del_selected('lstchx');" alt="selall_up" title="Tout vers les clients non g&eacute;r&eacute;s">
	</td>
</tr>
<tr>
	<td class="rubfrm" id="f_lstchx" align="center" colspan="2"><?PHP echo $txt_chp_clig; ?></td>
</tr>
<tr>
	<td width="20" valign="middle">
	<img src="../img/tri_haut.png" onClick="javascript:sort_select('lstchx',false);" alt="Tri croissant" title="Tri croissant">
	<br /><br /><br />
	<img src="../img/tri_bas.png" onClick="javascript:sort_select('lstchx',true);" alt="Tri d&eacute;croissant" title="Tri d&eacute;croissant">
	</td>
	<td align="center">
		<?PHP
			echo '<select multiple="multiple" class="annot_petit" name="lstchx[]" id="lstchx" style="width:870px;" size="20" OnDblClick="javascript:del_selected(this.id);">';
			// On se connecte a la base
			$conn = mysql_connect(DBHOST, DBUSER, DBPASS);
			mysql_select_db(DBNAME);
			$rech = "SELECT rcli_esclave FROM ".TBRCLI." WHERE rcli_maitre='".$cli_code."'";
			
			$rs = mysql_query($rech) or die(mysql_error());
			if (mysql_num_rows($rs)>0)
			{
				while($row = mysql_fetch_array($rs))
				{
					extract($row);
					$rech2= "SELECT * FROM `" .TBCLI. "` WHERE `cli_code` = '".$rcli_esclave."'";
					$rs2 = mysql_query($rech2) or die(mysql_error());
					if (mysql_num_rows($rs2) == 1)
					{
						if ($row2=mysql_fetch_array($rs2))
						{
							extract($row2);
							// On ne prend que les comptes actifs
							$rech3= "SELECT pw_id FROM `" .TBPW. "` WHERE `pw_code` = '".$cli_code."' AND `pw_actif` = '0'";
							$rs3 = mysql_query($rech3) or die(mysql_error());
							if (mysql_num_rows($rs3) == 0)
							{
								$txtres = $cli_ste.", ".$cli_adr1;
								if (trim($cli_adr2)<>"")
									$txtres.=", ".$cli_adr2;
								$txtres.=", ".Retournecp_openId($cli_ville,FALSE)." ".Retourneville_openId($cli_ville,FALSE);
								echo '<option value="'.$cli_code.'"';
								echo '>'.$txtres.'</option>';
							}
						}
					}
				}
			}
			mysql_close();
			echo '</select>';
		?>
	</td>
</tr>
</table>
<p align="center">
<input name="val" type="submit" class="bton_std" id="val" value="<?PHP echo $but_valider; ?>">
</p>
</form>
<?PHP
}
else
{
?>
	<script type="text/javascript">
	<!--
	self.close('fscomp');
	//-->
	</script>
<?PHP
}
?>
</body>
</html>
