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

$idrace = $post['idrace'];

//fetch the team
$teamfetch = pg_prepare($dbconn, "teamfetch", "SELECT team.* FROM team INNER JOIN race using (idteam) where idrace = $1");
$teamfetch = pg_execute($dbconn, "teamfetch", array($idrace));
$team = pg_fetch_assoc($teamfetch);

//fetch the drivers
$driverfetch = pg_prepare($dbconn, "driverfetch", "SELECT iddriver, idteam, driver.name drivername, team.name teamname, team.idchampionship from driver inner join team using (idteam) where idteam = $1");
if($driverfetch===FALSE) {
	$result['ok'] = false;
	$result['error'] = pg_last_error();
} else {
	$driverfetch = pg_execute($dbconn, "driverfetch", array($team['idteam']));
	if($driverfetch===FALSE) {
		$result['ok'] = false;
		$result['error'] = pg_last_error();
	} else {
		$drivers = array();
		while($row = pg_fetch_assoc($driverfetch)) {
			$drivers[] = $row;
		}
		//set the drivers in the team object
		$team['drivers'] = $drivers;
		//set the result object
		$result['team'] = $team;
		//return data
		$result['ok'] = true;
	}
}

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

echo $resultjson;
?>
