<?php
	
	session_start ();
	include('database.php');
	DB_connexion(); 
	
	header( 'content-type: text/html; charset=utf-8' );
	
	//error_reporting(0);
	date_default_timezone_set('Europe/Paris');
	
	define('_PATH', dirname(__FILE__));
		
	echo '<a href="blitz_admin.php">retour ...</a>  
	<br>
	<br>';
	
	
	
	if(!isset($_SESSION['logged']) )
	{
		header ('Location: interdiction.php');
	}
	
	if($_SESSION['logged']== "no")
	{
		header ('Location: interdiction.php');
	}
	
	/*if (!isset($_SESSION['nom']) && !isset($_SESSION['password']))
	{  
			header("Location: login.php");   
	}*/

	
	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['valide_form']) && $_POST['valide_form'] == "ok" )
	{
		
		$jour = date('d-m-Y');
		$heure = date("H_i_s");
		$infos = $jour.'-'.$heure;
		//$filename = "sauvegarde_edition-" .$infos .".txt"; // "test.csv";
		$fichier = "backup_user-" .$infos .".txt"; 

		DB_to_file($fichier);
	
		echo "Backup fait";
		echo '<br>';
		echo '<br>';

	
	}
?>
	
<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;
}

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


<?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;
				}
	
				$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);
				
				header("location: blitz_backup.php");
		
}
?>
	
<style>
	
.couleur_texte
{
color: red;
}

</style>
	
<?php	

function DateCmp($a, $b) 
{
    return ($a[1] < $b[1]) ? -1 : 0;
}

function SortByDate(&$Files) 
{
    usort($Files, 'DateCmp');
}
  
function cmp($a, $b) 
{
    if ($a == $b) 
	{
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}  

function convertSize($size)
{
  $base = log($size) / log(1024);
  $suffix = array("", "KB", "MB", "GB", "TB");
  $f_base = floor($base);
  return round(pow(1024, $base - floor($base)), 1) . $suffix[$f_base];
}
	
	$dir = _PATH."/backup_blitz/";
	
	// change de repertoire
	chdir("backup_blitz");
	
	echo $dir;
	
	echo "<br/>";
	echo "<br/>";
	
	$dircontents = scandir($dir); //1
	
	$array_file = array();
	
	$cpt = 0;
	
	$files = array();
	
	$associative = array();
	
	foreach ($dircontents as $file) 
	{
		$extension = pathinfo($file, PATHINFO_EXTENSION);
		if ($extension == 'zip') 
		{
			$LastModified = filemtime($file);
			$associative[$file] = $LastModified; 
		}
	}
	
	//echo "<pre>";
	//print_r($associative);
	//echo "<pre/>";
	
	uasort($associative, 'cmp');
	
	//echo "<pre>";
	//print_r(array_reverse($associative));
	//echo "<pre/>";
		
	$reverse = array_reverse($associative);
	
	//print_r(array_keys($reverse));
	
	$liste_of_keys = array_keys($reverse);
	
	foreach($liste_of_keys as $element)
	{
		//echo $element;
		//echo "<br/>";
		//echo "<br/>";
		
		$array_file[$cpt][0] = $element;
		$array_file[$cpt][1]= filesize($element);
		$cpt = $cpt + 1;
	}
	
	//echo "<pre>";
	//print_r($array_file);
	//echo "<pre/>";
		
	$nb_fichiers = count($array_file);
	$taille = 0;
	
	for($i=0; $i < count($array_file); $i++)
	{
		$taille = $taille + $array_file[$i][1];
	}

	// convertir en fix	nt une unité	
	$size_conversion = convertSize($taille);
	
	echo "<br/>";
	echo "<br/>";
	
	echo "$nb_fichiers fichier(s) pour un espace occupé de : " .$taille  .'(octets) soit ' .$size_conversion;
	echo '<br>';	
	
		
	echo "<table border=1 cellpadding=5 cellspacing=0>";
	echo "	<tr>
			<th>Id</th>
			<th>Fichier backup</th>
			<th>Taille en octets</th>
			</tr>";

	for($i=0; $i < count($array_file); $i++)
	{
			$j = $i + 1;
			echo "<tr>
				  <td>" .$j ."</td>";	
			//echo '<td>';
			//echo '<a href="restauration.php?fichier=" .$tab_affiche[$i][0].</a>' .$tab_affiche[$i][0] .'</td>';
			echo '<td> 
				  <a href="blitz_restauration.php?fichier='.$array_file[$i][0].'" title = "Restauration">';
			echo  $array_file[$i][0];
			echo '</a>
				  </td>';
			
			
			echo "<td align = 'center'>" .$array_file[$i][1] ."</td>";
			echo '</td>
			      </tr>';
	}
	echo "</table>";
	

?>

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