<?php
	require_once '../../autoload.php';
	
	$id		 		= -1;
	$title	 		= "";
	$begindate		= "";
	$enddate		= "";
	$type			= -1;
	$statusd 		= -1;
	$description	= "";
	$comment		= "";
		
	
	if ( isset ( $_REQUEST['id'] ) 				)	$id			 		= $_REQUEST['id'];
	if ( isset ( $_REQUEST['title'] )			)	$title				= $_REQUEST['title'];
	if ( isset ( $_REQUEST['begindate'] )		)	$begindate		 	= $_REQUEST['begindate'];
	if ( isset ( $_REQUEST['enddate'] )			)	$enddate		 	= $_REQUEST['enddate'];
	if ( isset ( $_REQUEST['status'] )			)	$status	 		 	= $_REQUEST['status'];
	if ( isset ( $_REQUEST['type'] )			)	$type	 		 	= $_REQUEST['type'];
	if ( isset ( $_REQUEST['description'] )		)	$description		= $_REQUEST['description'];
	if ( isset ( $_REQUEST['comment'] )			)	$comment			= $_REQUEST['comment'];
	if ( isset ( $_REQUEST['conclusion'] )		)	$conclusion			= $_REQUEST['conclusion'];
	
		
	$conn = get_dbconnection();
	
	$response = -1;
	
	if ( $conn )
	{
		$sql = '';

		if ( $id == -1 )
		{
			$sql = 'insert into survey(title,begindate,enddate, type, status) values(\'New survey\',now(),now(), 1, 3) returning id;';
		}
		else
		{
			$sql = 'update survey';
  			$sql .= ' set description = \''.pg_escape_string($conn,$description).'\'';
  			$sql .= ' ,title = \''.pg_escape_string($conn,$title).'\'';
  			$sql .= ' ,comment = \''.pg_escape_string($conn,$comment).'\'';
  			$sql .= ' ,conclusion = \''.pg_escape_string($conn,$conclusion).'\'';

  			if ( $begindate != '' )
    			$sql .= ' ,begindate = to_timestamp(\''.pg_escape_string($conn,$begindate).'\',\'YYYY-MM-DD\')';
  			else
    			$sql .= ' ,begindate = null';
  
  			if ( $enddate != '' )
    			$sql .= ' ,enddate = to_timestamp(\''.pg_escape_string($conn,$enddate).'\',\'YYYY-MM-DD\')';
  			else
    			$sql .= ' ,enddate = null';
    
  			$sql .= ' ,status = '.$status;
  			$sql .= ' ,type = '.$type.' where id='.$id.';commit;';
  		}

  		error_log ( "SaveSurvey : " . $sql );
		
		$result = pg_query ( $conn, $sql );
		
		if ( $result )
		{
			if ( $row = pg_fetch_row($result) )
			{
				$response = $row [0];
			}
		}
	}
	
	header ('Content-type: text/xml' );
	
	echo $response;
?>