<?php

		session_start ();
	
		if (!isset($_SESSION['nom']) && !isset($_SESSION['password']))
		{  
			header("Location: login.php");   
		}

		include('database.php');
		DB_connexion(); 
		//error_reporting(0);

		$val1 = "";
		$val2 = "";
		$val3 = "";
		$message = "";
			
		if(isset($_POST['verrou']) && $_POST['verrou'] == "ok")
		{		
					$ancien_mdp = $_POST['ancien_mdp']; 
					$nouveau_mdp = $_POST['nouveau_mdp'];
					$valide_mdp = $_POST['valide_mdp'];
				
					if($_SESSION['nom'] == "admin")
					{
						$client = $_POST['client']; 
						$pieces = explode(" ", $client);	
						$nom = $pieces[0]; 	
						$prenom = $pieces[1]; 	
					}
					else 
					{	$nom = $_SESSION['nom'];
						$prenom = $_SESSION['prenom'];
					}
					
					$sql = "SELECT * FROM client WHERE nom ='$nom' and prenom ='$prenom' ";	
					$result = mysqli_query($connexion, $sql );	
					$data = mysqli_fetch_assoc($result);
				
					if($ancien_mdp == $data['password'])
					{ 
						$sql="UPDATE client SET password='$nouveau_mdp' WHERE nom ='$nom' and prenom ='$prenom'";
						$result = mysqli_query($connexion, $sql );	
						$message = "ok";
						header ("Refresh: 5;URL=home.php"); 
					}
		  
					else 
					{  
						echo 'Le mot de passe actuel n\'est pas valide'; 
						echo '<br><br>'; 
					}  
				
				
	    }
	

?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="https://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/jquery.js"></script>
<script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

<title>Changement du password</title>
</head>		

<style>

.css_message {	width: 500px;
				border-style: solid;
				border-width: 1px;
				border-color: #1c75c8;
				padding: 3px; 
				background-color: #c5ddf6; 
			}

.ui-widget-overlay {
  background: #000;
}
</style>

<link rel="stylesheet" href="menu_style.css" type="text/css">

	<div id='cssmenu'>
	<ul>
		<li><a href='home.php'><span>Home</span></a></li>
		<li><a href='selection_planning_mois.php'><span>Planning</span></a></li>
		<li><a href='selection_gestion_mois.php'><span>Gestion</span></a></li>
		<li><a href='selection_statistique_mois.php'><span>Statistiques</span></a></li>
<?php
		if($_SESSION['nom'] == "admin")
		{ 	
			echo '<li><a href="deplacer_un_rendezvous_admin.php"><span>Déplacer</span></a></li>';
			echo '<li><a href="configuration.php"><span>Configuration</span></a></li>';
		}
		else
		{
			echo '<li><a href="deplacer_un_rendezvous_user.php"><span>Déplacer</span></a></li>';
		}
?>
		<li class="active"><a href='change_password.php'><span>Changer password</span></a></li>
		<li><a href='logout.php'><span>Déconnexion</span></a></li>
		<li><a href='#'><span><?php echo $_SESSION['nom'] .' ' .$_SESSION['prenom'] .' connecté' ?></span></a></li>
		<li><a href='#'><span><?php echo $_SESSION['year']; ?></span></a></li>
	</ul>
	</div>
	
<script>

function validation(chaine)
    {
    chaineValidee='';
    caracteresValides=" abcdefghijklmnopqrstuvwxyzéèàùâêûîìABCDEFGHIJKLMNOPQRSTUVWXYZ";
    // caracteresNonValides="<>&;";
    for (i=0; i<chaine.length; i++)
      {
      if (caracteresValides.indexOf(chaine.charAt(i)) != -1)
      // if (caracteresNonValides.indexOf(chaine.charAt(i)) == -1)
        {
        chaineValidee += chaine.charAt(i)
        }
      return chaineValidee;
      }
    } 

//^[a-zA-Z0-9]{3,8}$	
//var reg=new RegExp(pattern, option);
/*if (preg_match('`^([a-z0-9]+)$`i', $login)) {
// C'est ok
}
else {
// C'est pas ok
} */
/*function alphanumeric(inputtxt)  
{  
 var letterNumber = /^[0-9a-zA-Z]+$/;  
 if((inputtxt.value.match(letterNumber))   
  {  
   return true;  
  }  
else  
  {   
   alert("message");   
   return false;   
  }  
  }  */
	
function verif_alpha(mot)
{
	var alphaExp = /^[a-zA-Z0-9]+$/; 
	if(!mot.match(alphaExp))
	{ return false;
	}
	else {  return true;
		 }

}
	
	
function valider() 
{ 
		var verif = true;
		var msg_erreur = new Array;
		
		var mode = document.getElementById('mode').value;
		
		if(mode == "admin")
		{
			var list = document.getElementById("client");
			var indx = list.selectedIndex;
			alert(list);
	   
			if(indx < 0)
			{	verif = false;
				//msg_erreur[] = "Choisir un utilisateur !";
				msg_erreur.push("Choisir un utilisateur !.");
			}
		}
	   /* if(mode == "utilisateur")
		{
			$document.getElementById("utilisateur");
		}*/
	   
		var ancien_mdp = document.getElementById("ancien_mdp").value;
		var nouveau_mdp = document.getElementById("nouveau_mdp").value;
		var valide_mdp = document.getElementById("valide_mdp").value;
	 
		var caracteres = /^[0-9a-zA-Z]+$/;  
	   
		if(ancien_mdp == '' || nouveau_mdp == '' || valide_mdp == ''  )
		{	
			verif = false;
			//msg_erreur[] = "Pas de champs vide !";
			msg_erreur.push("Pas de champs vide !.");
		}
	 
		var minlength = 4;  
		var maxlength = 8;  
  
		if(nouveau_mdp.length < minlength || valide_mdp.length > maxlength)  
		{	
			verif = false;
			//msg_erreur[] = "Longueur du password insuffisante ! [4 - 8] !";
			msg_erreur.push("Longueur du password insuffisante ! [4 - 8] !.");
		}
		
		var retour1 = nouveau_mdp.match(caracteres);
		var retour2 = valide_mdp.match(caracteres);
		
		if(retour1 == null || retour2 == null)
		{
			verif = false;
			//msg_erreur[] = "Caractères non autorisés !";
			msg_erreur.push("Caractères non autorisés !.");
		}
		
		if(nouveau_mdp != valide_mdp)
		{
			verif = false;
			//msg_erreur[] = "Caractères non autorisés !";
			msg_erreur.push("Le password et sa confirmation ne sont pas identiques !.");
		}

		if(verif == true)
		{ 
			document.getElementById('verrou').value="ok";
		}
 	
		if(verif == false)
		{ 
			var affiche = msg_erreur.join("\n");
			alert(affiche);
			document.getElementById('verrou').value="erreur";
		}	
  
}


/***************************************************/

$(document).ready(function()
{
		$("#ancien_mdp").keyup(check_password);
		$('#nouveau_mdp').keyup(check_nouveau_mdp); 
		$('#valide_mdp').keyup(check_valide_mdp);
		//$('#bouton_submit').click(analyse_formulaire); 
		$('#bouton_submit').click(soumettre_formulaire); 
		
});

/***************************************************/

//http://www.mysamplecode.com/2012/05/jquery-get-input-text-value.html
function check_password()
{
		var mode = document.getElementById('mode').value;

		if(mode == "admin")
		{
			var list = document.getElementById("client");
			var indx = list.selectedIndex;
			if(indx < 0)
			{	
				$('#message_ancien_mdp').html('<img src="false.png" align="absmiddle">&nbsp;&nbsp;Il faut d\'abord chosir un utilisateur.');
				var client_check = false
			}
			else
			{	var client = list.value;
				var client_check = true
			}
		}
		if(mode == "utilisateur")
		{
			var client = document.getElementById("utilisateur").value;
			var client_check = true
		}

		if(client_check == true)	
		{
			
			var ancien_mdp = document.getElementById("ancien_mdp").value;
			var dataString = "client="+client+"&password="+ancien_mdp;
	
			$.ajax
			({
				type: "POST",
				url: "requete_password.php",
				//dataType: "json",
				//data: {client: client, password: ancien_mdp},
				data: dataString,
				cache: false,
				success: function(data)
				{
					if(data == 'yes')
					{
						$("#message_ancien_mdp").html('<img src="true.png" align="absmiddle">&nbsp;&nbsp;Identifié');
						var flag = "validation_step1";
						$('#ancien_mdp_status').val(flag);
						
					}
					if(data == 'no')
					{
						$("#message_ancien_mdp").html('<img src="false.png" align="absmiddle">&nbsp;&nbsp;Incorrect');
						
					}
					
				} 
			});
		}
   
}

/***************************************************/

function check_nouveau_mdp()
{
	
					var element = $(this).val();
					
					if(element.length == 0)
					{
						$('#message_nouveau_mdp').html('<img src="false.png" align="absmiddle">&nbsp;&nbsp;Le champ ne doit pas être vide !.');
					}
					
					else
					{
						var check_alpha = verif_alpha(element);
					
						if(check_alpha == false)
						{  
							$('#message_nouveau_mdp').html('<img src="false.png" align="absmiddle">&nbsp;&nbsp;Doit contenir uniquement des caractéres alphanumériques !.');
						}
						else
						{
					
							if(element.length <= 3)
							{	
								$('#message_nouveau_mdp').html('<img src="false.png" align="absmiddle">&nbsp;&nbsp;Trop court !.');
							}
							if(element.length > 10)
							{ 
								$('#message_nouveau_mdp').html('<img src="false.png" align="absmiddle">&nbsp;&nbsp;Trop long !.');		
							}
					
							if(element.length > 3 && element.length < 10)
							{	
								$('#message_nouveau_mdp').html('<img src="true.png" align="absmiddle">&nbsp;&nbsp;Valide .');
								var flag = "validation_step2";
								$('#nouveau_mdp_status').val(flag);
							}
						}
						
					}	
}

/***************************************************/
	
	function check_valide_mdp()
	{
					var element = $(this).val();
					
					if(element.length == 0)
					{
						$('#message_valide_mdp').html('<img src="false.png" align="absmiddle">&nbsp;&nbsp;Le champ ne doit pas être vide !.');
					}
					
					else
					{
						var check_alpha = verif_alpha(element);
					
						if(check_alpha == false)
						{ 
							$('#message_valide_mdp').html('<img src="false.png" align="absmiddle">&nbsp;&nbsp;Doit contenir uniquement des caractéres alphanumériques !.');
						}
						else
						{
					
							if(element.length <= 3)
							{	
								$('#message_valide_mdp').html('<img src="false.png" align="absmiddle">&nbsp;&nbsp;Trop court !.');
							}
							if(element.length > 10)
							{ 
								$('#message_valide_mdp').html('<img src="false.png" align="absmiddle">&nbsp;&nbsp;Trop long !.');		
							}
					
							if(element.length > 3 && element.length < 10)
							{
								$('#message_valide_mdp').html('                   ');
								
								var nouveau_mdp = document.getElementById("nouveau_mdp").value;
								var valide_mdp = document.getElementById("valide_mdp").value;

								if(nouveau_mdp != valide_mdp)
								{
									$('#message_valide_mdp').html('<img src="false.png" align="absmiddle">&nbsp;&nbsp;Non identique .');
								}
								if(nouveau_mdp == valide_mdp)
								{
									$('#message_valide_mdp').html('<img src="true.png" align="absmiddle">&nbsp;&nbsp;Identique .');
									var flag = "validation_step3";
									$('#valide_mdp_status').val(flag);
								}
							}
						}
						
					}	
	
	}

/***************************************************/

function soumettre_formulaire()
{

	var etat1 = $('#ancien_mdp_status').val();
	var etat2 = $('#nouveau_mdp_status').val();
	var etat3 = $('#valide_mdp_status').val();

	if( etat1 == "" || etat2 == "" || etat3 == "")
	{
		$("#dialog-confirm").dialog({
					//autoOpen: false,  
					resizable: false,
					modal: true,
					title: "Erreur",
					height: 250,
					width: 400,
					buttons: {
					"Fermer": function () {
							$(this).dialog('close');
							//callback(true);
						}
					}
			});
			
			
			$("#dialog-confirm").html('Il faut avoir 3 icones <img src="true.png" align="absmiddle"> pour valider le formulaire. ');
			$("#dialog-confirm" ).dialog("open");
			return false;
		
	}	
	else
	{
		document.getElementById('verrou').value="ok";
	}

}

function analyse_formulaire()
{
		var verif = true;
		var msg_erreur = new Array;
		var caracteres = /^[0-9a-zA-Z]+$/;  
		var minlength = 4;  
		var maxlength = 8;  
		var mode = document.getElementById('mode').value;
		var client_check = false;
		
		if(mode == "admin")
		{
			var list = document.getElementById("client");
			var indx = list.selectedIndex;
			if(indx < 0)
			{	verif = false;
				//msg_erreur[] = "Choisir un utilisateur !";
				msg_erreur.push("Choisir un utilisateur !.");
			}
			else
			{	var client = list.value;
				var client_check = true
			}
		}
		if(mode == "utilisateur")
		{
			var client = document.getElementById("utilisateur");
			var client_check = true
		}
	   
		var ancien_mdp = document.getElementById("ancien_mdp").value;
		var nouveau_mdp = document.getElementById("nouveau_mdp").value;
		var valide_mdp = document.getElementById("valide_mdp").value;
	   
		if(ancien_mdp == '' || nouveau_mdp == '' || valide_mdp == ''  )
		{	
			verif = false;
			//msg_erreur[] = "Pas de champs vide !";
			msg_erreur.push("Pas de champs vide !.");
		}
  
		var flag = false;
  
		if(client_check == true && ancien_mdp != '')
		{
		
			//var dataString = "client=BORDES Laurent&password=azer";
			var dataString = "client="+client+"&password="+ancien_mdp;
	
			$.ajax
			({
				type: "POST",
				url: "requete_password.php",
				//dataType: "json",
				//data: {client: client, password: ancien_mdp},
				data: dataString,
				cache: false,
				success: function(data)
				{
					
					if(data == 'no')
					{
						
						//flag = true;
						$("#add_err").html("Le password n'est pas valide");
						
					}
				} 
			});
		}
		
		/*if(flag == true)
		{	alert("Bingo");
			verif = false;
			msg_erreur.push("Faux !.");
			alert("Invalide");
		}*/
		if(nouveau_mdp.length < minlength || valide_mdp.length > maxlength)  
		{	
			verif = false;
			//msg_erreur[] = "Longueur du password insuffisante ! [4 - 8] !";
			msg_erreur.push("Longueur insuffisante ! [4 - 8] !.");
		}
		
		var retour1 = nouveau_mdp.match(caracteres);
		var retour2 = valide_mdp.match(caracteres);
		
		if(retour1 == null || retour2 == null)
		{
			verif = false;
			//msg_erreur[] = "Caractères non autorisés !";
			msg_erreur.push("Caractères non autorisés !.");
		}
		
		if(nouveau_mdp != valide_mdp)
		{
			verif = false;
			//msg_erreur[] = "Caractères non autorisés !";
			msg_erreur.push("Le password et sa confirmation ne sont pas identiques !.");
		}

		if(verif == true)
		{ 
			document.getElementById('verrou').value="ok";
			
			/*$("#dialog-confirm").dialog({
					//autoOpen: false,  
					resizable: false,
					modal: true,
					title: "Erreur",
					height: 250,
					width: 400,
					buttons: {
					"Fermer": function () {
							//$('#form_password').submit();
							$(this).dialog('close');
							//$('#form_password').valide();
							//callback();
						}
					}
			});*/
			
			//$("#dialog-confirm").html("Modification du mot de passe effectuée avec succés");
			//$( "#dialog-confirm" ).dialog("open");
			document.getElementById('texte').style.display = "block";
			//return false;
			//AutoCloseDialogBox(5000);
			//$('#form_password').submit();
			
			
		}
 	
		if(verif == false)
		{ 	
			//var s = s1 + '<br/>' +s2; 	
			//var affiche = msg_erreur.join("\n");
			document.getElementById('verrou').value="erreur";
			var mess = msg_erreur.join('<br/>');
			$("#dialog-confirm").dialog({
					//autoOpen: false,  
					resizable: false,
					modal: true,
					title: "Erreur",
					height: 250,
					width: 400,
					buttons: {
					"Fermer": function () {
							$(this).dialog('close');
							//callback(true);
						}
					}
			});
			
			$("#dialog-confirm").html(mess);
			$( "#dialog-confirm" ).dialog("open");
			return false;
		}	
	
} 

function AutoCloseDialogBox(WaitSeconds) {
            //Auto Close Dialog Box after few seconds
            setTimeout(
                function () {
                    $("#dialog-confirm").dialog("close");
                }, WaitSeconds);
        }
		
function callback()
{
/*    if (value) {
        alert("Confirmed");
    } else {
        alert("Rejected");
    }*/
}		

</script>	

<style>

p {
  margin-top: 0px;
}
 
fieldset {
  margin-bottom: 15px;
  padding: 10px;
}
 
legend {
  padding: 0px 3px;
  font-weight: bold;
  font-variant: small-caps;
}
 
label {
  width: 210px;
  display: inline-block;
  vertical-align: top;
  margin: 6px;
}
 
em {
  font-weight: bold;
  font-style: normal;
  color: #f00;
}
 
input:focus {
  background: #eaeaea;
}
 
/*input, textarea {
  width: 249px;
}*/
 
textarea {
  height: 100px;
}
 
select {
  width: 254px;
}
 
input[type=checkbox] {
  width: 10px;
}
 
input[type=submit] {
  width: 150px;
  padding: 10px;
}

</style>

</head>

<body>

	<form action="#" name ="form_password" method="post">
	<input type="hidden" name="verrou" id="verrou" value="">
	<input type="hidden" name="ancien_mdp_status" id="ancien_mdp_status" value="">
	<input type="hidden" name="nouveau_mdp_status" id="nouveau_mdp_status" value="">
	<input type="hidden" name="valide_mdp_status" id="valide_mdp_status" value="">
	
<?php

	if($_SESSION['nom'] == "admin")
	{
		echo '<input type="hidden" name="mode" id="mode" value="admin">';
	}
	else
	{	
		$utilisateur =	$_SESSION['nom'] . " " .$_SESSION['prenom'];
		echo '<input type="hidden" name="mode" id="mode" value="utilisateur">';
		echo '<input type="hidden" name="utilisateur" id="utilisateur" value="' .$utilisateur .'">';		
	}
?>	

    <br>
    <br>

  <p><i>Complétez les champs suivants afin de changé le mot de passe. Tous les champs </i><em>*</em> sont <em>obligatoires</em></p>
	<fieldset>
    <legend>Nouveau mot de passe</legend>

<?php
	
	if($_SESSION['nom'] == "admin")
	{	echo '<label for="client">Utilisateur <em>*</em></label>';
		echo '  <select size = "10" STYLE="width:300" id = "client" name="client">';
		$sql = 'SELECT * FROM client';
		mysqli_query($connexion, "SET NAMES 'utf8'");	
		$result = mysqli_query($connexion, $sql );
		$tab_nom = array();
		$tab_prenom = array();
	
		$ptr = 0;
			
		while ($data = mysqli_fetch_assoc ($result))
		{
			$tab_nom[$ptr] = $data['nom'];
			$tab_prenom[$ptr] = $data['prenom'];
			$ptr = $ptr + 1;
		}		

		for( $i=0; $i < count($tab_nom) ; $i++)
		{
			$tmp = $tab_nom[$i] . " " .$tab_prenom[$i];
			echo '<option value="' .$tmp. '">' .$tmp. '</option>'; 
		}
		
		echo '</select><br><br>';
	}	
	
	echo '<label for="ancien_mdp">Mot de passe <em>*</em></label>';
	echo '<input type="text" size="10" maxlength = "8" id = "ancien_mdp" name = "ancien_mdp" value = ' .$val1 .'>';
    echo '&nbsp;&nbsp;<span id="message_ancien_mdp"></span>';	
	echo '<br>';
	
    echo '<label for="nouveau_mdp">Nouveau mot de passe <em>*</em></label>';
	echo '<input type="text" size="10" maxlength = "8" id="nouveau_mdp" oncopy="return false;" oncut="return false;" name = "nouveau_mdp" value = ' .$val2 .'>'; //&nbsp;&nbsp; a-z A-Z 0-9 (entre 4 et 8 caractères)<br>';
	echo '&nbsp;&nbsp;<span id="message_nouveau_mdp"></span>';	
	echo '<br>';
		  
	echo '<label for="valide_mdp">Confirmation du mot de passe <em>*</em></label>';
	echo '<input type="text" size="10" maxlength = "8" onpast="return false;" id="valide_mdp" name="valide_mdp" value= ' .$val3 .'>';
	echo '&nbsp;&nbsp;<span id="message_valide_mdp"></span>';	
	echo '<br>';
		  
	echo '</fieldset>';
	
	//echo '<p><input type="submit" name="submit" value="Soummettre" onclick="valider()" >';
	
	echo '<input type="submit" value="Soummettre" class="button" id="bouton_submit" />'; // disabled="disabled"
	
?>  
    
	</form>
	<br />
	<br />

	<div id="dialog-confirm"></div>
	
<?php
				if( $message == "ok")
				{	
					echo '
							<div id="id_message" class="css_message">
							<p>
							<strong>Information</strong>: Modification du mot de passe effectuée avec succés.
							</p>
							<div>';
					$message = "none";
				}
?>

<div class="err" id="add_err"></div>


 

</body>
</html>
