<?php
	require_once '../../autoload.php';
	
	RightsCheck ("VIEW_AUDIT");
	
	$id		 		= -1;
	$comment 		= "";
	$title	 		= "";
	$inst_id 		= -1;
	$dep_id 		= -1;
	$date			= "";
	$start_date		= "";
	$end_date		= "";
	$status_id 		= -1;
	$origine 		= -1;
	$status_id 		= -1;
	$audit_type		= -1;
	
	
	
	if ( isset ( $_REQUEST['id'] ) 				)	$id			 		= $_REQUEST['id'];
	if ( isset ( $_REQUEST['inst_id'] )			)	$inst_id		 	= $_REQUEST['inst_id'];
	if ( isset ( $_REQUEST['dep_id'] )			)	$dep_id			 	= $_REQUEST['dep_id'];
	if ( isset ( $_REQUEST['date'] )			)	$date			 	= $_REQUEST['date'];
	if ( isset ( $_REQUEST['comment'] )			)	$comment			= $_REQUEST['comment'];
	if ( isset ( $_REQUEST['title'] )			)	$title				= $_REQUEST['title'];
	if ( isset ( $_REQUEST['start_date'] )		)	$start_date		 	= $_REQUEST['start_date'];
	if ( isset ( $_REQUEST['end_date'] )		)	$end_date		 	= $_REQUEST['end_date'];
	if ( isset ( $_REQUEST['status_id'] )		)	$status_id		 	= $_REQUEST['status_id'];
	if ( isset ( $_REQUEST['origine'] )			)	$origine		 	= $_REQUEST['origine'];
	if ( isset ( $_REQUEST['audit_type'] )		)	$audit_type		 	= $_REQUEST['audit_type'];
	
	
		
	$conn = get_dbconnection();
	
	$response = -1;
	
	if ( $conn )
	{
		$sql = '';

		if ( $id == -1 )
		{
			$sql = 'insert into audit(origine,date,status_id,title,start_date,end_date) values(0,now(),'.STATUS_PLANNED_ID.',\'New audit\',now(),now()) returning id;';
		}
		else
		{
			$sql = 'update audit';
  			$sql .= ' set comment = \''.pg_escape_string($conn,$comment).'\'';
  			$sql .= ' ,title = \''.pg_escape_string($conn,$title).'\'';

  			if ( $inst_id != '-1' && $inst_id != '' )
  				$sql .= ' ,inst_id = '.$inst_id;
  			else
    			$sql .= ' ,inst_id = -1';
  			
  			if ( $dep_id != '-1' && $dep_id != '' )
    			$sql .= ' ,dep_id = '.$dep_id;
  			else
    			$sql .= ' ,dep_id = -1';

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

  			$sql .= ' ,status_id = '.$status_id;
  			$sql .= ' ,origine = '.$origine;
  			$sql .= ' ,type = '.$audit_type;
  			$sql .= ' 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;
?>