<?php
	require_once '../../autoload.php';
	
	$survey_id 		= -1;
	$id		 		= -1;
	$content 		= "";
	$type			= -1;
	$position		= 0;
	$ai_analysis	= false;
		
	
	if ( isset ( $_REQUEST['survey_id'] )		)	$survey_id	 		= $_REQUEST['survey_id'];
	if ( isset ( $_REQUEST['id'] ) 				)	$id			 		= $_REQUEST['id'];
	if ( isset ( $_REQUEST['type'] )			)	$type	 		 	= $_REQUEST['type'];
	if ( isset ( $_REQUEST['position'] )		)	$position 		 	= $_REQUEST['position'];
	if ( isset ( $_REQUEST['content'] )			)	$content 		 	= $_REQUEST['content'];
	if ( isset ( $_REQUEST['ai_analysis'] )		)	$ai_analysis	 	= $_REQUEST['ai_analysis'];
	
		
	$conn = get_dbconnection();
	
	$response = -1;
	
	if ( $conn )
	{
		$sql = '';

		if ( $id == -1 )
		{
			$sql = "insert into survey_field(survey_id, type, position, content) values(".$survey_id.", ".$type.", ".$position.",'".pg_escape_string($conn,$content)."' ) returning id;";
		}
		else
		{
			$sql = 'update survey_field';
  			$sql .= ' set content = \''.pg_escape_string($conn,$content).'\'';
  			$sql .= ' ,type = '.$type.',ai_analysis='.$ai_analysis.' where id='.$id.' returning id;';
  		}
		
		$result = pg_query ( $conn, $sql );
		
		if ( $result )
		{
			if ( $row = pg_fetch_row($result) )
			{
				$response = $row [0];
			}
		}
	}
	
	header ('Content-type: text/xml' );
	
	echo $response;
?>