<?php
	require_once '../../../autoload.php';
	
	// RightsCheck ("VIEW_LOGINROLE");
	
	$mstud_id 		= -1;
	$description	= "";
	$anatomicregion	= "";
	$ri 			= "";
	$type 			= "";

	if ( isset ( $_REQUEST['mstud_id'] )		)	$mstud_id			= $_REQUEST['mstud_id'];
	if ( isset ( $_REQUEST['description'] )		)	$description 		= $_REQUEST['description'];
	if ( isset ( $_REQUEST['anatomicregion'] )	)	$anatomicregion 	= $_REQUEST['anatomicregion'];
	if ( isset ( $_REQUEST['ri'] )				)	$ri 				= $_REQUEST['ri'];
	if ( isset ( $_REQUEST['type'] )			)	$type 				= $_REQUEST['type'];
					
	$conn = get_dbconnection();
	
	$response = -1;
	
	if ( $conn )
	{
		$sql = '';

		if ( $mstud_id == -1 )
			$sql = "insert into master_study_description(description) values ('New master description') returning mstud_id;";
		else
		{
			set_time_limit(300);

			$sql = "update master_study_description";
  			$sql .= " set description = '".pg_escape_string ($conn,$description)."'";
  			$sql .= " ,anatomicregion = '".pg_escape_string ($conn,$anatomicregion)."'";
  			$sql .= " ,type = '".pg_escape_string ($conn,$type)."'";
  			if ( $ri == '0')
    			$sql .= " ,ri = false";
  			else 
    			$sql .= " ,ri = true";

  			$sql .= " where mstud_id =  ".$mstud_id.";";

  			$sql .= "update study set description_auto = description from master_study_description as msd where msd.mstud_id = ".$mstud_id." and study.mstud_id_auto = ".$mstud_id.";commit;";
		}

		error_log ( "save_master_study : " .$sql );
		
		$result = pg_query ( $conn, $sql );

		error_log ( " T1" );
		
		if ( $result )
		{
			error_log ( " T2" );
			if ( $mstud_id == -1 )
			{
				if ( $row = pg_fetch_row($result) )
					$response = $row [0];
			}
			else
				$response = $mstud_id;

			error_log ( " T3" );
		}

		error_log ( " T4" );
	}
	
	header ('Content-type: text/xml' );
	
	echo $response;
?>