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

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

		if ( $mstud_id != -1 )
		{
			$sql = 'update study set description_auto = raw_study_description.description, mstud_id_auto =-1';
  			$sql .= ' from raw_study_description where study.rstud_id = raw_study_description.rstud_id and mstud_id_auto = '.$mstud_id.';';
  			$sql .= 'update raw_study_description set mstud_id =-1 where mstud_id = '.$mstud_id.';';
  			$sql .= 'delete from link_nrd where type = 1 and  link_id = '.$mstud_id.';';
  		  	$sql .= 'delete from nrd USING nrd as nrd1 left join link_nrd on nrd1.nrd_id = link_nrd.nrd_id where link_nrd.nrd_id is null and nrd.nrd_id = nrd1.nrd_id and nrd.generic = false;';
  			$sql .= 'delete from master_study_description where mstud_id = '.$mstud_id.';commit;';

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

			if ( $result )
			{
				$response = $mstud_id;
			}
		}
	}
	
	header ('Content-type: text/xml' );
	
	echo $response;
?>