<?php
	require_once '../../autoload.php';

	RightsCheck ("VIEW_EXAMLIST");	

	$id		 		= -1;
	$name			= "";
	$modality		= "";
	$description	= "";
	$warninglist	= "";
	$tagexamlist	= "";
	
	if ( isset ( $_REQUEST['id'] ) 			)	$id		 		= $_REQUEST['id'];
	if ( isset ( $_REQUEST['name'] ) 		)	$name 			= $_REQUEST['name'];
	if ( isset ( $_REQUEST['modality'] ) 	)	$modality		= $_REQUEST['modality'];
	if ( isset ( $_REQUEST['description'] ) )	$description	= $_REQUEST['description'];
	if ( isset ( $_REQUEST['warninglist'] ) )	$warninglist	= $_REQUEST['warninglist'];
	if ( isset ( $_REQUEST['tagexamlist'] ) )	$tagexamlist	= $_REQUEST['tagexamlist'];
		
	$conn = get_dbconnection();
	
	$response = -1;
	
	if ( $conn )
	{
		$sql = "";
		
		if ( $id == -1 )
			$sql = "insert into examlist(nameid) values ('New exam') returning id;";
		else
		{
			$sql = 'update examlist';
  			$sql .= ' set nameid = \''.pg_escape_string ($name).'\'';
  			$sql .= ' ,modality = \''.pg_escape_string ($modality).'\'';
  			$sql .= ' ,description = \''.pg_escape_string ($description).'\'';
  			$sql .= ' where id =  '.$id.';';

  			if ( $warninglist == '')
  			{
    			$sql .= 'delete from examwarning_link where exam_id = '.$id.';commit;';
  			}
			else
			{
    			$sql .= 'delete from examwarning_link where exam_id = '.$id.' and examwarning_id not in ('.$warninglist.');';
    			$sql .= 'insert into examwarning_link(exam_id,examwarning_id)
      			select '.$id.', examwarning.id from examwarning left join examwarning_link on examwarning_link.examwarning_id = examwarning.id and exam_id = '.$id.'
      			where  examwarning.id in ('.$warninglist.') and examwarning.removed = false and examwarning_link.examwarning_id is null;commit;';
  			}

  			$sql .= create_update ( $tagexamlist, $_SESSION['alltagidallow'], $_SESSION['alltagiddeny'], 'examlist', $id );
		}
		
		error_log ( "SaveExam : " .$sql );
		$result = pg_query ( $conn, $sql );
		
		if ( $result )
		{
			if ( $id != -1 )
				$response = $id;
			else
			{
				if ( $row = pg_fetch_row($result) )
					$response = $row [0];
			}
		}
	}
	
	header ('Content-type: text/xml' );
	
	echo $response;
?>