<?php
include("connectServer.php");
session_start();

if (isset($_GET['game']) && isset($_GET['done']) && isset($_GET['time']) && isset($_GET['country'])){
	$piecesCountry = explode("_", $_GET['country']);
	$piecesDone = explode("_", $_GET['done']);
	$piecesTime = explode("_", $_GET['time']);
	
	if (count($piecesCountry) != count($piecesDone) || count($piecesCountry) != count($piecesTime)) {
		echo "missing pieces";
	}
	else {
		$_SESSION['score'] = 0;
		$_SESSION['total'] = 0;
		$_SESSION['time'] = 0;
        
        $game = intval($_GET['game']);
        
        $_SESSION['game'] = $game;
        
        if (isset($_SESSION['id'])) {
            $id = $_SESSION['id'];
        }
        else {
            $id = 0;
        }
        
		for ($i = 0; $i < count($piecesCountry); $i++) {
            $piecesCountry[$i] = intval($piecesCountry[$i]);
            $piecesDone[$i] = intval($piecesDone[$i]);
            $piecesTime[$i] = intval($piecesTime[$i]);
            
			$req = $bdd->prepare("INSERT INTO gData (GAME, PLAYER, COUNTRY, DONE, TIME) VALUES (" . $game . ", " . $id . ", " . $piecesCountry[$i] . ", " . $piecesDone[$i] . ", " . $piecesTime[$i] . ")");
			$req->execute();
			
			$_SESSION['total'] ++;
			if ($piecesDone[$i] == "1") {
				$_SESSION['score'] ++;
				$_SESSION['time'] += $piecesTime[$i];
			}
		}
		
		if ($_SESSION['time'] != 0) {
			$_SESSION['time'] = "Average response time : " . intval($_SESSION['time'] / $_SESSION['total']) . " s";
		}
		else {
			$_SESSION['time'] = "Looks like you got no right answer ... <br> Maybe next time !";
		}
	}
	
    header('Location: final.php', true, 302);
	exit;
}
else {
	echo "FAIL";
}
?>