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

	$laps = $post['laps'];
	$idrace = $post['idrace'];
	$iddriver = $post['iddriver'];

	// insert into drive (iddriver, idrace, laps, drivenr) values (13, 2, 6, (select coalesce(max(drivenr),0) from drive where iddriver = 13 and idrace = 2))

	$adddrive= pg_prepare($dbconn, "adddrive", "insert into drive (iddriver, idrace, laps, drivenr) values ($1, $2, $3, (select coalesce(max(drivenr)+1,1) from drive where idrace = $2))");
	$adddrive= pg_execute($dbconn, "adddrive", array($iddriver, $idrace, $laps));

	if($adddrive===FALSE) {
		$result['ok'] = false;
		$result['error'] = 'insert drive failed: '.pg_last_error($dbconn);
	} else {
		$result['ok'] = true;
	}


		$result['debug'] = array();
		$result['debug']['laps'] = $laps;
		$result['debug']['idrace'] = $idrace;
		$result['debug']['iddriver'] = $iddriver;

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

	echo $resultjson;
?>
