<?php
	include_once("db.php");

	//make result object
	$result = array();
	$result['ok'] = false;

	//get post data
	$postdata = file_get_contents("php://input");
	$post = json_decode($postdata, true);

	//fetch post variables
	$idchampionship = $post['idchampionship'];

	//fetch all the data
	$datafetch = pg_prepare($dbconn, "datafetch", "select poule.tier, poule.poule, team.idteam, team.name as teamname, race.idrace,
	(select extract(epoch from max(timestamp)-min(timestamp)) from measurement where idrace = race.idrace and valid) totaltime,
	(select sum(penaltyseconds) from comment where idrace = race.idrace) totalpenaltyseconds,
	(select min(timestamp) from measurement where idrace = race.idrace and valid) firsttimestamp,
	(select count(*) = 0 from race r left join measurement on r.idrace = measurement.idrace and valid where r.idrace = race.idrace and idmeasurement is null) everythingmeasured,
	(select extract(epoch from min(racetime)) from (select (max(timestamp)-min(timestamp)) racetime, tier, poule from valid_measurements inner join race r using (idrace) where tier = race.tier and poule = race.poule	group by tier, poule, idrace) sub) bestpouletotaltime
  from poule left join team_poule using (tier, poule, idchampionship) left join team using (idteam, idchampionship) left join race using (idteam, tier, poule, idchampionship) where poule.idchampionship = $1 order by poule.tier, poule.poule, team.idteam, idrace, firsttimestamp");
	$datafetch = pg_execute($dbconn, "datafetch", array($idchampionship));

	$datarows = array();
	while($row = pg_fetch_assoc($datafetch)) {
		$datarows[] = $row;
	}

	$result['rows'] = $datarows;

	//return data
	$result['ok'] = true;

	//print message
	$resultjson =  json_encode($result);

	echo $resultjson;
?>
