<?php
	require_once '../../autoload.php';
	
	RightsCheck ("VIEW_DEVICE");
	
	$id		 			= -1;
	$device_id			= -1;
	$status_id			= -1;
	$type 				= "";
	$planned_date		= "";
	$inspection_date	= "";
	$inspection_result	= "";
	$comment			= "";
	
	
	if ( isset ( $_REQUEST['id'] ) 				)	$id			 		= $_REQUEST['id'];
	if ( isset ( $_REQUEST['device_id'] )		)	$device_id		 	= $_REQUEST['device_id'];
	if ( isset ( $_REQUEST['status_id'] )		)	$status_id		 	= $_REQUEST['status_id'];
	if ( isset ( $_REQUEST['type'] )			)	$type 			 	= $_REQUEST['type'];
	if ( isset ( $_REQUEST['planned_date'] )	)	$planned_date		= $_REQUEST['planned_date'];
	if ( isset ( $_REQUEST['inspection_date'] )	)	$inspection_date	= $_REQUEST['inspection_date'];
	if ( isset ( $_REQUEST['result'] )			)	$inspection_result	= $_REQUEST['result'];
	if ( isset ( $_REQUEST['comment'] )			)	$comment			= $_REQUEST['comment'];
	
	$conn = get_dbconnection();
	
	$response = -1;
	
	if ( $conn )
	{
		$sql = '';

		if ( $id == -1 )
		{
			$sql = 'insert into device_inspection(device_id,result,status_id) values ('.$device_id.',-1,'.STATUS_PLANNED_ID.') returning id;';
		}
		else
		{
			$sql = "update device_inspection";
  			$sql .= " set status_id = ".$status_id;
  			$sql .= "  ,result = ".$inspection_result;
  			if ( $inspection_date != '')
    			$sql .= " ,inspection_date = to_timestamp('".pg_escape_string ($conn,$inspection_date)."','YYYY-MM-DD')";
  			else
    			$sql .= " ,inspection_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;";
  		}
		
		$result = pg_query ( $conn, $sql );
		
		if ( $result )
		{
			$row = pg_fetch_row($result);
			$response = $row [0];
		}
	}
	
	header ('Content-type: text/xml' );
	
	echo $response;
?>