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

	header("Content-Type: text/xml");

	$selectednrdid = '-1';
	if(isset($_POST['nrdid']))
	{
		$selectednrdid = $_POST['nrdid'];
	}

	$nrdtype = '';
	$wherenrdtype = '';
	if(isset($_POST['nrdtype']))
	{
		$nrdtype = $_POST['nrdtype'];

		if ( $nrdtype != '' )
			$wherenrdtype = " where nrdtype='".$nrdtype."'";
	}

	$conn = get_dbconnection();
	
	
	if ( !isset($_POST['mstudid']) || $_POST['mstudid'] == '' )
  	{
    	$_POST['mstudid'] = 'null';
  	}

  	if($_POST['linked'] == '1')
  	{
  		$whereclause = "and rsd.mstud_id = {$_POST['mstudid']}";
    }
    else
    {
     	$whereclause = "and case when(m2.modalitytitle in ('CT','MG','NM','XA')) then m2.modalitytitle else 'RX' end = themodtype.mastertype and rsd.mstud_id != {$_POST['mstudid']}";

     	if ( isset($_POST['datecode']) )
     	{
     		error_log ( "datecode : " .$_POST['datecode'] );

     		switch ( $_POST['datecode'] )
     		{
     			case 0:
     				error_log ( "All dates " );
     				break;

     			case 1:
     				error_log ( "One month" );
     				$whereclause .= " and date >= (CURRENT_DATE::date - '1 month'::interval)";

     				break;

     			case 2:
     				error_log ( "Two months" );
     				$whereclause .= " and date >= (CURRENT_DATE::date - '2 month'::interval)";
     				break;

     			case 6:
     				error_log ( "Six months" );
     				$whereclause .= " and date >= (CURRENT_DATE::date - '6 month'::interval)";
     				break;
     		}
     	}

     	if ( isset($_POST['withoutms']) )
     	{
     		if ( $_POST['withoutms'] == 'true' )
     			$whereclause .= " and rsd.mstud_id=-1";
     	}
  	}

  	$sql = "with themodtype as (select type as mastertype from  master_study_description where mstud_id = {$_POST['mstudid']}) select distinct string_agg(rsd.rstud_id::text,',') over (PARTITION by m2.modalitytitle,rsd.mstud_id,rsd.description) as rstud_id,  to_char(max(date) over (partition by  m2.modalitytitle,rsd.mstud_id,rsd.description), 'YYYYMMDD') as date, msd.description as mdescription, string_agg(m2.name,',') over (PARTITION by m2.modalitytitle, rsd.mstud_id, rsd.description) as name, m2.modalitytitle,rsd.description as description,rsd.mstud_id from modality_identity mi, modality m2,themodtype,raw_study_description as rsd left join master_study_description as msd on rsd.mstud_id = msd.mstud_id
		where rsd.description != '' and mi.mod_id = m2.mod_id and mi.modident_id = rsd.modident_id {$whereclause};";

	 error_log ( "studym_description_linked : " .$sql );

	$query = pg_query($conn,$sql);

	$arr = array ();
	while ( $row = pg_fetch_row ($query) )
	{
		$res = array ( 
	        		"rstud_id" 		=> $row [0],
	        		"date"			=> $row [1],
	        		"mdescription"	=> $row [2],
	        		"modality" 		=> $row [3],
	        		"description"	=> $row [5]
	        		
	        	);

	    array_push ( $arr, $res );
	}

	header('Content-type: application/json');
	
	echo json_encode($arr);
?>
