<?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="blitz_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']);		
	}		
	
	
	if (isset($_POST['datas']))
	{	

		echo $_POST['datas'];
		
		$file_open = fopen("tmp_db.csv","w+"); 
		fwrite($file_open, $_POST['datas']);
		fclose($file_open);
		
		//$_SESSION['transfert_data'] = $_POST['datas'];
		header ("Location: blitz_modification_db.php");
	}
	
function DB_to_file($filename)
{
			// sauvegarde du classement dans un fichier
	
			//$sql = "SELECT * FROM parties ORDER by date asc"; 
			$sql = "SELECT * FROM " .$_SESSION['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;
			}
	
//			if (!is_dir('path/to/directory')) {
//			mkdir('path/to/directory', 0777, true);
//			}
	
			$nom_fichier = $filename;
			chdir("backup_blitz");
											
			$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);
		
}

?>

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

<script type="text/javascript">

function call_update()
{
	 scruter();
	 setTimeout("call_update()", 1000); 
}

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 a tout reçu et le serveur est ok
				if(xhr.readyState == 4 && xhr.status == 200)
				{
					document.getElementById("message_patience").style.display='none';			
						$(function()
						{
									$( "#message_generation" ).dialog({
									modal: true,
									title: "Infos",
									buttons: {
												Ok: function()
												{
													$( this ).dialog( "close" );
													
												}
											 }
										});
						});
						
				}
			}
*/
			//xhr.open("POST","blitz_edition_partie.php",true);
			xhr.open("POST","blitz_modification_db.php",true);
			//xhr.open("POST","blitz_traitement_edition_DB.php",true);
			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>

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


</head>

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

			//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 name="inscription" method="post" action="blitz_edition_DB.php">
				<textarea style='resize:none' id='datas' name='datas' cols='50%' rows='20' ><?php echo $data;?></textarea>
				<input type="submit" name="valider" value="Enregistrer"/>
			</form>
			
			
			<!--
			<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()" /> 
			-->	
				
				
			<div id='message_patience' style="display: none">
			<img src="loader.gif" name = "image" id="image"> Traitement en cours ...
			</div> 	
			
			<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>
			
			<div id="message_expiration" style="display: none">
			<p>
			<span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 50px 0;"></span>
			La session a expiré. veuillez vous reconnecter.
			</p>
			</div>

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