<?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'];

	if(isset($post['tier']) && isset($post['available'])) {
		//fetch everything not in the tier yet, but available in the championship
		$tier = $post['tier'];
		$poule = $post['poule'];
		$teamfetch = pg_prepare($dbconn, "teamfetch", "select t.* from team t
			where t.idchampionship = $1 and
				t.idteam not in (select idteam from team_poule where team_poule.idchampionship = t.idchampionship
					and team_poule.idteam = t.idteam and team_poule.tier = $2
					)"); //and team_poule.tier = $2 and team_poule.poule = $3
		$teamfetch = pg_execute($dbconn, "teamfetch", array($idchampionship, $tier));
	} else if(isset($post['tier']) && isset($post['poule'])) {
		//fetch everything currently set in the poule
		$tier = $post['tier'];
		$poule = $post['poule'];
		$teamfetch = pg_prepare($dbconn, "teamfetch", "select team.* from team inner join team_poule using (idteam,idchampionship) where idchampionship = $1 and tier = $2 and poule = $3");
		$teamfetch = pg_execute($dbconn, "teamfetch", array($idchampionship, $tier, $poule));
	} else {
		//fetch the championships
		$teamfetch = pg_prepare($dbconn, "teamfetch", "select team.*, (select count(*) from driver where idchampionship = $1 and idteam = team.idteam) drivercount from team where idchampionship = $1");
		$teamfetch = pg_execute($dbconn, "teamfetch", array($idchampionship));
	}

	if($teamfetch === FALSE) {
		$result['ok'] = false;
		$result['error'] = pg_last_error($dbconn);
	} else {
		//build result object
		$teams = array();
		while($row = pg_fetch_assoc($teamfetch)) {
			$teams[] = $row;
		}

		$result['teams'] = $teams;

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

	//print message
	$resultjson =  json_encode($result);
	echo $resultjson;
?>
