<?php

	include('database.php');
	DB_connexion(); 
	
	error_reporting(0);
	header( 'content-type: text/html; charset=utf-8' );
			

function lire_csv($nom_fichier, $separateur =";")
{
    $row = 0;
    $donnee = array();   
	$joueur = array();
	
	$file = fopen ($nom_fichier,"r");
	$ligne = 1;
	
	$table_csv = array();
	
	while(! feof($file))
	{
		// lire le fichier ligne par ligne
		$tmp = fgets($file);
		
		if($ligne > 3 )
		{
			// minuscule
			$tmp = strtolower($tmp);
			// eliminer les ; a gauche
			$tmp = ltrim($tmp, ";");
			// decomposer la chaine avec le séparateur ;
			$pieces = explode(";", $tmp);
			//suppression des valeurs inutiles
			$array = array_filter($pieces, function($var)
			{
				return (!($var == '' || is_null($var)));
			});
			// efface la derniere cellule du tableau	
			array_pop($array); 
			// conserver les lignes utiles
			if(strlen($tmp) > 2)
			{
				//$table_csv[] = $array;
				
				if(count($array) == 5)
				{
					array_push($joueur,$array[1]);
					array_push($joueur,$array[2]);
					
					$val = $array[4];
					$position = strpos($val, "5");
					if($position !== false)
					{ 
						echo " Match nul";
						echo "<br>";
						$array[3] = "0.5";
						$array[4] = "0.5";
					}
					// on stock 
					$table_csv[] = $array;
				}
				else
				{
					echo "Erreur";
				}
				
			}
					
		}
		
		$ligne = $ligne + 1;
		
	}
	
	fclose($file);

			
	$sans_doublon = array_unique($joueur);	
	//$classer = sort($sans_doublon);
	$merge = array($table_csv, $sans_doublon );
	
	//echo "<pre>";
	//print_r($merge);
	//echo "<br>";
	//echo "************************************************************";
	
	return $merge;
}

function stockage_joueurs_DB($donnees)
{
			$elo = 1000;
			$i = 0;
			$nb_ligne = count($donnees);
			
			for ($i=0; $i < $nb_ligne; $i++)
			{
				$prenom = $donnees[$i];
				$partie = 0;
				$prior = 0;
			
				$sql = " INSERT INTO classement ";
				$sql = $sql . " (joueur, elo, parties, prior) VALUES ";
				$sql = $sql . " ('$prenom', '$elo','$partie','$prior') ";
				echo $sql;
				echo "<br>";
				$result = mysql_query($sql);
				if (!$result)
				{ 
					echo("ERROR: " . mysql_error() . "\n$SQL\n");	
				}
			}	
}


function incr_games($games)
	{
		$games=$games+1;
		return $games;
	}

	function specialrating($n,$rating,$op_rating,$r_coef) 
	{
		if ($r_coef==.5) 
		{
			$r_coef=0;
		}
		elseif ($r_coef==0)
		{
			$r_coef=-1;
		}
		$newrating=($n*$rating+$op_rating+$r_coef*400)/($n+1);
		$rnewrating=round($newrating,0);
		return $rnewrating;
	}

	function standardrating($n,$rating,$op_rating,$s) 
	{
		$k=kcalculation($n,$rating);
		$e=winningexpactancy($rating,$op_rating);
	
		$newrating=$rating+$k*($s-$e);
		if ($rating<$newrating)
		{
			$roundAway=.4999;
		}
		else
		{
			$roundAway=-.4999;
		}
		$newrating=round($newrating+$roundAway,0);
		return $newrating;
	}

	function kcalculation($myGameCount, $rating)
	{
		if ($rating<2200) 
		{
			$myPriorGames=50/sqrt((1+(pow((2200-$rating),2))/100000));
		}
	
		elseif($rating>=2200) 
		{
			$myPriorGames=50;
		}
	
		if ($myPriorGames>$myGameCount)
		{
			$myPriorGames=$myGameCount;
		}

		$k=800/($myPriorGames+1);
		return $k;
	}

	function winningexpactancy($rating,$op_rating)
	{
		$we=1/(pow(10,(-($rating-$op_rating)/400))+1);
		return $we;
	}

	function incr_prior($prior)
	{
		if ($prior<50) 
		{
			$prior=$prior+1;
		}
		return $prior;
	}
	
	function incr_gcount($gcount) 
	{
		$gcount=$gcount+1;
		return $gcount;
	}

	function incr_wins($wins)
	{
		$wins=$wins+1;
		return $wins;
	}

	function incr_losses($losses)
	{
		$losses=$losses+1;
		return $losses;
	}

	function incr_draws($draws)
	{
		$draws=$draws+1;
		return $draws;
	}


function elo($donnees)
{
	$i = 0;
	$nb_ligne = count($donnees);
	for ($i=0; $i < $nb_ligne; $i++)
	{
				$timestamp_partie = $donnees[$i][0];
				$J1 = $donnees[$i][1];
				$J2 = $donnees[$i][2];
				$J1_score = $donnees[$i][3];
				$J2_score = $donnees[$i][4];
				
				echo $J1 ." " .$J2 ." " .$J1_score ." " .$J2_score;
				echo "<br>";

				$sql_w = "select * from classement where joueur = '$J1' ";
				echo $sql_w;
				echo "<br>";
				$result = mysql_query($sql_w);
				while ($data = mysql_fetch_array($result))
				{
					$w_playerID = $data['id'];
					$w_joueur = $data['joueur'];
					$w_rating = $data['elo'];
					$w_games = $data['parties'];
					$w_prior = $data['prior'];
					$w_bonus = $data['bonus'];
					$w_oldrating = $data['oldrating'];
					$w_gcount = $data['gcount'];
					$w_wins = $data['wins'];
					$w_losses = $data['losses'];
					$w_draws = $data['draws'];
				}	
				
				echo $w_playerID ." " 
					 .$w_joueur ." " 
					 .$w_rating ." " 
				  	 .$w_games ." " 
					 .$w_prior ." " 
					 .$w_bonus ." " 
					 .$w_oldrating ." " 
					 .$w_gcount ." " 
					 .$w_wins  ." " 
					 .$w_losses  ." " 
					 .$w_draws ." " ;
				echo "<br>";
				
				$sql_b = "select * from classement where joueur = '$J2' ";
				echo $sql_b;
				echo "<br>";
				$result = mysql_query($sql_b);
				while ($data = mysql_fetch_array($result))
				{
					$b_playerID = $data['id'];
					$b_joueur = $data['joueur'];
					$b_rating = $data['elo'];
					$b_games = $data['parties'];
					$b_prior = $data['prior'];
					$b_bonus = $data['bonus'];
					$b_oldrating = $data['oldrating'];
					$b_gcount = $data['gcount'];
					$b_wins = $data['wins'];
					$b_losses = $data['losses'];
					$b_draws = $data['draws'];
				}	

				echo $b_playerID ." " 
					 .$b_joueur ." " 
					 .$b_rating ." " 
				  	 .$b_games ." " 
					 .$b_prior ." " 
					 .$b_bonus ." " 
					 .$b_oldrating ." " 
					 .$b_gcount ." " 
					 .$b_wins  ." " 
					 .$b_losses  ." " 
					 .$b_draws ." " ;
				echo "<br>";

				
				if($J1_score==1) 
				{
					if($w_prior<=8) 
					{
						$new_w_rating=specialrating($w_prior,$w_rating,$b_rating,1);
					}
					if($w_prior>8)
					{
						$new_w_rating=standardrating($w_prior,$w_rating,$b_rating,1);
					}
					if($b_prior<=8)
					{
						$new_b_rating=specialrating($b_prior,$b_rating,$w_rating,0);
					}
					if($b_prior>8)
					{
						$new_b_rating=standardrating($b_prior,$b_rating,$w_rating,0);
					}
				}
				
				if(  $J1_score == "0.5" && $J2_score == "0.5"  ) 
				{
					if($w_prior<=8)
					{
						$new_w_rating=specialrating($w_prior,$w_rating,$b_rating,.5);
					}
					if($w_prior>8) 
					{
						$new_w_rating=standardrating($w_prior,$w_rating,$b_rating,.5);
					}
					if($b_prior<=8) 
					{
						$new_b_rating=specialrating($b_prior,$b_rating,$w_rating,.5);
					}
					if($b_prior>8) 
					{
						$new_b_rating=standardrating($b_prior,$b_rating,$w_rating,.5);
					}
				}
				
				if ($J2_score==1) 
				{
					if($w_prior<=8)
					{
						$new_w_rating=specialrating($w_prior,$w_rating,$b_rating,0);
					}
					if($w_prior>8)
					{
						$new_w_rating=standardrating($w_prior,$w_rating,$b_rating,0);
					}
					if($b_prior<=8) 
					{
						$new_b_rating=specialrating($b_prior,$b_rating,$w_rating,1);
					}
					if($b_prior>8)
					{
						$new_b_rating=standardrating($b_prior,$b_rating,$w_rating,1);
					}
				}
				
				
				if($J1_score==1)
				{
					$w_wins=incr_wins($w_wins);
					$b_losses=incr_losses($b_losses);
					$partie_result = 1;
				}
				
				if($J1_score == 0.5 && $J2_score == 0.5) 
				{
					$w_draws=incr_draws($w_draws);
					$b_draws=incr_draws($b_draws);
					$partie_result = 3;
				}
				
				if($J2_score==1) 
				{
					$w_losses=incr_losses($w_losses);
					$b_wins=incr_wins($b_wins);
					$partie_result = 2;
				}

				$b_gcount=incr_gcount($b_gcount);
				$w_gcount=incr_gcount($w_gcount);
				$w_prior=incr_prior($w_prior);
				$b_prior=incr_prior($b_prior);
				$w_games=incr_games($w_games);
				$b_games=incr_games($b_games);
				
				$sql_w="UPDATE classement SET `elo`=$new_w_rating, `parties`=$w_games,`prior`=$w_prior,
				`oldrating`=$w_rating,`gcount`=$w_gcount,`wins`=$w_wins,`losses`=$w_losses,`draws`=$w_draws
				WHERE `joueur`= '$J1' ";

				$sql_b="UPDATE classement SET `elo`=$new_b_rating, `parties`=$b_games,`prior`=$b_prior,
				`oldrating`=$b_rating,`gcount`=$b_gcount,`wins`=$b_wins,`losses`=$b_losses,`draws`=$b_draws
				WHERE `joueur`= '$J2' "; 
	
				echo $sql_w;
				echo "<br>";
				echo $sql_b;
				echo "<br>";
				
				//	$today=time();
				
				$result1 = mysql_query($sql_w);
				$result2 = mysql_query($sql_b);
				
								
				$sql_w="INSERT INTO `evolution` (playerID,rating,date) VALUES ($w_playerID,$new_w_rating,'$timestamp_partie')";
				$sql_b="INSERT INTO `evolution` (playerID,rating,date) VALUES ($b_playerID,$new_b_rating,'$timestamp_partie')";

				
				echo $sql_w;
				echo "<br>";
				echo $sql_b;
				echo "<br>";
				$result3 = mysql_query($sql_w);
				$result4 = mysql_query($sql_b);
				
				$sql="INSERT INTO parties (w_playerID,w_name,b_playerID,b_name,w_brating,w_arating,b_brating,b_arating,result,date) 
				VALUES ($w_playerID,'$w_joueur',$b_playerID,'$b_joueur',$w_rating,$new_w_rating,$b_rating,$new_b_rating,$partie_result,'$timestamp_partie')";
				
				$result5 = mysql_query($sql);

				if (!$result1 || !$result2 || !$result3 || !$result4 || !$result5) 
				{
					echo "Failed!";
				}
		
		
	} /*for*/
	
}	


function traitement_dates($liste_parties)
{

	$i = 0;
	$nb_ligne = count($liste_parties);
	for ($i=0; $i < $nb_ligne; $i++)
	{
		$date = $liste_parties[$i][0];
		//echo $date;
		//echo "<br>";

		//$timestamp = strtotime($date);
		$annee = 2015;
		$mois = 7;
		
		$pieces = explode("-", $date);
		$timestamp = mktime (0, 0, 0, $mois, $pieces[0], $annee); // mois jour annee
		echo $timestamp;
		echo "<br>";
		
		//echo sprintf('%02d', $val);

		 $liste_parties[$i][0] = $timestamp;
		
	}

	return($liste_parties);
}


function import_donnees($fichier)
{
	// extractions des donnees
	$donnees = lire_csv($fichier);
	
	//echo "<pre>";
	//print_r($donnees);
	//echo "<br>";

	// fragmentation
	$liste_parties = array();
	$liste_joueurs = array();
	$liste_parties = $donnees[0];
	$liste_joueurs = $donnees[1]; 
	// affichage
	echo " ------------------------------" ."<br>";
	echo "<pre>";
	print_r($liste_parties);
	// ordonner par ordre alphabetique
	usort($liste_joueurs, "strcasecmp");
	print_r($liste_joueurs);
	$tab_retour = traitement_dates($liste_parties);
	unset($liste_parties);
	$liste_parties = $tab_retour;
 	// enregistrer 
    stockage_joueurs_DB($liste_joueurs);
	// calculer du classement
	elo($liste_parties);

	echo "Script executé avec succés";	
	
}	
?>