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

	require( '../../GetDataFromDB.php' );

	

	$toProcess = true;

	$type 			= '';
	$description 	= '';
	$mdescription 	= '';
	$anatomicregion	= '';

	if ( isset ($_GET ['type'] ) )		  		$type 			= $_GET['type'];
	if ( isset ($_GET ['description'] ) )  		$description 	= $_GET['description'];
	if ( isset ($_GET ['mdescription'] ) )  	$mdescription 	= $_GET['mdescription'];
	if ( isset ($_GET ['anatomicregion'] ) ) 	$anatomicregion = $_GET['anatomicregion'];

	$draw			= $_GET ['draw'];
	$start			= $_GET ['start'];
	$length			= $_GET ['length'];

	$columns 		= $_GET ['columns'];
	$order			= $_GET ['order'];
	$orderCol		= $order [0]['column'];
	$orderDir		= $order [0]['dir'];
	$orderColName	= $columns [$orderCol]['data'];
	$orderby		= " ORDER BY ".$orderColName." ".$orderDir;

	$limit = '';

	$to_add 	= '';
	$to_remove	= '';

	if ( isset($_GET['to_add']) )
     	$to_add = $_GET['to_add'];

     if ( isset($_GET['to_remove']) )
     	$to_remove = $_GET['to_remove'];

	if ( isset($_GET['start']) && $_GET['length'] != -1 )
	{
			$limit = " OFFSET ".intval($_GET['start'])." LIMIT ".intval($_GET['length']);
	}

	if($_GET['linked'] == '1')
  	{
  		error_log (" linked." );

  		$whereclause = "and rsd.mstud_id = {$_GET['mstudid']}";

  		if ( $to_remove != '' )
     		$whereclause .= ' and rsd.rstud_id not in ('.$to_remove.')';
    }
    else
    {
    	error_log ( " not linked." );

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

     	if ( isset($_GET['datecode']) )
     	{
     		switch ( $_GET['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($_GET['withoutms']) )
     	{
     		if ( $_GET['withoutms'] == 'true' )
     			$whereclause .= " and rsd.mstud_id=-1";
     	}

     	if ( $to_add != '' )
     		$whereclause .= ' and rsd.rstud_id not in ('.$to_add.')';
  	}

  	error_log (" to_add : " .$to_add );

  	if($_GET['linked'] == '1')
  	{
		$psql = "
  		with themodtype as (select type as mastertype from  master_study_description where mstud_id = {$_GET['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,
  			0 as newrow
  		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 msd.description ilike '%{$mdescription}%' and rsd.description != '' and rsd.description ilike '%{$description}%' and mi.mod_id = m2.mod_id and mi.modident_id = rsd.modident_id {$whereclause}";

		if ( $to_add != "" )
		{
			$psql .= "
			union
			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,
  				1 as newrow
  			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 msd.description ilike '%{$mdescription}%' and rsd.description != '' and rsd.description ilike '%{$description}%' and mi.mod_id = m2.mod_id and mi.modident_id = rsd.modident_id and rsd.rstud_id in (".$to_add.")";
		}
	}
	else
	{
		$psql = "
  		with themodtype as (select type as mastertype from  master_study_description where mstud_id = {$_GET['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,
  			0 as newrow
  		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 msd.description ilike '%{$mdescription}%' and rsd.description != '' and rsd.description ilike '%{$description}%' and mi.mod_id = m2.mod_id and mi.modident_id = rsd.modident_id {$whereclause}";

		if ( $to_remove != "" )
		{
			$psql .= "
			union
			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,
  				1 as newrow
  			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 msd.description ilike '%{$mdescription}%' and rsd.description != '' and rsd.description ilike '%{$description}%' and mi.mod_id = m2.mod_id and mi.modident_id = rsd.modident_id and rsd.rstud_id in (".$to_remove.")";
		}
	}

	error_log ( "studym_description_linked1 : " .$psql );

	$recordsTotal 		= 1000;
	$recordsFiltered	= 0;

	$data				= Array ();

	if ( $toProcess == true )
		$data = GetDataFromDB ( $psql, $recordsFiltered, $limit, $orderby );

	$arr = array (
			"draw"            => intval( $draw ),
			"recordsTotal"    => intval( $recordsTotal ),
			"recordsFiltered" => intval( $recordsFiltered ),
			"data"            => $data,
			"sql"			  => $psql.$orderby.$limit
		);

	$result = json_encode ( $arr );

	echo $result;

?>