<?php
	session_start();
	include('database.php');
	DB_connexion(); 

	if(!isset($_SESSION['logged']) )
	{	
		header ('Location: interdiction.php');
	}
	
	if($_SESSION['logged']== "no")
	{
		header ('Location: interdiction.php');
	}
	
	header( 'content-type: text/html; charset=utf-8' );
		
	echo '<a href="admin.php">retour ...</a>  
	<br>
	<br>';
	
	if(!empty($_POST) )
	{
		$_SESSION['sauvegarde_formulaire'] = $_POST ;
     
		$page_actuelle = $_SERVER['PHP_SELF'] ;
		if(!empty($_SERVER['QUERY_STRING']))
		{
			$page_actuelle .= '?' . $_SERVER['QUERY_STRING'] ;
		}
     
		header('Location: ' . $page_actuelle);
		exit;
	}
	
	if(isset($_SESSION['sauvegarde_formulaire']))
	{
		$_POST = $_SESSION['sauvegarde_formulaire'] ;
		unset($_SESSION['sauvegarde_formulaire']);		
	}		
	
	
function DB_to_file($filename)
{
				// sauvegarde du classement dans un fichier
	
				$sql = "SELECT * FROM parties ORDER by date asc"; 
				$results = mysql_query($sql);
				$nb_parties = mysql_num_rows($results);
							
				while($row = mysql_fetch_assoc($results))
				{
					$blanc = $row['w_name'];
					$noir = $row['b_name'];
					$date = $row['date'];
					$resultat = $row['result'];
					$date_partie = date('d/m/Y', $date);
					
					if($resultat == 1)
					{
						$_score_blanc = 1;
						$_score_noir = 0;
					}
					if($resultat == 2)
					{
						$_score_blanc = 0;
						$_score_noir = 1;
					}
					if($resultat == 3)
					{
						$_score_blanc = 0.5;
						$_score_noir = 0.5;
					}
				
					$table_csv[0] = $date_partie;
					$table_csv[1] = $blanc;
					$table_csv[2] = $noir;
					$table_csv[3] = $_score_blanc;
					$table_csv[4] = $_score_noir;

					$table_fichier[] = $table_csv;
				}
	
				$nom_fichier = $filename;
				chdir("backup");
											
				$fp = fopen($nom_fichier, 'w'); 
				for ($i=0; $i < $nb_parties; $i++)
				{
					$str_comma_separated = implode(";", $table_fichier[$i]);
					fputs ($fp, $str_comma_separated);
					if($i != $nb_parties - 1)
					fputs($fp, "\n");
				}
						
				fclose($fp);
		
}


		if( isset($_POST['valide_form']) && $_POST['valide_form'] == "ok" )
		{
			echo " Job a faire ...";
			

		}
		


?>

<!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" />
<title>Edition de la database</title>

<link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>


<script type="text/javascript">

function call_update()
{
	 //ajax_routine(); 
	 scruter();
	 setTimeout("call_update()", 1000); //appelle la fonction 1 fois par  seconde
}

function scruter()
{
				var xhr = getXhr()
				// On défini ce qu'on va faire quand on aura la réponse
				xhr.onreadystatechange = function()
				{
					// On ne fait quelque chose que si on a tout reçu et que le serveur est ok
					if(xhr.readyState == 4 && xhr.status == 200)
					{
						//alert(xhr.responseText);
						retour = xhr.responseText
						
						if(retour == 0)
						{  	
		
							$(function()
							{
									$( "#message_expiration" ).dialog({
									modal: true,
									title: "Infos",
									buttons: {
												Ok: function()
												{
													$( this ).dialog( "close" );
													 document.location.href = "logout_expire.php";
												}
											 }
										});
							});
							
							
						}
	
						
						
					}
				}
					
				xhr.open("GET","session_timeout.php",true);
				xhr.send(null);
}


function getXhr()
{
    var xhr = null; 
	if(window.XMLHttpRequest) // Firefox et autres
	   xhr = new XMLHttpRequest(); 
	else if(window.ActiveXObject)
	{ // Internet Explorer 
	   try {
				xhr = new ActiveXObject("Msxml2.XMLHTTP");
		   } catch (e) 
		   {
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
		   }
	}
	else { // XMLHttpRequest non supporté par le navigateur 
			alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest..."); 
			xhr = false; 
		 } 

	return xhr;
}

function sauver()
{
	
	document.getElementById("message_patience").style.display='block';
	
	var xhr = getXhr();
				
	xhr.onreadystatechange = function()
	{
		// On ne fait quelque chose que si on a tout reçu et que le serveur est ok
		if(xhr.readyState == 4 && xhr.status == 200)
		{
			//retour = xhr.responseText;
			document.getElementById("message_patience").style.display='none';			
			//document.getElementById('message').innerHTML = retour;
				$(function()
				{
							$( "#message_generation" ).dialog({
							modal: true,
							title: "Infos",
							buttons: {
										Ok: function()
										{
											$( this ).dialog( "close" );
											
										}
									 }
								});
				});
				
		}
	}

	xhr.open("POST","traitement_edition_DB.php",true);
	// ne pas oublier ça pour le post
	xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	
	contenu = document.getElementById('datas').value;
	
	//xhr.send("J1="+J1+"&J2="+J2+"&jour="+jour+"&mois="+mois+"&annee="+annee+"&selection_date="+selection_date+"&selection_score="+selection_score);
	xhr.send("datas="+contenu);
	
	
}			

</script>

</head>

<?php
		
		$jour = date('d-m-Y');
		$heure = date("H_i_s");
		$infos = $jour.'-'.$heure;
		$filename = "sauvegarde_edition-" .$infos .".txt"; // "test.csv";

		//db-backup-12-04-2015-11_43_41.sql
		
		//$fichier = '/homez.65/analogde/www/Massage/Backup/manuel_db-backup-'.$infos.'.sql';

		DB_to_file($filename);

		$fp = fopen($filename, 'r') or die('Could not open file!');
		$data = fread($fp, filesize($filename)) or die("Could not read file!");

		echo '<h3>Liste des parties (format csv)</h3>';	
?>

<body>

		<!-- <form method="post" id="form_DB" action="edition_DB.php" > -->
		<input type="hidden" name="valide_form" id="valide_form" value="" />
		
		<textarea style='resize:none' id='datas' name='datas' cols='50%' rows='20' ><?php echo $data;?></textarea>
		
		<input id="sauve" name="sauve" type="submit" value="Enregistrer"   onclick="sauver()" /> 
		<!--</form> -->
			
		<div id='message_patience' style="display: none">
		<img src="loader.gif" name = "image" id="image"> Traitement en cours ...
		</div> 	
		 <!-- style="display: none;" -->

		
		<div id="message_generation" style="display: none">
		<p>
		<span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 50px 0;"></span>
		Modification de la database prise en compte.
		</p>
		</div>

		<script type="text/javascript">
		call_update();
		</script>		
		
</body>
</html>