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

	$idchampionship = $post['idchampionship'];
	$tier = $post['tier'];
	$poule = $post['poule'];

	//fetch the championships
	$racefetch = pg_prepare($dbconn, "racefetch", "select team.*, race.idrace, (select string_agg(laps||'', ',') lapagg
		from drive where drive.idrace = race.idrace),
		(select extract(epoch from max(case when sensortime is null then timestamp else sensortime end)-min(case when sensortime is null then timestamp else sensortime end)) from measurement where valid and idrace = race.idrace) as totaltime, 
		(select count(*) from measurement where idrace = race.idrace) measurementcount,
		(select count(*) from drive where idrace = race.idrace) drivecount from team inner join race using (idteam, idchampionship)
		where idchampionship = $1 and tier = $2 and poule = $3");
	$racefetch = pg_execute($dbconn, "racefetch", array($idchampionship, $tier, $poule));

	//build result object
	$races = array();
	while($row = pg_fetch_assoc($racefetch)) {
		$races[] = $row;
	}

	$result['races'] = $races;

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

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

	echo $resultjson;
?>
