<?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['submit']))
	//{ 
		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 );	
						//echo 'Modification du mot de passe effectuée avec succés'; 
						//echo '<br><br>';
						$message = "ok";
					}
		  
					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>
	</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 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()
{
		$( "#bouton_submit" ).click(analyse_formulaire); 
		
});


function analyse_formulaire()
{
/*	
		$("#dialog-confirm").dialog({
					//autoOpen: false,  
					resizable: false,
					modal: true,
					title: "Erreur",
					height: 250,
					width: 400,
					buttons: {
					"Fermer": function () {
							$(this).dialog('close');
							//callback(true);
						}
					}
		});
*/
		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;
			alert(client);
			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 dataString = 'client='+ client;
	 /*   $.ajax
		({
				type: "POST",
				url: "requete_password.php",
				data: dataString,
				cache: false,
				//success: function(html)
				success: function(responseText)
				{	if(responseText == 0)
					{
						verif = false;
						msg_erreur.push("Le mot de passe actuel est invalide !.");
					}
					//$(".date_origine").html(html);
				} 
		});*/
	   
		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 !.");
		}
  
		if(client_check == true && ancien_mdp != '')
		{
			var dataString = 'client='+client+'&password='+ancien_mdp;
			$.ajax
				({
					type: "POST",
					url: "requete_password.php",
					data: dataString,
					cache: false,
					//success: function(html)
					success: function(responseText)
					{	if(responseText == 0)
						{	
							alert("No good !);
							//verif = false;
							//msg_erreur.push("Le mot de passe actuel est 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="">
<?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>
		  <input type="text" maxlength = "8" id = "ancien_mdp" name = "ancien_mdp" value = ' .$val1 .'><br>';
    
    echo '<label for="nouveau_mdp">Nouveau mot de passe <em>*</em></label>
		  <input type="text" 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 '<label for="valide_mdp">Confirmation du mot de passe <em>*</em></label>
	      <input type="text" maxlength = "8" onpast="return false;" id="valide_mdp" name="valide_mdp" value= ' .$val3 .'><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"/>';
	
?>  
    
	</form>
	<br />
	<br />
<!--	<a href="home.php">retour ...</a>  -->

	<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 id="id_message" class="css_message">
	<p>
	<strong>Information</strong>: Modification du mot de passe effectuée avec succés.
	</p>
	<div>
-->	

</body>
</html>
