<?php
	require_once '../../autoload.php';
	
	RightsCheck ("VIEW_DEVICE");
	
	$id		 		= -1;
	$dep_id 		= -1;
	$installdate	= "";
	$removeddate	= "";
	$installedby	= "";
	$inchargeof		= "";
	$comment		= "";
	
	if ( isset ( $_REQUEST['id'] ) 				)	$id			 		= $_REQUEST['id'];
	if ( isset ( $_REQUEST['dep_id'] )			)	$dep_id			 	= $_REQUEST['dep_id'];
	if ( isset ( $_REQUEST['device_id'] )		)	$device_id		 	= $_REQUEST['device_id'];
	if ( isset ( $_REQUEST['installdate'] )		)	$installdate		= $_REQUEST['installdate'];
	if ( isset ( $_REQUEST['removeddate'] )		)	$removeddate		= $_REQUEST['removeddate'];
	if ( isset ( $_REQUEST['installedby'] )		)	$installedby		= $_REQUEST['installedby'];
	if ( isset ( $_REQUEST['inchargeof'] )		)	$inchargeof			= $_REQUEST['inchargeof'];
	if ( isset ( $_REQUEST['comment'] )			)	$comment			= $_REQUEST['comment'];
		
	$conn = get_dbconnection();
	
	$response = -1;
	
	if ( $conn )
	{
		$sql = '';

		if ( $id == -1 )
		{
			
			$sql = 'insert into device_installation(device_id,installdate,dep_id) values ('.$device_id.',now(),-1) returning id;';
		}
		else
		{
  			$sql = 'update device_installation';
  			$sql .= ' set dep_id = '.$dep_id;
  			$sql .= ' ,installdate = to_timestamp(\''.pg_escape_string ($conn,$installdate).'\'||to_char(installdate,\'HH24MISS\'),\'YYYY-MM-DDHH24MISS\')';
  			if ( $removeddate != '')
    		$sql .= ' ,removeddate = to_timestamp(\''.pg_escape_string ($conn,$removeddate).'\'||to_char(now(),\'HH24MISS\'),\'YYYY-MM-DDHH24MISS\')';
  			else
    			$sql .= ' ,removeddate = null';
  			$sql .= ' ,installedby = \''.pg_escape_string ($conn,$installedby).'\'';
  			$sql .= ' ,inchargeof = \''.pg_escape_string ($conn,$inchargeof).'\'';
  			$sql .= ' ,comment = \''.pg_escape_string ($conn,$comment).'\'';
  			$sql .= ' where id =  '.$id.';commit;';
  		}
		
		$result = pg_query ( $conn, $sql );
		if ( $id != -1 )
			$response = $id;
		else
		{
			if ( $result )
			{
				if ( $row = pg_fetch_row($result) )
					$response = $row [0];
			}
		}
	}
	
	header ('Content-type: text/xml' );
	
	echo $response;
?>