<?php
include ("header.php");


function contrat_new_mod($id, $id_axa, $id_type='', $avenant=0) { //$avenant=2 => resiliation
	global $link, $USERS, $CONTRATS, $GLOBAL_TITRE;

	$color_table="#FFFFFF";
	$color_left="#FAFAFA";
	$color_right="#FFFFFF";
			
	if (($id=='' && $id_axa=='') || ($avenant)){
		$date_souscription="";
		$date_effet_debut="";
		$date_effet_fin="";
		$date_echeance="";
		
		$prime="";
		$montant="0";
		$information="";
		$prime_paye='0000-00-00 00:00:00';
		
		$id_axa="";
		$id_client=((isset($_GET["id_client"]))?client_id($_GET["id_client"]):0);
		$id_apporteur=0;
		$id_utilisateur=$_SESSION["SS_user_id"];
		$id_devis=0;
		$souscription_lieu="";
		$souscription_origine="";
		$scan="0";
		
		if ($avenant) {
			$titre_page='<b><a href="contrat.php?req=mod&id='.$id.'" class="white" target="_blank" >Contrat '.contrat_id_axa($id).'</a>&nbsp;&raquo;&nbsp;';
			if ($avenant==1) $titre_page.='<img src="../images/admin/avenant.gif" align="absmiddle"> Ajout d\'un avenant</b>';
			if ($avenant==2) $titre_page.='<img src="../images/admin/resiliation.gif" align="absmiddle"> Résiliation</b>';
			$info="";
			$id_contrat=$id;
			$id_avenant=avenant_id($id);
			$id_contrat_axa=contrat_id_axa($id);
			}
		else {
			$titre_page="Ajout d'un contrat";
			$info="";
			$id_contrat=0;
			}
		$id="";
		}
		
	else {
	    if ($id_axa!="") $result=mysql_query("SELECT * FROM contrats WHERE id_axa='$id_axa'", $link);
		else $result=mysql_query("SELECT * FROM contrats WHERE id='$id'", $link);
		if (mysql_num_rows($result)==0) {echo '<center><br />Aucun enregistrement ne correspond à cet identifiant !<br /><br /></center>'; return false;}
		$row=mysql_fetch_array($result); 
		foreach ($row as $key=>$value) ${$key}=html($value);
		if ($id_contrat!=0) $avenant=1;
		if ($resiliation!="") $avenant=2;
		//if ($date_souscription=="0000-00-00") $date_souscription="";
		//if ($date_effet_debut=="0000-00-00") $date_effet_debut="";
		//if ($date_effet_fin=="0000-00-00") $date_effet_fin="zz";
		//if ($date_echeance=="0000-00-00") $date_echeance="";
		
		if ($avenant) {
			$id_avenant=avenant_id($id);
			$id_contrat_axa=contrat_id_axa($id_contrat);
			$titre_page='<b><a class="white" target="_blank" href="contrat.php?req=mod&id='.$id_contrat.'">Contrat '.contrat_id_axa($id_contrat).'</a>&nbsp;&raquo;&nbsp;';
			if ($avenant==1) $titre_page.='<img src="../images/admin/avenant.gif" align="absmiddle"> Modification de l\'avenant '.$id_avenant.'</b>';
			if ($avenant==2) $titre_page.='<img src="../images/admin/resiliation.gif" align="absmiddle"> Modification de la résiliation du contrat</b>';
			$info="";
			}
		else {
			$titre_page='Modification du contrat '.$id_axa;
			$info="&nbsp;&nbsp;&nbsp;Ajouté par ".utilisateur_nom($id_utilisateur_add)." le ".datetime_short($date_add);
			if ($date_mod!="0000-00-00 00:00:00") $info.="<br>&nbsp;&nbsp;&nbsp;Modifié par ".utilisateur_nom($id_utilisateur_mod)." le ".datetime_short($date_mod);
			}
		}
	$GLOBAL_TITRE.=strip_tags($titre_page);

	
	echo '	
	<table cellpadding="2" cellspacing="0" border="0" bgcolor="000000" width="100%">
	<form method="post" action="contrat.php" name="form1">
    <tr> 
       <td valign="top" class="white" height="22">
		<b>&raquo;&nbsp;</b><a class="white" href="contrat.php?req=liste"><b>Contrats</b></a><b>&nbsp;&raquo;&nbsp;'.$titre_page.'</b>
	</td></tr>
	<tr>
		<td valign="top" class="white" height="22" bgcolor="#999999">
		'.$info.'
	</td></tr>
	
	
	<tr>
    <td valign="top" width="100%" bgcolor="#ffffff">
	
	
	
	<table cellpadding="5" cellspacing="1" border="0" bgcolor="'.$color_table.'">
	';
	
	
	if (!$avenant) {
	echo '
		<tr>
			<td align="right" bgcolor="'.$color_left.'"><b>Id</b></td>
			<td bgcolor="'.$color_right.'"><input type="text" name="id_axa" size="20" maxlength="250" value="'.$id_axa.'"></td>
		</tr>
		<tr>
			<td align="right" bgcolor="'.$color_left.'"><b>Type</b></td>
			<td bgcolor="'.$color_right.'">
			<select name="id_type" onchange="document.getElementById(\'i_select_pieces\').src=\'iframes.php?req=select_pieces_contrat_type&id=\'+this.options[this.selectedIndex].value">';
			$result=mysql_query("SELECT id, titre FROM contrats_type", $link);
			while ($row=mysql_fetch_array($result)){
				echo '<option value="'.$row["id"].'" '.(($id_type==$row["id"])?"SELECTED":"").'>'.$row["titre"];
				}
			echo '
			</select></td>
		</tr>
		<tr>
			<td align="right" bgcolor="'.$color_left.'"><b>Client</b></td>
			<td bgcolor="'.$color_right.'"><input type="text" 
				onchange="if(document.getElementById(this.value)) document.getElementById(this.value).selected=true; else alert(\'Aucun client correspondant\');" 
				name="id_client_axa" 
				id="id_client_axa" 
				value="'.client_id_axa($id_client).'"
				size="20"><select 
					name="id_client" 
					id="id_client" 
					onchange="document.getElementById(\'id_client_axa\').value=this.options[selectedIndex].id;">';
			$result=mysql_query("SELECT id, id_axa, nom, prenom FROM clients ORDER BY nom, prenom ASC", $link);
			while ($row=mysql_fetch_array($result)){
				echo '<option id="'.$row["id_axa"].'" value="'.$row["id"].'" '.(($id_client==$row["id"])?"SELECTED":"").'>'.strtoupper($row["nom"]).' '.ucwords($row["prenom"]).' '.$row["id_axa"];
				}
			echo '
				</select></td>
		</tr>';
		}
	else echo '
		<tr>
			<td align="right" bgcolor="'.$color_left.'"><b>Id</b></td>
			<td bgcolor="'.$color_right.'">'.$id_contrat_axa.' '.$id_avenant.'</td>
		</tr>';
	
		
	echo '
	
	<tr>
		<td align="right" bgcolor="'.$color_left.'"><b>Date de '.(($avenant==2)?"demande":"souscription").'</b></td>
		<td bgcolor="'.$color_right.'"><input type="text" id="date_souscription" name="date_souscription" size="8" maxlength="8" value="'.date_sql2txt($date_souscription).'"> JJMMAAAA</td>
	</tr>
	<tr>
		<td align="right" bgcolor="'.$color_left.'"><b>Date d\'effet</b></td>
		<td bgcolor="'.$color_right.'"><input type="text" id="date_effet_debut" name="date_effet_debut" size="8" maxlength="8" value="'.date_sql2txt($date_effet_debut).'"> JJMMAAAA</td>
	</tr>
	<tr>
		<td align="right" bgcolor="'.$color_left.'"><b>Date d\'échéance</b></td>
		<td bgcolor="'.$color_right.'"><input type="text" id="date_echeance" name="date_echeance" size="8" maxlength="8" value="'.date_sql2txt($date_echeance).'"> JJMMAAAA</td>
	</tr>
	
	'.
	(($avenant!=2)?'
	<tr>
		<td align="right" bgcolor="'.$color_left.'"><b>Date de fin d\'effet</b></td>
		<td bgcolor="'.$color_right.'"><input type="text" id="date_effet_fin" name="date_effet_fin" size="8" maxlength="8" value="'.date_sql2txt($date_effet_fin).'"> JJMMAAAA</td>
	</tr>
	':"")
	
	.'
	<tr>
		<td align="right" bgcolor="'.$color_left.'"><b>Montant</b></td>
		<td bgcolor="'.$color_right.'"><input type="text" name="montant" size="5" maxlength="20" value="'.$montant.'">€</td>
	</tr>
	<tr>
		<td align="right" bgcolor="'.$color_left.'"><br /></td>
		<td bgcolor="'.$color_right.'"></td>
	</tr>';
	
	
	if ($avenant!=2) {
		echo '
		<tr>
			<td align="right" valign="top" bgcolor="'.$color_left.'"><b>Pi&egrave;ces &agrave; fournir</b></td>
			<td bgcolor="'.$color_right.'">
			<div id="select_pieces_div"></div>
			<iframe id="i_select_pieces" name="i_select_pieces" frameborder="0" height="0" width="0" src="iframes.php?req=select_pieces_contrat_type&id='.$id_type.'"></iframe>
			
			<font class="mini"><br /><br /></font>
			<div id="my_base" name="my_base" style="width:500px">
			<table cellpadding="3" bgcolor="#dddddd" cellspacing="1" border="0" height="30"><tr bgcolor="#666666">
			<td width="50" align="center"><font class="white">Fournie</font></td>
			<td width="300"><font class="white">Pièce à fournir</font></td>
			<td width="50" align="center"><font class="white">Action</font></td>
			</tr></table>
			';
		
		
		
		if ($id==0) {
			if ($id_type!=25){// BANQUE, on laisse la liste complète
				$sql_more="";
				if (!$avenant){ // avenant on laisse
					if ($id_type<=4) {//AUTO
						$sql_more.=",4,5,23"; // carte et permis de conduire
						if ($id_type==3) $sql_more.=",5,11,12,26"; // MOTO - bordereau + club 14
						}
					}
				$result=mysql_query("SELECT p.id, p.nom, 0 as fournie FROM pieces p WHERE p.id IN(1,2,25".$sql_more.")", $link);
				}
			else $result=mysql_query("SELECT p.id, p.nom, 0 as fournie FROM contrats_type_pieces ctp, pieces p WHERE ctp.id_contrat_type='".$id_type."' AND p.id=ctp.id_piece", $link);
			}
		else $result=mysql_query("SELECT p.id, p.nom, cp.fournie FROM contrats_pieces cp, pieces p WHERE cp.id_contrat='".$id."' AND p.id=cp.id_piece", $link);
		while ($row=mysql_fetch_array($result)){
			echo '
				<span id="p_'.$row["id"].'">
				<table cellpadding="3" bgcolor="#eeeeee" cellspacing="1" border="0"><tr bgcolor="#FFFFFF" >
				<td width="50" align="center">
					<input type="hidden" name="pieces[id]['.$row["id"].']" id="pieces[id]['.$row["id"].']" value="'.$row["id"].'" >
					<input type="checkbox" name="pieces[checked]['.$row["id"].']" id="pieces[checked]['.$row["id"].']" value="1" '.(($row["fournie"]==1)?"CHECKED":"").'></td>
				<td width="300"><label for="pieces[checked]['.$row["id"].']">'.$row["nom"].'</label></td>
				<td width="50" align="center"><a href="javascript:void(0);" onclick="document.getElementById(\p_'.$row["id"].'\).removeNode(true);">Effacer</a></td>
				</tr></table>
				</span>';
			}
	
	
		
		echo '<span id="last"></span></div>
		
		<script>';
		?>
	 
		function piece_add(id, texte){
			if (document.getElementById("p_"+id)==null){
				var nod=document.createElement("SPAN");
				nod.id="p_"+id;
				nod.innerHTML='<table cellpadding="3" bgcolor="#eeeeee" cellspacing="1" border="0"><tr bgcolor="#FFFFFF"><td width="50" align="center"><input type="hidden" name="pieces[id]['+ id +']" id="pieces[id]['+ id +']" value="'+ id +'" ><input type="checkbox" name="pieces[checked]['+ id +']" id="pieces[checked]['+ id +']" value="1"></td><td width="300"><label for="pieces[checked]['+ id +']">'+ texte +'</label></td><td width="50" align="center"><a href="javascript:void(0);" onclick="document.getElementById(\'p_'+ id +'\').removeNode(true);">Effacer</a></td></tr></table>';
				document.getElementById("my_base").insertBefore(nod, last);
				}
			}
	
		
		<?php	


		echo '</script><br /><br />
		
		</td>
		</tr>
		
		';
		}
	
	if ($avenant==2) {
		if ($id!="") $resiliation=contrat_resiliation_get($id);
		contrat_resiliation_init($resiliation);
		
		echo '
		<tr>
			<td align="right" bgcolor="'.$color_left.'"><b>Remboursement</b></td>
			<td bgcolor="'.$color_right.'"><input type="text" name="resiliation[remboursement]"" size="5" maxlength="20" value="'.$resiliation["remboursement"].'">€</td>
		</tr>
		<tr>
			<td align="right" bgcolor="'.$color_left.'"><b>Par chèque</b></td>
			<td bgcolor="'.$color_right.'">
				<input type="radio" name="resiliation[cheque]" id="remboursement_cheque1" value="1" '.(($resiliation["cheque"])?"CHECKED":"").'><label for="remboursement_cheque1">Oui</label>
				<input type="radio" name="resiliation[cheque]" id="remboursement_cheque0" value="0" '.((!$resiliation["cheque"])?"CHECKED":"").'><label for="remboursement_cheque0">Non</label>
			
			</td>
		</tr>
		<tr>
			<td valign="top" align="right" bgcolor="'.$color_left.'"><b>Résilié par</b></td>
			<td bgcolor="'.$color_right.'">';
			foreach ($CONTRATS["resiliation_par"] as $par_id=>$par_text){
				echo '<input type="radio" name="resiliation[par]" id="resiliation_par_'.$par_id.'" value="'.$par_id.'" '.(($resiliation["par"]==$par_id)?"CHECKED":"").'><label for="resiliation_par_'.$par_id.'">'.$par_text.'</label><br />';
				}
			echo '</td>
		</tr>
		<tr>
			<td align="right" bgcolor="'.$color_left.'" height="35"><b>Motif de résiliation</b></td>
			<td bgcolor="'.$color_right.'"><select name="resiliation[motif]"
			onchange="slcted=this.options[this.selectedIndex].value; if (slcted==1 || slcted==2 || slcted==10 || slcted==11 || slcted==30 || slcted==50 || slcted==51) document.getElementById(\'resiliation[more]\').style.display=\'inline\'; else document.getElementById(\'resiliation[more]\').style.display=\'none\';"
			onkeyup="slcted=this.options[this.selectedIndex].value; if (slcted==1 || slcted==2 || slcted==10 || slcted==11 || slcted==30|| slcted==50 || slcted==51) document.getElementById(\'resiliation[more]\').style.display=\'inline\'; else document.getElementById(\'resiliation[more]\').style.display=\'none\';">
		';
		foreach ($CONTRATS["resiliation_motif"] as $optgroups=>$options){
			echo '<optgroup label="'.$optgroups.'">';
			foreach ($options as $option_id=>$option_text){
				echo '<option value="'.$option_id.'" '.(($resiliation["motif"]==$option_id)?"SELECTED":"").'>'.$option_text.'</option>';
				}
			echo '</optgroup>';
			}
		
		echo '
			
			</select></td>
			<td>
			<input type="text" name="resiliation[more]" id="resiliation[more]" value="'.html($resiliation["more"]).'" maxlength="50" 
			style="display:'.((
				$resiliation["motif"]=="1" || 
				$resiliation["motif"]=="2" ||
				$resiliation["motif"]=="50" ||
				$resiliation["motif"]=="51" ||
				$resiliation["motif"]=="10" || 
				$resiliation["motif"]=="11" || 
				$resiliation["motif"]=="30")
					?"inline":"none").';">
			</td>
		</tr>';
		}
		
	elseif (!$avenant) {
		if ($prime_paye!='0000-00-00 00:00:00') $disabled='DISABLED';
		else $disabled='';
		echo '
		
		<tr>
			<td align="right" valign="top" bgcolor="'.$color_left.'"><b>Apporté</b></td>
			<td bgcolor="'.$color_right.'">
			<select name="devis" id="devis" onchange="display_devis(options[this.selectedIndex].value)" '.$disabled.'>
				<option value="0">Non
				<option value="1" '.(($id_apporteur!=0)?"SELECTED":"").'>Oui
				</select><br />
				<div id="devis_div" name="devis_div" style="display:'.(($id_apporteur!=0)?"inline":"none").';">
				<br />
				
				<table>
				<tr>
					<td align="right">Apporteur</td>
					<td><select '.$disabled.' name="id_apporteur" onchange="document.getElementById(\'i_select_devis\').src=\'iframes.php?req=select_devis_apporteurs&disabled='.$disabled.'&idd='.$id_devis.'&id=\'+this.options[this.selectedIndex].value">
					<option value="">Sélectionnez...
					';
				
				$result=mysql_query("SELECT id, nom, prenom, type FROM utilisateurs WHERE type=3 ORDER BY type DESC", $link);
				while ($row=mysql_fetch_array($result)){
					echo '<option value="'.$row["id"].'" '.(($id_apporteur==$row["id"])?"SELECTED":"").'>['.$USERS["type"][$row["type"]]."] ".strtoupper($row["nom"])." ".ucwords($row["prenom"]);
					}
				
				echo '</select></td>
				</tr>
				<tr>
				<td align="right">Devis</td>
				<td height="20">
				<div id="id_devis_div"></div>
				<iframe '.$disabled.' id="i_select_devis" name="i_select_pieces" frameborder="0" scrolling="no" height="0" width="0" src="iframes.php?req=select_devis_apporteurs&disabled='.$disabled.'&idd='.$id_devis.'&id='.$id_apporteur.'"></iframe>
				</td></tr>
				<tr>
					<td align="right">Commission</td>
					<td><input '.$disabled.' type="text" name="prime" size="5" maxlength="20" value="'.$prime.'">€</td>
				</tr>
				</table>
			
			
			
			
			
			
			
				</div>
				<script>
				function display_devis(obj){
					devis_div_obj=document.getElementById("devis_div");
					if (obj=="1") devis_div_obj.style.display="inline";
					else devis_div_obj.style.display="none";
					
					}
				</script>
			</td>
		</tr>
		<tr>
			<td align="right" bgcolor="'.$color_left.'"><b>Lieu de souscription</b></td>
			<td bgcolor="'.$color_right.'"><select name="souscription_lieu">';
			
			foreach ($CONTRATS["souscription_lieu"] as $key=>$value)
				echo '<option value="'.$key.'" '.(($souscription_lieu==$key)?"SELECTED":"").'>'.ucwords($value);
			
			echo '</select></td>
		</tr>
		<tr>
			<td align="right" bgcolor="'.$color_left.'"><b>Origine de la souscription</b></td>
			<td bgcolor="'.$color_right.'"><select name="souscription_origine">';
			
			foreach ($CONTRATS["souscription_origine"] as $key=>$value)
				echo '<option value="'.$key.'" '.(($souscription_origine==$key)?"SELECTED":"").'>'.ucwords($value);
				
			echo '</select></td>
		</tr>
		';
		}
		
		
		
	echo '
	<tr>
		<td valign="top" align="right" bgcolor="'.$color_left.'"><b>Commentaires</b></td>
		<td bgcolor="'.$color_right.'"><textarea name="information" cols="49" rows="6" style="overflow:auto;">'.$information.'</textarea></td>
	</tr>
	<tr>
		<td align="right" bgcolor="'.$color_left.'"><b>Trait&eacute; par</b></td>
		<td bgcolor="'.$color_right.'"><select name="id_utilisateur">';
		
		
	if ($id=='' && $id_axa==''){	
		$result=mysql_query("SELECT id, nom, prenom, type FROM utilisateurs WHERE type<=2 and actif=1 ORDER BY type DESC", $link);
			}
		else
		{	
		$result=mysql_query("SELECT id, nom, prenom, type FROM utilisateurs WHERE type<=2 ORDER BY type DESC", $link);
			}
		
		
		while ($row=mysql_fetch_array($result)){
			echo '<option value="'.$row["id"].'" '.(($id_utilisateur==$row["id"])?"SELECTED":"").'>'.ucwords($row["prenom"])." ".strtoupper($row["nom"]);
			}
		
		echo '</select></td>
	</tr>
	
	<tr>
		<td bgcolor="'.$color_left.'" align="right">';
		if ($id_contrat=="0" or $id=="") echo '<b>Scan</b></td>
		<td bgcolor="'.$color_right.'">';
		echo '<input type="hidden" name="scan" value="0">';
		if ($id_contrat=="0" or $id=="")
		echo '<input type="checkbox" name="scan" value="1" '.(($scan=="1")?"CHECKED":"").'>';
		echo '</td>
	</tr>
	
	</table>
	
	</td></tr>
    <tr>
	<td align="center"><br/>
	<input type="hidden" name="req" value="save">
	<input type="hidden" name="id" value="'.$id.'">
	<input type="hidden" name="id_contrat" value="'.$id_contrat.'">
	<input type="submit" value="Enregistrer"><br/><br/></td></tr>
	</form></table>
	';
	}



function contrat_save() {
    global $link, $GLOBAL_TITRE;
	

	foreach ($_POST as $key=>$value) {
		if (is_array($value)) {
			foreach ($value as $akey=>$avalue) {
				if (!is_array($avalue)) $_POST[$key][$akey]=var_post_post($avalue);
				else $_POST[$key][$akey]=$avalue;
				}
			}
		else $_POST[$key]=var_post_post($value);
		}
		
	$_POST["date_souscription"]=date_txt2sql($_POST["date_souscription"]);
	$_POST["date_effet_debut"]=date_txt2sql($_POST["date_effet_debut"]);
	if (isset($_POST["date_effet_fin"])) $_POST["date_effet_fin"]=date_txt2sql($_POST["date_effet_fin"]);
	$_POST["date_echeance"]=date_txt2sql($_POST["date_echeance"]);
	
	$error=0;
	echo '<center><br />';	
	
	if (isset($_POST["id_axa"]) && $_POST["id_axa"]=="") {
        $error=1;
        echo '<b>Le champ identifiant doit être saisi !</b><br><br>';
    	}

	if (isset($_POST["devis"])){
		if ($_POST["devis"]=="0") {
			$_POST["id_apporteur"]=0;
			$_POST["id_devis"]=0;
			$_POST["prime"]=0;
			}
		}
	if (isset($_POST["id_axa"])) {
		$sql="SELECT id FROM contrats WHERE id_axa='".mysql_escape_string($_POST["id_axa"])."'";
		$test_res=mysql_query($sql, $link);
		if (mysql_num_rows($test_res)!=0){
			$test_id=mysql_result($test_res, 0, "id");
			if ($_POST["id"]!=""){
				if ($test_id!=$_POST["id"]) {
					$error=1;
					echo 'Ce contrat est déjà inscrit !';
					}
				}
			else {
				$error=1;
				echo 'Ce contrat est déjà inscrit !';
				}
			}
		}

	if (contrat_is_resilie($_POST["id_contrat"]) && isset($_POST["resiliation"]) && $_POST["id"]==""){
		$error=1;
		echo 'Ce contrat a déjà été résilié.';
		}
			
	if ($error!=1){
	 	$sql_more="";
		
		
		foreach ($_POST as $key=>$value){
			if ($key!="req" && $key!="id" && $key!="id_avenant" && $key!="id_client_axa" && $key!="resiliation" && substr($key, 0, 5)!="devis" && substr($key, 0, 6)!="pieces") 
				$sql_more.=",".$key."='".$value."'";
			}
		
		
		if ($_POST["id"]=="") {
			$sql_action="INSERT INTO";
			$sql_more="date_add=NOW(), id_utilisateur_add='".$_SESSION["SS_user_id"]."' ".$sql_more;
			}
		else {
			$sql_action="UPDATE";
			$sql_more="date_mod=NOW(), id_utilisateur_mod='".$_SESSION["SS_user_id"]."' ".$sql_more." WHERE id='".$_POST["id"]."'";
			}
		
		
		$sql=$sql_action." contrats SET ".$sql_more;
		mysql_query($sql, $link);
		if ($_POST["id"]=="") $_POST["id"]=mysql_insert_id();
		
		
		mysql_query("DELETE FROM contrats_pieces WHERE id_contrat='".$_POST["id"]."'", $link);
		if (isset($_POST["pieces"]["id"])) {
			foreach($_POST["pieces"]["id"] as $value){
				mysql_query("INSERT INTO contrats_pieces set id_contrat='".$_POST["id"]."', id_piece='".$value."', fournie='".((isset($_POST["pieces"]["checked"][$value]))?"1":"0")."'", $link);
				}
			}
			
		if ($_POST["id_contrat"]=="0") $_POST["id_contrat"]=$_POST["id"];
		
		contrat_incomplet_set($_POST["id"]);
		contrat_resiliation_set($_POST["id"], ((isset($_POST["resiliation"])?$_POST["resiliation"]:"")) );
		
		echo '<br><font class="normal">Merci !</font><br>
		<font class="normal">Les informations ont été enregistrées !
		<br><font class="normal">La <a class="normal" href="contrat.php?req=mod&id='.$_POST["id"].'">fiche'.((isset($_POST["id_axa"]))?" ".$_POST["id_axa"]:"").'</a> est à jour</font>
		<br /><br />
		<font class="normal"><a class="normal" href="contrat.php?req=liste&id_axa='.(($_POST["id_contrat"]=="0")?$_POST["id_axa"]:contrat_id_axa($_POST["id_contrat"])).'">Retour au contrat</a></font><br>
		<font class="normal"><a class="normal" href="contrat.php?req=liste">Retour à la liste complète</a></font><br>
		</center><br />';
		$GLOBAL_TITRE.="Enregistrement #".(($_POST["id_contrat"]=="0")?$_POST["id_axa"]:"").' effectué';
		}
	else echo '<br/><br /><input type="button" onClick="history.go(-1)" value="Retour"></center>';
	}


	
function contrat_liste($id_axa="", $id_client_axa="", $page=0) {
    global $link, $GLOBAL_TITRE;
	$GLOBAL_TITRE.="Liste";
	$per_page=20;
	$start=$page*$per_page;
	
	$piece[0]='<font color="red"><big><b>&bull;</b></big></font>';
	$piece[1]='<font color="#AED536"><big><b>&bull;</b></big></font>';
	
	
	
	$res=mysql_query("SELECT id, date_effet_fin FROM contrats WHERE id_contrat='0' AND date_effet_fin<NOW() AND date_effet_fin!='0000-00-00' AND resilie='0'", $link);
	while ($row=mysql_fetch_array($res)){
		mysql_query("INSERT INTO contrats SET 
						date_add=NOW(), 
						date_effet_debut='".sn($row["date_effet_fin"])."', 
						date_souscription='".sn($row["date_effet_fin"])."', 
						montant='0',
						id_contrat='".sn($row["id"])."' ", $link);
		$id_tmp=mysql_insert_id();
		$res_tmp["motif"]="40";//contrat temporaire
		contrat_resiliation_init($res_tmp);
		contrat_resiliation_set($id_tmp, $res_tmp);
		}	
	
	
	
	
	$sql_more="";
	$show_incomplet=true;
	$show_resilie=false;
	if ($id_axa!="") $sql_more.=" AND id_axa='".$id_axa."'";
	if ($id_client_axa!="") $sql_more.=" AND id_client='".client_id($id_client_axa)."'";
	if (isset($_GET["incomplet"]) ) {
		if ($_GET["incomplet"]=="1"){
			$sql_more.=" AND incomplet_global='1' AND resilie='0'";
			$show_incomplet=true;
			}
		else $show_incomplet=false;
		}
	if (isset($_GET["resilie"])) {
		if ($_GET["resilie"]=="1"){
			$sql_more.=" AND resilie='1'";
			$show_incomplet=false;
			$show_resilie=true;
			}
		else $show_resilie=false;}

	
	
		
	echo '<center>
	<table border="0" cellpadding="3" cellspacing="1" bgcolor="#eeeeee" width="100%">

	<tr class="white">
	<td bgcolor="#000000"></td>
	<td bgcolor="#000000" width="100"><b>Contrat</b></td>	
	<td bgcolor="#000000" align="center"><b>Type</b></td>
	<td bgcolor="#000000"><b>Client</b></td>
	<td bgcolor="#000000" align="center" width="36"><b>Pièces</b></td>
	<td bgcolor="#000000" align="center" width="60"><b>Montant</b></td>
	<td bgcolor="#000000" align="center" width="25"><b>Scan</b></td>
	<td bgcolor="#000000" align="center" width="71"><b>Date d\'ajout</b></td>
	<td bgcolor="#000000" align="center" width="88"><b>Actions</b></td>
	</tr>';

	
	$nb_res=mysql_result(mysql_query("SELECT count(id) FROM contrats WHERE id_contrat='0'".$sql_more, $link),0);
	
	
	
	
	
	
	$query="SELECT id, id_axa, id_client, date_add, date_effet_debut, date_echeance, montant, relance, id_type, resilie ,scan FROM contrats 
		WHERE id_contrat='0'".$sql_more." ORDER BY date_last ASC LIMIT ".$start.", ".$per_page."";
	$result=mysql_query($query, $link);
	while ($row=mysql_fetch_array($result)){
		$bgcolor="#FFFFFF";
		$id=$row['id'];	
		$id_axa=$row['id_axa'];
		$id_client=$row['id_client'];
		$id_type=$row['id_type'];
		$relance=$row["relance"];
		$resilie_all=$row["resilie"];
		if ($relance=="") $relance=array();
		else $relance=unserialize($relance);
		$relance_num=relance_get_max($relance);
		if (isset($relance[0])) $relance_num++;
		if ($relance_num>3) {
				$tmp=dateshort($relance[3]);
				$date_tmp=explode("/", $tmp);
				if ((mktime(0, 0, 0, $date_tmp[0], $date_tmp[1], $date_tmp[2])+24*3600*15)<mktime() && !$resilie_all){
					$bgcolor="#FFEEEE";
					}
				$relance_num=3;
				}
	
		$montant=$row['montant'];
		$montant2=$montant;
		$date_add=dateshort($row['date_add']);
		$date_effet=dateshort($row['date_effet_debut']);
		$date_echeance=dateshort($row['date_echeance']);
		$date_echeance2=$date_echeance;
		$scan=$row["scan"];
		if($scan==0){
			$img ="../images/case_vide.png";
			}else{
			$img ="../images/check_vert.png";}
	
			
		
		$result2=mysql_query("SELECT nom, prenom, id_axa FROM clients WHERE id='".$id_client."'", $link);
		while ($row2=mysql_fetch_array($result2)){
			$nom=strtoupper($row2["nom"]);
			$prenom=ucwords($row2["prenom"]);
			$client_id_axa=$row2["id_axa"];
			}
		if (mysql_num_rows(mysql_query("SELECT id_contrat FROM contrats_pieces WHERE id_contrat='".$id."' AND fournie='0'"))==0){
			$relance_num=0;
			$ok=true;
			}
		else $ok=false;
		$bad_all=true;
		
		

		
		
		$return_me="";
		$return_me_resiliation="";
		$resiliation="";
		$result2=mysql_query("SELECT id, id_axa, resiliation, date_add, date_effet_debut, date_echeance, montant, scan, relance FROM contrats WHERE id_contrat='$id' ORDER BY date_effet_debut", $link);
		$i=1;
		
		
		$a_resilier=false;
		if (mysql_num_rows($result2)==0) $ok_all=$ok;
		$bgcolor2="#f8f8f8";
		while ($row2=mysql_fetch_array($result2)){
			$id2=$row2["id"];
			$id_axa2=$row2["id_axa"];
			$montant2=$row2['montant'];
			$resiliation=$row2['resiliation'];
			$relance2=$row2["relance"];
			$scan=$row2["scan"];
			if($scan==0){
			$img2 ="../images/puce_carre_rouge.gif";
			}else{
			$img2 ="../images/puce_carre_verte.gif";}
			if ($relance2=="") $relance2=array();
			else $relance2=unserialize($relance2);
			$relance_num2=relance_get_max($relance2);
			if (isset($relance2[0])) $relance_num2++;
			if ($resiliation!="") {
				$resilie=true;
				$resiliation=unserialize($resiliation);
				}
			else $resilie=false;
			if ($resilie) {
				$return_me_var="return_me_resiliation";
				$j=$i;
				$i=mysql_num_rows($result2);
				}
			else {
				$return_me_var="return_me";
				$j=$i;
				}
			if ($relance_num2>3) {
				$tmp=dateshort($relance2[3]);
				$date_tmp=explode("/", $tmp);
				if ((mktime(0, 0, 0, $date_tmp[0], $date_tmp[1], $date_tmp[2])+24*3600*15)<mktime() && !$resilie_all){
					$bgcolor2="#FFEEEE";
					//$bgcolor="#FFEEEE";
					}
				$relance_num2=3;
				}
				
			$date_add2=dateshort($row2['date_add']);
			$date_effet2=dateshort($row2['date_effet_debut']);
			$date_echeance2=dateshort($row2['date_echeance']);
			if (mysql_num_rows(mysql_query("SELECT id_contrat FROM contrats_pieces WHERE id_contrat='".$id2."' AND fournie='0'"))>0){
				$ok2=false;
				$ok_all=false;
				}
			else {
				$bad_all=false;
				$ok2=true;
				$relance_num2=0;
				}
			
			
				
			$id_axa2=(($i<10)?"00":"0").$i;
			$id_axa2_long=$id_axa." ".(($i<10)?"00":"0").$i;
			
				
			
			${$return_me_var}.='<tr id="avenant_'.$id.'_'.$i.'" style="display:'.(($ok2)?"none":"inline").';">
			<td bgcolor="#ffffff" align="center" width="1"></td>
			<td bgcolor="'.$bgcolor2.'">&nbsp;<a href="contrat.php?req=mod&id='.$id2.'"><img src="../images/admin/'.(($resilie)?"resiliation":"avenant").'.gif" style="margin-right:3px;" align="absmiddle" border="0">'.$id_axa2.'</a></td>
			<td bgcolor="'.$bgcolor2.'" align="center"></td>
			<td bgcolor="'.$bgcolor2.'" align="center"></td>
			<td bgcolor="'.$bgcolor2.'" align="center">'.$piece[$ok2].'</td>
			<td bgcolor="'.$bgcolor2.'" align="center">'.$montant2.(($montant2!="")?"€":"").'</td>
			<td bgcolor="'.$bgcolor2.'" align="center"></td>
			<td bgcolor="'.$bgcolor2.'" align="center">'.$date_add2.'</td>
			<td bgcolor="'.$bgcolor2.'" align="right">
			<table border="0" cellpadding="0" cellspacing="0"><tr>';
				if (!$resilie_all || $resilie)
				${$return_me_var}.='<td width="18" align="center"><img onclick="window.open(\'print.php?id='.$id2.'&idr='.$relance_num2.'\', \'relance'.$id2.'\', \'toolbars=no, resizable=yes, scrollbars=yes\');" 
				style="cursor:pointer; cursor:hand;" src="../images/admin/relance_'.$relance_num2.'.gif" border="0" alt="Imprimer l'.(($relance_num2==0)?"e contrat":"a relance #".$relance_num2).'"></a></td>';
				
				${$return_me_var}.='
				<td width="18" align="center"><a title="Modifier" href="contrat.php?req=mod&id='.$id2.'"><img src="../images/admin/mod.gif" border="0"></a></td>
				<td width="16" align="right"><a title="Supprimer" href="#" onclick="if(window.confirm(\'Etes vous sûr de vouloir supprimer l\\\'avenant #'.$id_axa2_long.' ?\')) location.href=\'contrat.php?req=del&id='.$id2.'\'; else return false;"><img src="../images/admin/del.gif" border="0"></a></td>
			</tr></table>
			</td>
			</tr>';
			$i=$j;
			if (!$resilie) $i++;
			}
			
		
		/*if (($show_resilie==true && $resilie_all) || 
			($show_resilie==false && $show_incomplet==true && !$ok_all && !$resilie) ||
			($show_resilie==false && $show_incomplet==false)
			){
			$nb_res++;*/
		echo '<tr>
			<td bgcolor="'.$bgcolor.'" width="14" valign="top">
			'.(($return_me!="" || $return_me_resiliation!="")?'<a href="#" onclick="avenant_show_hide('.$id.', '.(mysql_num_rows($result2)+1).');"><img id="avenant_img_'.$id.'" 
				src="../images/admin/'.((!$bad_all)?"plus":"moins").'.gif" align="absmiddle" border="0"></a>':'<div style="width:14px;display:none;"></div>').'</td>
			<td bgcolor="'.$bgcolor.'" valign="top"><table cellpadding="0" cellspacing="0" border="0" width="100%"><tr>
				<td><a href="contrat.php?req=mod&id='.$id.'"><img src="../images/admin/'.(($resilie_all)?"resilie":"contrat").'.gif" style="margin-right:3px;" align="absmiddle" border="0">'.$id_axa.'</a></td>
				<td align="right">'.((is_array($resiliation) && $resiliation["motif"]=="30")?
					'&nbsp;<a title="Ce contrat a été remplacé par le contrat #'.html($resiliation["more"]).'" href="contrat.php?req=liste&id_axa='.$resiliation["more"].'"><img src="../images/admin/link.gif" align="absmiddle" border="0"></a>':"").
				'</td>
				</tr>
				</table></td>
				
				

				<td bgcolor="'.$bgcolor.'" align="center" valign="top"><span style="font-size:9px;font-family:tahoma;">'.contrat_type_nom($id_type).'</span></td>
			<td bgcolor="'.$bgcolor.'" align="left" valign="top">
			<table cellpadding="0" cellspacing="0" border="0" width="100%"><tr>
				<td width="75" valign="top"><a title="Voir le client : '.html($nom." ".$prenom).' (#'.$client_id_axa.')" target="_blank" href="client.php?req=mod&id='.$id_client.'"><img align="absmiddle" src="../images/admin/client.gif" border="0"><span style="font-size:9px;font-family:tahoma;">'.$client_id_axa.'</span></a></td>
				<td align="left" valign="top"><span style=" font-size:9px;font-family:tahoma;">'.html($nom." ".$prenom).'</span></td>
			
				<td align="right" valign="top">'.(($id_client_axa=="")?
					'<a title="Voir tous les contrats de ce client" href="contrat.php?req=liste&id_client='.$client_id_axa.'"><img align="absmiddle" src="../images/admin/filtre.gif" border="0"></a>':"").
				'</td>
				</tr>
				</table></td>
			
			<td bgcolor="'.$bgcolor.'" align="center" valign="top"><div id="ok_all_'.$id.'" style="display:'.(($ok_all)?"inline":"none").';">'.$piece[$ok_all].'</div><div id="ok_'.$id.'" style="display:'.(($ok_all)?"none":"inline").';">'.$piece[$ok].'</div></td>
			<td bgcolor="'.$bgcolor.'" align="center" valign="top"><div id="montant_all_'.$id.'" style="display:'.(($ok_all)?"inline":"none").';">'.$montant2.(($montant2!="")?"€":"").'</div><div id="montant_'.$id.'" style="display:'.(($ok_all)?"none":"inline").';">'.$montant.(($montant!="")?"€":"").'</div></td>
			<td bgcolor="'.$bgcolor.'" align="center" valign="top"><img src='.$img.'></td>
			<td bgcolor="'.$bgcolor.'" align="center" valign="top">'.$date_add.'</td>
			<!--
			<td bgcolor="'.$bgcolor.'" align="center" valign="top"><div id="date_all_'.$id.'" style="display:'.(($ok_all)?"inline":"none").';">'.$date_echeance2.'</div><div id="date_'.$id.'" style="display:'.(($ok_all)?"none":"inline").';">'.$date_echeance.'</div></td>
			-->
			<td bgcolor="'.$bgcolor.'" align="right" valign="top">
				<table border="0" cellpadding="0" cellspacing="0"><tr>';
				if (!$resilie_all) echo '
				<td width="18" align="center"><a title="Nouvel Avenant" href="contrat.php?req=aaddone&id='.$id.'"><img src="../images/admin/avenant_new.gif" border="0"></a></td>
				<td width="18" align="center"><a title="Résilier" href="contrat.php?req=resiliation&id='.$id.'"><img src="../images/admin/resilie.gif" border="0"></a></td>
				<td width="18" align="center"><img onclick="window.open(\'print.php?id='.$id.'&idr='.$relance_num.'\', \'relance'.$id.'\', \'toolbars=no, resizable=yes, scrollbars=yes\');"
				 style="cursor:pointer; cursor:hand;" src="../images/admin/relance_'.$relance_num.'.gif" border="0" alt="Imprimer l'.(($relance_num==0)?"e contrat":"a relance #".$relance_num).'"></a></td>
				';
				
				echo '
				<td width="18" align="center"><a title="Modifier" href="contrat.php?req=mod&id='.$id.'"><img src="../images/admin/mod.gif" border="0"></a></td>
				<td width="16" align="right"><a title="Supprimer" href="#" onclick="if(window.confirm(\'Etes vous sûr de vouloir supprimer le contrat #'.$id_axa.' ?\')) location.href=\'contrat.php?req=del&id='.$id.'\'; else return false;"><img src="../images/admin/del.gif" border="0"></a></td></tr>
		</table>
		
			
			
		
					
			
					</tr>'.$return_me.$return_me_resiliation;
			//}	
		}
	
	echo '</table>
	<script>
	function avenant_show_hide(who, number){
		if (document.getElementById(\'avenant_\'+ who+ \'_1\').style.display==\'none\') show_me=true;
		else show_me=false;
		
		if(show_me) {
			document.getElementById(\'avenant_img_\'+ who).src=\'../images/admin/moins.gif\';
			document.getElementById(\'ok_all_\'+ who).style.display=\'none\';
			document.getElementById(\'ok_\'+ who).style.display=\'inline\';
			document.getElementById(\'montant_all_\'+ who).style.display=\'none\';
			document.getElementById(\'montant_\'+ who).style.display=\'inline\';
			//document.getElementById(\'date_all_\'+ who).style.display=\'none\';
			//document.getElementById(\'date_\'+ who).style.display=\'inline\';
			}
		else {
			document.getElementById(\'avenant_img_\'+ who).src=\'../images/admin/plus.gif\';
			document.getElementById(\'ok_all_\'+ who).style.display=\'inline\';
			document.getElementById(\'ok_\'+ who).style.display=\'none\';
			document.getElementById(\'montant_all_\'+ who).style.display=\'inline\';
			document.getElementById(\'montant_\'+ who).style.display=\'none\';
			//document.getElementById(\'date_all_\'+ who).style.display=\'inline\';
			//document.getElementById(\'date_\'+ who).style.display=\'none\';
			}
		for (i=1; i<number; i++){
			if (show_me) document.getElementById(\'avenant_\'+ who+ \'_\' +i).style.display=\'\';
			else document.getElementById(\'avenant_\'+ who+ \'_\' +i).style.display=\'none\';
			}
		}
	</script>
	<br />
	
	<table border="0" cellpadding="4" cellspacing="1"><tr>
	';
	
	$nb_page=ceil($nb_res/$per_page);
	$page_visu=$page+1;
	
	if ($nb_page>1){
		
		
			
		
		
		
		echo '<td align="left" width="80">';
		if ($page>0) echo '<a href="contrat.php?req=liste&id_client='.$id_client_axa.'&page='.($page-1).'&incomplet='.$show_incomplet.'&resilie='.$show_resilie.'">< Précédent</a>';
		echo '</td>';
		
		for ($i=1; $i<=$nb_page; $i++){
			if ($i<=3) echo '<td><a href="contrat.php?req=liste&id_client='.$id_client_axa.'&page='.($i-1).'&incomplet='.$show_incomplet.'&resilie='.$show_resilie.'">'.(($i==$page_visu)?"<b>".$i."</b>":$i).'</a></td>';
			elseif ($i==($page_visu-2) && $i<=($page_visu+2)) echo '<td>...</td>';
			elseif ($i>=($page_visu-2) && $i<=($page_visu+2)) 	echo '<td><a href="contrat.php?req=liste&id_client='.$id_client_axa.'&page='.($i-1).'&incomplet='.$show_incomplet.'&resilie='.$show_resilie.'">'.(($i==$page_visu)?"<b>".$i."</b>":$i).'</a></td>';
			elseif ($i==($nb_page-3))echo '<td>...</td>';
			elseif ($i>=($nb_page-3)) echo '<td><a href="contrat.php?req=liste&id_client='.$id_client_axa.'&page='.($i-1).'&incomplet='.$show_incomplet.'&resilie='.$show_resilie.'">'.(($i==$page_visu)?"<b>".$i."</b>":$i).'</a></td>';
			}
		
		echo '<td align="right" width="80">';
		if ($page_visu<$nb_page) echo '<a href="contrat.php?req=liste&id_client='.$id_client_axa.'&page='.($page+1).'&incomplet='.$show_incomplet.'&resilie='.$show_resilie.'">Suivant ></a>';
		echo '</td>';
		}
		
	echo '</tr></table>
	</center>
	';
	}
	

	
	
function contrat_del($id) {
    global $link;
	
	if (($id=="")||($id=="0")) exit();
	
	if (contrat_is_resiliation($id)) 
		mysql_query("UPDATE contrats SET resilie='0' WHERE id='".contrat_id_contrat($id)."'", $link);
	
	mysql_query("DELETE FROM contrats_pieces WHERE id_contrat='".sn($id)."'", $link);
	contrat_incomplet_set($id);		
   	mysql_query("DELETE FROM contrats WHERE id='".sn($id)."'", $link);
	mysql_query("DELETE FROM contrats WHERE id_contrat='".sn($id)."'", $link);
	
	
			
	contrat_liste();
	}

if (!isset($req)) $req="";
switch($req) {

        case "liste":
			if (!isset($id_axa)) $id_axa="";
			if (!isset($id_client)) $id_client="";
			if (!isset($page)) $page="0";
			contrat_liste($id_axa, $id_client, $page);
            break;
	
        case "aaddone":
			contrat_new_mod($id, 0, 0, 1);
            break;
			
		case "addone":
        	contrat_new_mod(0, 0, $type);
        	break;
		
		case "resiliation":
            contrat_new_mod($id, 0, 0, 2);
            break;
        
		case "mod":
			if (!isset($id)) $id="";
            if (!isset($id_axa)) $id_axa="";
            contrat_new_mod($id, $id_axa);
            break;
						
        case "save":
			contrat_save();
            break;

        case "del":
            contrat_del($id);
            break;

      default:
            contrat_liste();
            break;
	}

include ("footer.php");
	
?>