<?php
	require_once '../../autoload.php';
	
	$id		 		= -1;
	$title 			= "";
	$type 			= "";
	$comment		= "";
	$planned_date	= "";
	$formation_date	= "";
	$status_id		= "";
	$staff_id		= "";
	
	if ( isset ( $_REQUEST['id'] ) 				)	$id			 	= $_REQUEST['id'];
	if ( isset ( $_REQUEST['title'] ) 			)	$title 			= $_REQUEST['title'];
	if ( isset ( $_REQUEST['type'] ) 			)	$type 			= $_REQUEST['type'];
	if ( isset ( $_REQUEST['comment'] )			)	$comment		= $_REQUEST['comment'];
	if ( isset ( $_REQUEST['planned_date'] )	)	$planned_date	= $_REQUEST['planned_date'];
	if ( isset ( $_REQUEST['formation_date'] )	)	$formation_date	= $_REQUEST['formation_date'];
	if ( isset ( $_REQUEST['status_id'] )		)	$status_id		= $_REQUEST['status_id'];
	if ( isset ( $_REQUEST['staff_id'] )		)	$staff_id		= $_REQUEST['staff_id'];
		
	$conn = get_dbconnection();
	
	$response = -1;
	
	if ( $conn )
	{
		if ( $id == -1 )
		{
			$sql = "insert into staff_formation (title, staff_id, status_id) values ('New formation', ".$staff_id.", 3) returning id;";
		}
		else
		{
			$sql = 'update staff_formation';
  			$sql .= ' set status_id = '.$status_id;
  			$sql .= '  ,title = \''.pg_escape_string ($conn,$title).'\'';
  			if ( $formation_date != '')
    			$sql .= ' ,formation_date = to_timestamp(\''.pg_escape_string ($conn,$formation_date).'\',\'YYYY-MM-DD\')';
  			else
    			$sql .= ' ,formation_date = null';

  			if ( $planned_date != '')
    			$sql .= ' ,planned_date = to_timestamp(\''.pg_escape_string ($conn,$planned_date).'\',\'YYYY-MM-DD\')';
  			else
    			$sql .= ' ,planned_date = null';

  			$sql .= ' ,type = \''.pg_escape_string ($conn,$type).'\'';
  			$sql .= ' ,comment = \''.pg_escape_string ($conn,$comment).'\'';
  			$sql .= ' where id =  '.$id.' returning id; commit;';
  		}

  		error_log ( "Save formation : " .$sql );
		
		$result = pg_query ( $conn, $sql );

		if ( $result )
		{
			$row = pg_fetch_assoc($result);
			$response = $row ['id'];
		}
	}
	
	header ('Content-type: text/xml' );
	
	echo $response;
?>