<?php

	session_start ();
	
	if (!isset($_SESSION['nom']) && !isset($_SESSION['password']))
	{  
			header("Location: login.php");   
	}
	
	header( 'content-type: text/html; charset=utf-8' );
	
	include('database.php');
	include('fonctions.php');
	DB_connexion(); 

			if(isset($_GET['verrou']) && $_GET['verrou'] == "ok")	
			{
					$annee = date('Y');
					$table = "reservation" .$annee;
			
					$date_origine = $_GET['date_origine'];
					$date_destination = $_GET['date_destination'];
					$utilisateur =	$_SESSION['nom'] . " " .$_SESSION['prenom'];
					
					//echo $date_origine ." --- " .$date_destination;
		
					$pieces_origine = explode("*", $date_origine);
					$pieces_destination = explode("*", $date_destination);
		
					$origine_jour = $pieces_origine[0];
					$origine_seance = $pieces_origine[1];
		
					$destination_jour = $pieces_destination[0];
					$destination_seance = $pieces_destination[1];
					
					$origine_seance = trim($origine_seance);
					$destination_seance = trim($destination_seance);

					$origine_jour = trim($origine_jour);
					$destination_jour = trim($destination_jour);
			
					$sql = "SELECT * FROM " .$table ." WHERE rendezvous = '$origine_jour' ";
					//echo $sql;	
					mysqli_query($connexion, "SET NAMES 'utf8'");
					$result = mysqli_query($connexion, $sql );
					if(!$result)
					{
						die('Impossible d\'exécuter la requête :' . mysql_error());
					}
					
					$datas = mysqli_fetch_assoc($result);
					echo '<pre>';
					echo "Origine";
					echo '<br>';
					print_r($datas);
					
					$normal = $datas['normal'];
					$etendu = $datas['etendu'];
					$tab_selection[1] = $datas['seance1'];
					$tab_selection[2] = $datas['seance2'];
					$tab_selection[3] = $datas['seance3'];
					$tab_selection[4] = $datas['seance4'];
					$tab_selection[5] = $datas['seance5'];
					$tab_selection[6] = $datas['seance6'];
					$tab_selection[7] = $datas['seance7'];
					$tab_selection[8] = $datas['seance8'];
					$horairedebut = $datas['horairedebut'];
					$horairefin = $datas['horairefin'];	
		
					//echo $origine_seance ."  " .$destination_seance;
					//echo '<br><br>';
					$origine_seance = codeur_horaire($origine_seance);
					//echo $origine_seance; 
					$destination_seance = codeur_horaire($destination_seance);
					//echo $destination_seance; 

// modification de la source					
		
					$indice_debut = substr($horairedebut, 5); 
					$indice_fin = substr($horairefin, 4); 
					
					if($origine_seance >= $indice_debut && $origine_seance <= $indice_fin)
					{
						if($normal > 0)
						{
							$normal = $datas['normal'] - 1;
						}
					}
					else
					{
						if($etendu > 0)
						{
							$etendu = $datas['etendu'] - 1;
						}
					}		
					
					if($origine_seance == "1")
					{
						$tab_selection[1] = "";
					}
					if($origine_seance == "2")
					{
						$tab_selection[2] = "";
					}
					if($origine_seance == "3")
					{
						$tab_selection[3] = "";
					}
					if($origine_seance == "4")
					{
						$tab_selection[4] = "";
					}
					if($origine_seance == "5")
					{
						$tab_selection[5] = "";
					}
					if($origine_seance == "6")
					{
						$tab_selection[6] = "";
					}
					if($origine_seance == "7")
					{
						$tab_selection[7] = "";
					}
					if($origine_seance == "8")
					{
						$tab_selection[8] = "";
					}
					
					mysqli_query($connexion, "SET NAMES 'utf8'");	
					$sql = "UPDATE " .$table ." SET 
												normal = '$normal' ,
												etendu = '$etendu' ,
												seance1 = '$tab_selection[1]' , 
												seance2 = '$tab_selection[2]' , 		
												seance3 = '$tab_selection[3]' ,
												seance4 = '$tab_selection[4]' , 			
												seance5 = '$tab_selection[5]' , 
												seance6 = '$tab_selection[6]' , 	
												seance7 = '$tab_selection[7]' , 	
												seance8 = '$tab_selection[8]' 
												WHERE rendezvous ='$origine_jour' ";						
	
					echo '<pre>';
					echo $sql;
						
//					$result = mysqli_query($connexion, $sql );
//					if(!$result)
//					{
//						die('Impossible d\'exécuter la requête :' . mysql_error());
//					}


// modification de la destination		
					echo '<pre>';
					$sql = "SELECT * FROM " .$table ." WHERE rendezvous = '$destination_jour' ";
					//echo $sql;	
					mysqli_query($connexion, "SET NAMES 'utf8'");
					$result = mysqli_query($connexion, $sql );
					if(!$result)
					{
						die('Impossible d\'exécuter la requête :' . mysql_error());
					}
					
					$datas = mysqli_fetch_assoc($result);
					
					$normal = $datas['normal'];
					$etendu = $datas['etendu'];
					$tab_selection[1] = $datas['seance1'];
					$tab_selection[2] = $datas['seance2'];
					$tab_selection[3] = $datas['seance3'];
					$tab_selection[4] = $datas['seance4'];
					$tab_selection[5] = $datas['seance5'];
					$tab_selection[6] = $datas['seance6'];
					$tab_selection[7] = $datas['seance7'];
					$tab_selection[8] = $datas['seance8'];
					$horairedebut = $datas['horairedebut'];
					$horairefin = $datas['horairefin'];		
			
					if($destination_seance == "1")
					{
						$tab_selection[1] = $utilisateur;
					}
					if($destination_seance == "2")
					{
						$tab_selection[2] = $utilisateur;
					}
					if($destination_seance == "3")
					{
						$tab_selection[3] = $utilisateur;
					}
					if($destination_seance == "4")
					{
						$tab_selection[4] = $utilisateur;
					}
					if($destination_seance == "5")
					{
						$tab_selection[5] = $utilisateur;
					}
					if($destination_seance == "6")
					{
						$tab_selection[6] = $utilisateur;
					}
					if($destination_seance == "7")
					{
						$tab_selection[7] = $utilisateur;
					}
					if($destination_seance == "8")
					{
						$tab_selection[8] = $utilisateur;
					}
		
					$indice_debut = substr($horairedebut, 5); 
					$indice_fin = substr($horairefin, 4); 
					
					if($destination_seance >= $indice_debut && $destination_seance <= $indice_fin)
					{
							$normal = $datas['normal'] + 1;
					}
					else
					{
							$etendu = $datas['etendu'] + 1;
					}		
			
					mysqli_query($connexion, "SET NAMES 'utf8'");	
					$sql = "UPDATE " .$table ." SET 
												normal = '$normal' ,
												etendu = '$etendu' ,
												seance1 = '$tab_selection[1]' , 
												seance2 = '$tab_selection[2]' , 		
												seance3 = '$tab_selection[3]' ,
												seance4 = '$tab_selection[4]' , 			
												seance5 = '$tab_selection[5]' , 
												seance6 = '$tab_selection[6]' , 	
												seance7 = '$tab_selection[7]' , 	
												seance8 = '$tab_selection[8]' 
												WHERE rendezvous ='$destination_jour' ";						
	
					echo '<pre>';
					echo $sql;
					
//					$result = mysqli_query($connexion, $sql );
//					if(!$result)
//					{
//						die('Impossible d\'exécuter la requête :' . mysql_error());
//					}
					
					
/////	mise à jour de la table gestion
					
					echo '<br><br>';
					echo "************************";
					echo '<pre>';					
					
					$sql = "SELECT * FROM gestion WHERE jour ='$origine_jour' and client ='$utilisateur' and seance = '$origine_seance' ";	
					//echo $sql;	
					mysqli_query($connexion, "SET NAMES 'utf8'");
					$result = mysqli_query($connexion, $sql );
					if(!$result)
					{
						die('Impossible d\'exécuter la requête :' . mysql_error());
					}
					
					$datas = mysqli_fetch_assoc($result);	
					
					$id = $datas['id'];
					$sql = "DELETE FROM gestion WHERE id = '$id'";
					//echo $sql;
//					$result = mysqli_query($connexion, $sql );	

					$annee = $datas['annee'];
					$mois = $datas['mois'];
					$statut = $datas['statut'];
					$cheque = $datas['cheque'];
					$banque = $datas['banque'];
					
					date_default_timezone_set('Europe/Paris');
					$jour  = date("d-m-Y");
					$heure = date("H:i:s");
					$date_inscription = $jour . " " .$heure;
					
					$sql = "INSERT INTO gestion (id,annee, mois,jour,date_inscription, client,mode,seance,compteur,montant,statut, cheque, banque ) 
							VALUES('', 
									'$annee',
									'$mois', 
									'$destination_jour',
									'$date_inscription',
									'$utilisateur',
									'actif',
									'$destination_seance',
									'0',
									'0',
									'$statut',
									'$cheque',
									'$banque'"; 		
					
					$str = "gestion";
					mysqli_query($connexion, "SET NAMES 'utf8'");	
					$sql = "INSERT INTO " .$str ."(id,annee, mois,jour, date_inscription, client,mode,seance,compteur,montant,statut, cheque, banque ) 
						VALUES('', '$annee', '$mois', '$destination_jour', '$date_inscription', '$utilisateur' ,'actif' , '$destination_seance'   ,'0','0','$statut','$cheque', '$banque')"; 
					
					echo $sql;							
//					$result = mysqli_query($connexion, $sql );	
//					if(!$result)
//					{
//						die('Impossible d\'exécuter la requête :' . mysql_error());
//					}		
					
					echo '<br><br>';
					echo "Migration du rendez-vous réussi : du $date_origine vers $date_destination";
					echo '<br><br>';
					
					//header("Location: deplacer_un_rendezvous.php");

			}
?>

<html>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<head>

	<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>

</head>

<body>

<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>
		<li class="active"><a href="deplacer_un_rendezvous_user.php"><span>Déplacer</span></a></li>
		<li><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>
	<br>
	<br>

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

function valide()
{
	var verif = true;   
	var msg_erreur = new Array();

	var val1 = document.getElementById('client').selectedIndex;	
	var val2 = document.getElementById('date_origine').selectedIndex;	
	var val3 = document.getElementById('date_destination').selectedIndex;	

	var val1 = document.getElementById('client').value;	
	var val2 = document.getElementById('date_origine').value;	
	var val3 = document.getElementById('date_destination').value;	
		
	if(val1 == "none_client" || val2 == "none_date_origine" || val3 == "none_date_nouvelle")
	{	
		msg_erreur[1] = "Element non selectionnionné !.";		
		verif = false;
	}
	
	if(verif == true)
	{
		document.getElementById('utilisateur').value= document.getElementById('client').value;
		document.getElementById('verrou').value="ok";	
	}
	if(verif == false) 
	{ 	
		var affiche = msg_erreur.join("\n"); 
		document.getElementById('verrou').value="erreur";	
		alert(affiche);
		//document.getElementById('message').innerHTML = affiche ;	
		//message.textContent = "my text";	
		//document.getElementById('message').innerHTML = "text1 <br> text2"; 
	}	
	
}

$(document).ready(function()
{
		$(".client").change(function()
		{
			
			var client = $(this).val();
			var dataString = 'client='+ client;
			//alert(dataString);

			$.ajax
			({
				type: "POST",
				url: "requete_ajax.php",
				data: dataString,
				cache: false,
				success: function(html)
				{
					$(".date_origine").html(html);
				} 
			});
		});
		
		$( "#bouton_submit" ).click(analyse_formulaire); //click  mousedown trigger('mousedown')
		
		 $("#btnOpenDialog").click(fnOpenNormalDialog);

});

function analyse_formulaire()
 {
	//event.preventDefault();
	var val2 = document.getElementById('date_origine').value;	
	var val3 = document.getElementById('date_destination').value;	
	
	if(val2 == "none_date_origine" || val3 == "none_date_nouvelle" )
	{	
		
				$("#dialog-confirm").dialog({
					//autoOpen: false,  
					resizable: false,
					modal: true,
					title: "Erreur",
					height: 250,
					width: 400,
					buttons: {
					"Fermer": function () {
							$(this).dialog('close');
							//callback(true);
						}
					}
				});
				
		var s1 = "toto";
		var s2 = "lulu";
		var s = s1 + '<br/>' +s2; 	
		var mess = "Tous les champs doivent être selectionnés !.";	
		
		//$("#dialog-confirm").html("Selection incompléte !.");
		//$("#dialog-confirm").html("You are about to delete this item. <br />It cannot be restored at a later time! Continue?");
		//$("#dialog-confirm").html(s);
		$("#dialog-confirm").html(mess);
		
		
		$( "#dialog-confirm" ).dialog( "open" );
		//$("#MyDialog").html("Confirm Dialog Box");
		// $("#MyDialog").dialog();
	
		//msg_erreur[1] = "Element non selectionnionné !.";		
		//verif = false;
		    return false;
		
	}
	else
	{
	 //$('#my_form').submit();
		alert("OK");
	 	document.getElementById('verrou').value="ok";	
		document.getElementById('utilisateur').value= document.getElementById('client').value;
		$('#form_deplacer').submit();
		
		//document.getElementById("form_deplacer").submit();
		
		/* $("form").submit(function(){
        alert("Submitted");
    });*/
		
		/* $.ajax({
                url: "deplacer_un_rendezvous_user.php",
                type: 'get',
                dataType: 'json',
                data: $("#form_deplacer").serialize(),
                success: function(data) {
                           
                         }
            });*/
	}
	
	
	
  }
function fnOpenNormalDialog()
  {
    // message que l'on souhaite affiché
	//$("#dialog-confirm").html("Confirm Dialog Box");

    // Define the Dialog and its properties.
    $("#dialog-confirm").dialog({
		//autoOpen: false,  
        resizable: false,
        modal: true,
        title: "Modal",
        height: 250,
        width: 400,
        buttons: {
            "Yes": function () {
                $(this).dialog('close');
                callback(true);
            },
                "No": function () {
                $(this).dialog('close');
                callback(false);
            }
        }
    });
	
	$( "#dialog-confirm" ).dialog( "open" );
	AutoCloseDialogBox(5000);
    return false;
}

//http://coursesweb.net/jquery/validate-submit-form

function AutoCloseDialogBox(WaitSeconds) {
            //Auto Close Dialog Box after few seconds
            setTimeout(
                function () {
                    $("#dialog-confirm").dialog("close");
                }, WaitSeconds);
        }

function callback(value) {
    if (value) {
        alert("Confirmed");
    } else {
        alert("Rejected");
    }
}

</script>
	
<?php

	echo "Déplacer un rendez-vous";
	echo "<br><br>";
	
	$annee = date('Y');
	$table = "reservation" .$annee;
	$ts_du_jour = strtotime(date("d-m-Y"));	
	
	echo 	'<form action="#" name ="form_deplacer" id ="form_deplacer" method="get">';
	echo	'<input type="hidden" name="verrou" id="verrou" value="">';
	echo 	'<input type="hidden" name="utilisateur" id="utilisateur" value="">';	
		
	echo 	'<table cellpadding="1">
			 <tr>
			 <th>Jour origine</th>	
			 <th></th>	
			 <th>Jour destination</th>
			 </tr>';	
	
	echo 	'<tr>';
	
	echo	'<td>';
			
	$utilisateur =	$_SESSION['nom'] . " " .$_SESSION['prenom'];
	$sql = "SELECT * FROM gestion WHERE annee ='$annee' AND client = '$utilisateur' and mode = 'actif' ";
	//echo $sql;
	mysqli_query($connexion, "SET NAMES 'utf8'");	
	$result = mysqli_query($connexion, $sql );
	
	if(!$result)
	{	
		die('Impossible d\'exécuter la requête :' . mysql_error());
	}
	
	$tab_jour = array();
	$tab_seance = array();	
		
	$ts_du_jour = strtotime(date("d-m-Y"));	
	
	while ($data = mysqli_fetch_assoc ($result))
	{
			$ts = strtotime($data['jour']);
		
			if($ts_du_jour < $ts)
			{
				$tab_jour[] = $data['jour'];
				$tab_seance[] = decoder_horaire($data['seance']);
			}	
	}
	
	echo '	<select id = "date_origine"  name = "date_origine" class="date_origine" size="10" STYLE="width:200">
			<option value="none_date_origine" selected="selected">--Selection--</option>';	
		
	for( $i=0; $i < count($tab_jour) ; $i++)
	{
		$infos = $tab_jour[$i] ." * " .$tab_seance[$i];
		echo '<option value="' .$infos. '">' .$infos. '</option>'; 
	}	
	echo '</select>';
	
	echo '</td>';
	//echo '<td>&nbsp;&nbsp;&nbsp;</td>';	
	echo '<td>';
	
			
//// listing des horaires libres
			
	$sql = "SELECT * FROM " .$table ." WHERE annee ='$annee' AND mode = 'actif' ";	
	mysqli_query($connexion, "SET NAMES 'utf8'");	
	$result = mysqli_query($connexion, $sql );
	
	if(!$result)
	{	
		die('Impossible d\'exécuter la requête :' . mysql_error());
	}
	
	$tab_jour = array();
	$tab_seance = array();	
	
	while ($data = mysqli_fetch_assoc ($result))
	{
		$ts = $data['ts'];
		
		if($ts_du_jour < $ts)
		{	
			if(strlen($data['seance1']) == 0 || $data['seance1'] == "creneau ouvert" )
			{
				$tab_jour[] = $data['rendezvous'];
				$tab_seance[] = "12H20";
			}
			if(strlen($data['seance2']) == 0 || $data['seance2'] == "creneau ouvert")
			{	
				$tab_jour[] = $data['rendezvous'];
				$tab_seance[] = "12H40";
			}
			if(strlen($data['seance3']) == 0 || $data['seance3'] == "creneau ouvert")
			{	
				$tab_jour[] = $data['rendezvous'];
				$tab_seance[] = "13H00";
			}
			if(strlen($data['seance4']) == 0 || $data['seance4'] == "creneau ouvert")
			{	
				$tab_jour[] = $data['rendezvous'];
				$tab_seance[] = "13H20";
			}
			if(strlen($data['seance5']) == 0 || $data['seance5'] == "creneau ouvert")
			{	
				$tab_jour[] = $data['rendezvous'];
				$tab_seance[] = "13H40";
			}
			if(strlen($data['seance6']) == 0 || $data['seance6'] == "creneau ouvert")
			{   
				$tab_jour[] = $data['rendezvous'];
				$tab_seance[] = "14H00";
			}
			if(strlen($data['seance7']) == 0 || $data['seance7'] == "creneau ouvert")
			{
				$tab_jour[] = $data['rendezvous'];
				$tab_seance[] = "14H20";
			}
			if(strlen($data['seance8']) == 0 || $data['seance8'] == "creneau ouvert")
			{	
				$tab_jour[] = $data['rendezvous'];
				$tab_seance[] = "14H40";
			}
		}	
	}	

	echo '</td>';
	echo '<td>&nbsp;&nbsp;&nbsp;</td>';	
	echo '<td>';
	
	echo '<select id = "date_destination"  name =  "date_destination" size="10" STYLE="width:300">
		  <option value="none_date_nouvelle" selected="selected">--Selection--</option>';

	for( $i=0; $i < count($tab_jour) ; $i++)
	{
		$infos = $tab_jour[$i] ." * " .$tab_seance[$i];
	 	echo '<option value="' .$infos. '">' .$infos. '</option>'; 
	}	
					
	echo '</select>';
	echo '</td>';
	echo '</tr>';
	echo '</table>';
	
	//echo '<input type="submit" name="submit" value="Enregistrer"   onclick="valide()" />';	
	//echo '<input type="submit" value="Validation" class="button" id="bouton_submit"/>';
	echo '<input type="submit" value="Déplacer" class="button" id="bouton_submit"/>';
	
	echo '</form>';		

// bloquer le bouton soumettre
//http://www.mkyong.com/jquery/how-to-disable-submit-button-after-clicked-with-jquery/
	
?>
<!--
	<input type="button" id="btnOpenDialog" value="Open Confirm Dialog" />
	<div id="MyDialog" style="display: none;">
        This is the default dialog box</div>
	
	<p id="message"></p>
-->	
	<div id="dialog-confirm"></div>
	
</body>
</html>