<?php
			include('correlation.php');
			include('chessmaster.php');

			date_default_timezone_set('Europe/Paris');
			
			$jour = $_POST['jour'];
			$mois = $_POST['mois'];
			$annee = $_POST['annee'];
			$J1 = $_POST['J1'];
			$J2 = $_POST['J2'];
			$selection_score = $_POST['selection_score'];
			$flag_validation = false;
			
					switch ($selection_score)
			{
				case "Blanc gagne":
					$score_blanc = "1";
					$score_noir = "0";
					$flag_validation = true;
					break;
				case "Blanc perd":
					$score_blanc = "0";
					$score_noir = "1";
					$flag_validation = true;
					break;
				case "Match nul":
					$score_blanc = "0.5";
					$score_noir = "0.5";
					$flag_validation = true;
					break;
			}
			
			if($flag_validation == true)
			{
					$tab_associatif = array(); 
					$tab_associatif ['Janvier']='1';
					$tab_associatif ['Février']='2';
					$tab_associatif ['Mars']='3';
					$tab_associatif ['Avril']='4';
					$tab_associatif ['Mai']='5';
					$tab_associatif ['Juin']='6';
					$tab_associatif ['Juillet']='7';
					$tab_associatif ['Aôut']='8';
					$tab_associatif ['Septembre']='9';
					$tab_associatif ['Octobre']='10';
					$tab_associatif ['Novembre']='11';
					$tab_associatif ['Décembre']='12';
					$mois = $tab_associatif[$mois];
					
					$num_jour = intval($jour);
					$num_mois = intval($mois);
					
					if($num_jour < 10)
					{
						$jour = '0' .$jour;
					}
					
					if($num_mois < 10)
					{
						$mois = '0' .$mois;
					}
					
					$date_format = $jour ."-" .$mois ."-" .$annee; 
					
					if(check_date($date_format) == "Erreur") 
					{
						echo 2;
					}
					else
					{
						$timestamp_ajout = mktime (0, 0, 0, $mois, $jour, $annee);
						
						$donnees = array();
						$donnees[0] = $timestamp_ajout;
						$donnees[1] = $J1;
						$donnees[2] = $J2;
						$donnees[3] = $score_blanc;
						$donnees[4] = $score_noir;
						inserer_partie($donnees); 
						echo 1;
					}	

			}

/******************************************************************************************/
			
function check_date($data) 
{
			if (date('d-m-Y', strtotime($data)) == $data) 
			{
				return "OK";
			} 
			else 
			{
				return "Erreur";
			}
}

/******************************************************************************************/

function transfert_DB()
{	
		$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;
		}
		
		$retour[] = $nb_parties;
		$retour[] = $table_fichier;
		return($retour);
}

/******************************************************************************************/

function regenerer_DB($tab_global)
{	
			// joueur
			$joueur = array();
			$sql = "SELECT * FROM classement ORDER by joueur asc"; 
			$results = mysql_query($sql);
			while($row = mysql_fetch_assoc($results))
			{
				$joueur[] = $row['joueur'];
			}

			// regenerer le classement
			mysql_query('TRUNCATE TABLE classement;');
			mysql_query('TRUNCATE TABLE evolution;');
			mysql_query('TRUNCATE TABLE parties;');
			mysql_query('TRUNCATE TABLE chessmaster;');
		
			stockage_joueurs_DB($joueur);
			
			$indice =  0;	
			for ($i=0; $i < count($tab_global); $i++)
			{
				$datas = $tab_global[$i];
				list($jour, $mois, $annee) = explode('/', $datas[0]);
				$timestamp = mktime (0, 0, 0, $mois, $jour, $annee);
				$donnees[0] = $timestamp; 
				$donnees[1] = $datas[1];
				$donnees[2] = $datas[2];
				$donnees[3] = $datas[3];
				$donnees[4] = $datas[4];
				algo_elo($donnees, "nostatistique", "sql", $indice );
				$indice = $indice + 1;
				chess_master($donnees,$indice);
			}
}	

/******************************************************************************************/

function stockage_joueurs_DB($donnees)
{
			$elo = 1000;
			$nb_ligne =  count($donnees);
			
			for ($i=0; $i < $nb_ligne; $i++)
			{
				$prenom = $donnees[$i];
				$partie = 0;
				$prior = 0;
				// verifier que le joueur n'existe pas dans la database
				$sql = "select joueur from classement where joueur = '$prenom' ";
				$result = mysql_query($sql);
				if(mysql_num_rows($result)>=1)
				{
						echo "Ce joueur existe deja  :" .$prenom;
						echo "<br>";
				}
		
				else
				{
					$sql = "SELECT elo FROM elo_affectation WHERE joueur ='".$prenom."'";
					$result = mysql_query($sql);
					$row = mysql_fetch_array($result);
					$elo =  $row['elo'];
			
					$sql = " INSERT INTO classement ";
					$sql = $sql . " (joueur, elo, parties, prior, initial) VALUES ";
					$sql = $sql . " ('$prenom', '$elo','$partie','$prior', '$elo') ";
					//echo $sql;
					//echo "<br>";
					$result = mysql_query($sql);
					if (!$result)
					{ 
						echo("ERROR: " . mysql_error() . "\n$SQL\n");	
					}
				}	
			}	
}		

/******************************************************************************************/
			
function inserer_partie($donnees) 
{
			$sql = "SELECT * FROM parties";
			$results = mysql_query($sql);
			while($row = mysql_fetch_assoc($results))
			{
				$list_timestamp[] = intval($row["date"]);
			}
			
			$timestamp_ajout = $donnees[0];
			$J1 = $donnees[1] ;
			$J2 = $donnees[2];
			$score_blanc = $donnees[3];
			$score_noir = $donnees[4];
			
			// retourne le dernier timestamp
			$last_timestamp = end($list_timestamp);
			
			// il s'agit de la suite de la table : un simple ajout sans un le recalcule
			if($timestamp_ajout > $last_timestamp)
			{
						algo_elo($donnees, "nostatistique", "sql", 0);
					
						$sql = "SELECT * FROM chessmaster";
						$results = mysql_query($sql);
						$n =  mysql_num_rows($results);
						$sql = "SELECT * FROM chessmaster WHERE id = '$n' ";
						$results = mysql_query($sql);
						$row = mysql_fetch_assoc($results);
						$master = $row['gagnant'];
				
						if($J1 == $master &&  $J2 != $master)
						{
							if($score_blanc == 1)
							{
								insert_chessmaster_DB($J1, $J2, $J1, $timestamp_ajout);
							}
							if($score_blanc == 0 )
							{
								insert_chessmaster_DB($J1, $J2, $J2, $timestamp_ajout);
							}
							if($score_blanc == 0.5 && $score_noir == 0.5)
							{
								insert_chessmaster_DB($J1, $J2, $J1, $timestamp_ajout);
							}
						}	
				
						if($J1 != $master &&  $J2 == $master)
						{
							if($score_noir == 1)
							{
								insert_chessmaster_DB($J1, $J2, $J2, $timestamp_ajout);
							}
							if($score_noir == 0)
							{
								insert_chessmaster_DB($J1, $J2, $J1, $timestamp_ajout);
							}
							if($score_blanc == 0.5 && $score_noir == 0.5)
							{
								insert_chessmaster_DB($J1, $J2, $J2, $timestamp_ajout);
							}
						}	

						$retour = "simple";
			}
	
			else
			{
				// recherche si la date existe ?
				// retourne la cle si elle existe
				$test =  array_search( $timestamp_ajout , $list_timestamp); 
			
				if($test != "")
				{
					// timestamp existe...
					$array = array_count_values($list_timestamp);
					$nb_partie = $array[$timestamp_ajout];
					$index_ajout =  $test + $nb_partie - 1;
				}
			
				else
				{
					// on fait un recherche pour trouver le timestamp le plus proche
					$num= $timestamp_ajout; 
					$diff = $num;
					$min = $num;

					foreach($list_timestamp as $a)
					{
					  if( abs($a-$num)< $diff )
					  {
						  $diff=abs($a-$num);
						  $min=$a;
					  }
					}
				
					$test =  array_search( $min , $list_timestamp);
					$array = array_count_values($list_timestamp);
					$nb_partie = $array[$min];
					
					// avant 
					if($timestamp_ajout < $min)
					{
						$index_ajout =  $test - 1 ;
					}
					// apres
					if($timestamp_ajout > $min)
					{
						$index_ajout =  $test  ;
					}
				}

				// un recalcule est obligatoire
				$tmp = transfert_DB();
				$donnees[0] = date('d/m/Y', $timestamp_ajout);
				$nb_parties = $tmp[0];
				$table_fichier = $tmp[1];
				$tab1 = array();
				$tab2 = array();

				for ($i=0; $i <= $index_ajout ; $i++)
				{
					$tab1[] = $table_fichier[$i];
				}
									
				for ($i=$index_ajout + 1 ; $i < $nb_parties; $i++)
				{
					$tab2[] = $table_fichier[$i];
				}

				$table[] = $donnees;
				$tab_global = array_merge($tab1,$table, $tab2);
				regenerer_DB($tab_global);
				$retour = "complexe";
			}
			
}
?>