<?php
	require_once '../../autoload.php';
	
	RightsCheck ("VIEW_DEVICE");
	
	$id		 			= -1;
	$device_id			= -1;
	$status_id			= -1;
	$type 				= "";
	$maintenance_date	= "";
	$planned_date		= "";
	$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['maintenance_date'] ))	$maintenance_date	= $_REQUEST['maintenance_date'];
	if ( isset ( $_REQUEST['planned_date'] )	)	$planned_date		= $_REQUEST['planned_date'];
	if ( isset ( $_REQUEST['comment'] )			)	$comment			= $_REQUEST['comment'];
	
	$conn = get_dbconnection();
	
	$response = -1;
	
	if ( $conn )
	{
		$sql = '';

		if ( $id == -1 )
		{
			$sql = "insert into device_maintenance(device_id, type, status_id) values (".$device_id.",'Corrective', 3) returning id;";
		}
		else
		{
			$sql = 'update device_maintenance';
  			$sql .= ' set comment = \''.pg_escape_string($conn,$comment).'\'';

  			if($maintenance_date != '')
    			$sql .= ' ,maintenance_date = to_timestamp(\''.pg_escape_string($conn,$maintenance_date).'\',\'YYYY-MM-DD\')';
  			else 
    			$sql .= ' ,maintenance_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 .= ' ,status_id = '.$status_id;
  			$sql .= " ,type = '".$type."'";
  			$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;
?>