<?php include_once ("../inc/config.inc.php") ?>
<?php include_once ("../inc/func.inc.php") ?>
<?php include_once ("../inc/func_time.inc.php") ?>
<?php include_once ("../inc/func_date.inc.php") ?>
<?php include_once ("../inc/func_log.inc.php") ?>
<?php include ("../inc/func_txt.inc.php") ?>
<?php include_once ("../inc/fic.inc.php") ?>
<?php require_once ("../classes/xpm/smtp.php"); ?>
<?php include_once ("../inc/mail.inc.php") ?>
<?PHP
	Archivelog(@$HTTP_SESSION_VARS["code_log"]);
?>
<?php
	 	// Variables Formulaire
		$rlp_choisis = @$HTTP_SESSION_VARS["rlp_choisis"];

		$titre = strip_tags(trim(@$_POST["titre"]));
		$typdde = strip_tags(trim(@$_POST["typdde"]));

		$datecrea = datefrang(strip_tags(trim(@$_POST["datecreaf"])));
		$code = str_majuscules(strip_tags(trim(@$_POST["code"])));
		$codecli = str_majuscules(strip_tags(trim(@$_POST["codecli"])));
		if (strtolower(strip_tags(trim(@$_POST["sitep"]))) == "sitep")
			$sitep=1;
		else
		{
			// On doit au moins choisir un site...
			if ($HTTP_SESSION_VARS["scli_choisis"] <> "")
				$sitep=0;
			else
				$sitep=1;
		}
		$codeage = str_majuscules(strip_tags(trim(@$_POST["codeage"])));
		$co = str_majuscules(strip_tags(trim(@$_POST["co"])));
		$cope = str_majuscules(strip_tags(trim(@$_POST["cope"])));
		
		$row = lit_enr_per($cope);
		if (is_array($row)==TRUE)
			extract ($row);
		else
			$cope_nbj=0;
		$delai = strip_tags(trim(@$_POST["delai"]));
		$nbh = strip_tags(trim(@$_POST["nbh"])).":00";
		$nbs = heure_sec($nbh);
		$indextyph = strip_tags(trim(@$_POST["typh"]));
		if ($indextyph == "0")
			$typh = 0;
		else
			$typh = 1;

		$datedf = strip_tags(trim(@$_POST["datedf"]));
		if ($datedf <> "")
			$dated = datefrang($datedf);
		else
			$dated = $datedf;
		$dateff = strip_tags(trim(@$_POST["dateff"]));
		if ($dateff <> "")
			$datef = datefrang($dateff);
		else
			$datef = $dateff;

		$preavis = strip_tags(trim(@$_POST["preavis"]));

		// On ne peut pas avoir un préavis inférieur au maximum ("dernier délai") choisi
		if ($preavis < preavis_max())
			$preavis = preavis_max();			

		// On ne peut pas avoir un préavis supérieur au maximum ("premier délai autorisé") choisi
		if ($preavis > preavis_min())
			$preavis = preavis_min();			
		
		$matos = strip_tags(trim(@$_POST["matos"]));

		$datesigf = strip_tags(trim(@$_POST["datesig"]));
		if ($datesigf <> "")
			$datesig = datefrang($datesigf);
		else
			$datesig = "";
		$signe = strip_tags(trim(@$_POST["signe"]));

		$datefinf = strip_tags(trim(@$_POST["datefinf"]));
		if ($datefinf <> "")
			$datefin = datefrang($datefinf);
		else
			$datefin = "";
		
		if ($typdde == "add")
		{
			$renouv =0;
			$rnum = "";
		}
		else
		{
			$renouv = strip_tags(trim(@$_POST["renouv"]));
			$rnum = strip_tags(trim(@$_POST["num"]));
		}

		$pu = strip_tags(trim(@$_POST["pu"]));

		$codeuser = @$HTTP_SESSION_VARS["code_log"];

		$retourliste = TRUE;
		$enr_ok = TRUE;

		if (strip_tags(trim(@$_POST["enrimp"])) == "Enregistrer & Imprimer")
		{
			$imprim = TRUE;
			$retourliste = FALSE;
		}

		if ($typdde == "add")
		{
			if (($cope_nbj == 0) AND ($delai == ""))
				$enr_ok = FALSE;
				
			if ($enr_ok == TRUE)
			{
				$codeco = crecode("CO");
	
				// Ajout de la fiche Contrat Client
			
				$conn = mysql_connect(DBHOST, DBUSER, DBPASS);
				mysql_select_db(DBNAME);
				$rech = "INSERT INTO " .TBCOCL;
				$rech.= " (cocl_datecrea,cocl_codecrea,cocl_datemod,cocl_codemod,cocl_dateenv,cocl_daterec,cocl_code,cocl_codeco,cocl_codecope,";
				$rech.= "cocl_codeage,cocl_codecli,cocl_delai,cocl_nbs,cocl_typh,cocl_dated,cocl_datef,cocl_preavis,cocl_daterel,cocl_nivrel,";
				$rech.= "cocl_renouv,cocl_rnum,cocl_datefin,cocl_signe,cocl_soldes,cocl_matos,cocl_pvht,cocl_coderlp,cocl_sitep)";
				$rech.= " VALUES";
				$rech.= " ('$datecrea','$codeuser','$datea','$codeuser','$datea','','$codeco','$co','$cope',";
				$rech.= "'$codeage','$codecli','$delai','$nbs','$typh','$dated','$datef','$preavis','','',";
				$rech.= "'$renouv','$rnum','$datefin','','$nbs','$matos','$pu','$rlp_choisis','$sitep')";
				$rs = mysql_query($rech) or die(mysql_error());
	
				/* Vérification du type de client et MAJ si nécessaire */
				
				// MAJ de la fiche Client (pour modification du type), et passage en type 'déjà client'
				$rech2 = "UPDATE `" .TBCLI. "` SET `cli_datemod`='".$datea."', `cli_codemod`='".$codeuser."', `cli_prop`='".$codeage."', `cli_type`='2'  WHERE `cli_code` = '".$codecli."'";
				$rs2 = mysql_query($rech2) or die(mysql_error());
		
				$msg = "Contrat ".$codeco." créé.";
	
				// Balayage et activation des sites sélectionnés
				if ($HTTP_SESSION_VARS["scli_choisis"] <> "")
				{
					$tab_sites = explode("-",$HTTP_SESSION_VARS["scli_choisis"]);
					foreach ($tab_sites as $id_site)
					{
						if ($id_site <> "")
						{
							$rech = "INSERT INTO ". TBSCLIC;
							$rech.= " (sclic_datecrea,sclic_datemod,sclic_idscli,sclic_codecocl)";
							$rech.= " VALUES";
							$rech.= " ('$datecrea','$datea','$id_site','$codeco')";
							$rs = mysql_query($rech) or die(mysql_error());
						}
					}
				}
				
				mysql_close($conn);

				// Envoi d'email vers le client
				envoi_mail("Création de votre contrat","con","cre","xxx","cli",$codeco,"","",FALSE);
				// Envoi d'email vers l'agence
				if (@$HTTP_SESSION_VARS["niv_log"] <> 4)
					envoi_mail("Création de contrat","con","cre","xxx","age",$codeco,"","",FALSE);
				// Envoi d'email vers le centre de gestion
				envoi_mail("Création de contrat","con","cre","xxx","cdg",$codeco,"","",TRUE);
			}
			else
			{
				$msg = "Il faut impérativement un délai d'intervention pour cette périodicité.";
				$retourliste = FALSE;
				$imprim = FALSE;
			}
		}

		if ($typdde == "edit")
		{
			if (($cope_nbj == 0) AND ($delai == ""))
				$enr_ok = FALSE;
				
			if ($enr_ok == TRUE)
			{
				// MAJ de la fiche Contrat Client
			
				$conn = mysql_connect(DBHOST, DBUSER, DBPASS);
				mysql_select_db(DBNAME);
				$rech = "UPDATE `" .TBCOCL;
				$rech .= "` SET `cocl_datemod`='".$datea."', `cocl_codemod`='".$codeuser."', `cocl_codecope`='".$cope."', `cocl_codecli`='".$codecli."', `cocl_delai`='".$delai."', `cocl_nbs`='".$nbs."', `cocl_typh`='".$typh."',";
				$rech .=" `cocl_dated`='".$dated."', `cocl_datef`='".$datef."', `cocl_preavis`='".$preavis."', `cocl_renouv`='".$renouv."', `cocl_rnum`='".$rnum."', `cocl_datefin`='".$datefin."',";
				$rech .=" `cocl_signe`='".$signe."', `cocl_matos`='".$matos."', `cocl_pvht`='".$pu."', `cocl_coderlp`='".$rlp_choisis."', `cocl_sitep`='".$sitep."'";
				$rech .=" WHERE `cocl_code` = '".$code."'";
				$rs = mysql_query($rech) or die(mysql_error());

				/* Vérification du type de client et MAJ si nécessaire */
				
				// MAJ de la fiche Client (pour modification du type), et passage en type 'déjà client'
				$rech2 = "UPDATE `" .TBCLI. "` SET `cli_datemod`='".$datea."', `cli_codemod`='".$codeuser."', `cli_type`='2'  WHERE `cli_code` = '".$codecli."'";
				$rs2 = mysql_query($rech2) or die(mysql_error());
		

				// Mise à jour des sites sélectionnés

				// On vide d'abord tout
				$rech = "DELETE FROM `" .TBSCLIC. "` WHERE `sclic_codecocl`= '".$code."'";
				$rs = mysql_query($rech) or die(mysql_error());

				// On reconstruit si des sites ont été choisis
				if ($HTTP_SESSION_VARS["scli_choisis"] <> "")
				{
					$tab_sites = explode("-",$HTTP_SESSION_VARS["scli_choisis"]);
					foreach ($tab_sites as $id_site)
					{
						if ($id_site <> "")
						{
							$rech = "INSERT INTO ". TBSCLIC;
							$rech.= " (sclic_datecrea,sclic_datemod,sclic_idscli,sclic_codecocl)";
							$rech.= " VALUES";
							$rech.= " ('$datecrea','$datea','$id_site','$code')";
							$rs = mysql_query($rech) or die(mysql_error());
						}
					}
				}

				mysql_close($conn);
	
				if ($datefin <> "") // Si date de clôture, on prévient le client
				{
					// Envoi d'email vers le client
					envoi_mail("Clôture de votre contrat","con","clo","xxx","cli",$code,"","",FALSE);
					// Envoi d'email vers l'agence
					if (@$HTTP_SESSION_VARS["niv_log"] <> 4)
						envoi_mail("Clôture de contrat","con","clo","xxx","age",$code,"","",FALSE);
					// Envoi d'email vers le centre de gestion
					envoi_mail("Clôture de contrat","con","clo","xxx","cdg",$code,"","",TRUE);
				}
				else // Si pas de date de clôture, on le prévient simplement de la modification
				{	
					// Envoi d'email vers le client
					envoi_mail("Modification de votre contrat","con","mod","xxx","cli",$code,"","",FALSE);
					// Envoi d'email vers l'agence
					if (@$HTTP_SESSION_VARS["niv_log"] <> 4)
						envoi_mail("Modification de contrat","con","mod","xxx","age",$code,"","",FALSE);
					// Envoi d'email vers le centre de gestion
					envoi_mail("Modification de contrat","con","mod","xxx","cdg",$code,"","",TRUE);
				}
				
				$msg = "Contrat ".$code." modifié.";
			}
			else
			{
				$msg = "Il faut impérativement un délai d'intervention pour cette périodicité.";
				$retourliste = FALSE;
				$imprim = FALSE;
			}
		}

		if ($typdde == "del")
		{
			// SUPPRESSION de la fiche Contrat Client
			
			if ($datefin == "")
			{
				if (nb_cocl_in_coclh($code) == 0)
				{		
					$conn = mysql_connect(DBHOST, DBUSER, DBPASS);
					mysql_select_db(DBNAME);
					
					// Contrôle que ce contrat n'est pas un renouvellement
					$rech = "SELECT `cocl_id` FROM `". TBCOCL. "` WHERE `cocl_renouv` = 1 AND `cocl_rnum` = '".$code."'";
					$rs = mysql_query($rech) or die(mysql_error());
					if (mysql_num_rows($rs)>0)
					{
						// Oui, on supprime alors l'info de renouvellement
						while ($row = mysql_fetch_assoc($rs)) 
						{         
							$rech2 = "UPDATE `" .TBCOCL;
							$rech2 .= "` SET `cocl_datemod`='".$datea."', `cocl_codemod`='".$codeuser."', ";
							$rech2 .=" `cocl_renouv`='0', `cocl_rnum`=''";
							$rech2 .=" WHERE `cocl_id` = '".$row["cocl_id"]."'";
							$rs2 = mysql_query($rech2) or die(mysql_error());
						}
					}
					mysql_free_result($rs);

					// On supprime le contrat
					$rech = "DELETE FROM `" .TBCOCL. "` WHERE `cocl_code` = '$code'";
					$rs = mysql_query($rech) or die(mysql_error());

					// On supprime les affectations de sites
					$rech = "DELETE FROM `" .TBSCLIC. "` WHERE `sclic_codecocl`= '".$code."'";

					mysql_close($conn);
					
					$msg = "Contrat ".$code." supprimé";
				}
				else
				{
					$msg = "Le contrat ".$code." à déjà été utilisé dans une intervention.";
					$retourliste = FALSE;
					$imprim = FALSE;
				}
			}
			else
			{
				$msg = "Impossible de supprimer un contrat clôt.";
				$retourliste = FALSE;
				$imprim = FALSE;
			}
		}

?>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>SMI - ESPACE PRIVE : Fiche Contrat Client</title>

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

<!-- Feuille de style & Script pour le menu -->
<link href="../inc/menu.css" rel="stylesheet" type="text/css">
<script language="JavaScript" src="../coolmenus/coolmenus4.js"></script>

<!-- Scripts Javascript pour affichages -->
<script language="JavaScript" src="../inc/aff.js"></script>

<!-- Affichage nouvelle fenêtre pour impression -->
<script type="text/javascript">
	function lanceimp(page)
	{
	  window.open(page,'impression','width='+screen.width+' height='+screen.height);
	}
</script>

</head>
</body>

<?php 
	include_once ("entete.php"); 
?>

<p align="center"><span class="titrepage"><?PHP echo $titre ?></span></p>
<p align="center">&nbsp;</p>
<p align="center" class="annot_gras_it"><?PHP echo $msg ?></p>
<?PHP if ($retourliste == FALSE) 
{ 
	if ($imprim == TRUE)
	{
		if ($typdde == "add")
			$urlimp = "cocl_pdf.php?code=".$codeco;
		else
			$urlimp = "cocl_pdf.php?code=".$code;
?>
	<p align="center">
    <a href="javascript:;" onClick="lanceimp('<?PHP echo $urlimp; ?>');")><img src="../img/print.gif" title="Imprimer le contrat" width="22" height="22" border="0" align="absmiddle"></a> 
		<a href="javascript:;" onClick="lanceimp('<?PHP echo $urlimp; ?>');")> Imprimer le contrat </a></div>
	</p>
<?PHP
	}
?>
<br>
<br>
	<table width="100%"  border="0">
	  <tr>
		<td width="3%">&nbsp;</td>
		<td width="44%"><div align="right"><a href="cocl_lst.php?ord=DES&tri=Code"><img src="../img/liste.gif" width="33" height="34" border="0" align="absmiddle"></a> <a href="cocl_lst.php?ord=DES&tri=Code" class="annot_gras_it">Retour &agrave; la liste</a></div></td>
		<td width="7%">&nbsp;</td>
		<td width="43%"><a href="index.php"><em><img src="../img/index.gif" width="48" height="48" border="0" align="absmiddle"> </em><span class="annot_gras_it">Revenir &agrave; l'accueil</span> </a></td>
		<td width="3%">&nbsp;</td>
	  </tr>
	</table>
<?PHP 
} 
else 
{
?>
	<script type="text/javascript">
	window.setTimeout("location=('cocl_lst.php?ord=DES&tri=Code');",2000)
	</script>
	<p align="center" class="annot_std_it">Retour à la liste dans 2 secondes...</p>
<?PHP
}
?>
