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

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


	$toProcess = true;

	// $pat_id		 	= $_GET ['pat_id'];

	$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 = '';


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


	$whereclause = "";
	$filteralert = "";

	$modtype = '';;

	if(isset($_GET['modality']))
		$modtype = $_GET['modality'];

	function custom_filter($modtype)
	{
		global $whereclause;
		global $filteralert;

		switch($modtype)
		{
			case 'RX': $whereclause.= " and v_modality_config.modalitytitle not in ('CT','MG','NM')";
								 $filteralert.= " and modality.modalitytitle not in ('CT','MG','NM')";
			break;
			case 'CT': $whereclause.= " and v_modality_config.modalitytitle = 'CT'";
								 $filteralert.= " and modality.modalitytitle= ('CT')";
			break;
			case 'MG': $whereclause.= " and v_modality_config.modalitytitle = 'MG'";
							   $filteralert.= " and modality.modalitytitle = ('MG')";

			break;
			case 'NM': $whereclause.= " and v_modality_config.modalitytitle = 'NM'";
								 $filteralert.= " and modality.modalitytitle = ('NM')";
			break;
			default:break;
		}

		if ( isset($_GET["date1"]) && $_GET["date1"] != '' )
		{
			$ldate = $_GET["date1"];
			$_SESSION['filter_rx_data']['datefrom'] = $ldate;
			$_SESSION['filter_ct_data']['datefrom'] = $ldate;
			$_SESSION['filter_mg_data']['datefrom'] = $ldate;
			$_SESSION['filter_nm_data']['datefrom'] = $ldate;
			$whereclause .= " and date::date >= to_date('{$ldate}','YYYY-MM-DD')";
			$filteralert .= " and date::date >= to_date('{$ldate}','YYYY-DD-MM')";
		}
		if ( isset($_GET["date2"]) && $_GET["date2"] != '' )
		{
			$ldate = $_GET["date2"];
			$_SESSION['filter_rx_data']['dateto'] = $ldate;
			$_SESSION['filter_ct_data']['dateto'] = $ldate;
			$_SESSION['filter_mg_data']['dateto'] = $ldate;
			$_SESSION['filter_nm_data']['dateto'] = $ldate;
			$whereclause .= " and date::date <= to_date('{$ldate}','YYYY-MM-DD')";
			$filteralert .= " and date::date >= to_date('{$ldate}','YYYY-MM-DD')";
		}

		if ( isset($_GET["rirx"]) && $_GET["rirx"] == 'RI' )
			$whereclause .= " and (v_modality_config.ri = true or msd.ri = true)";
		else
		{
			if ( isset($_GET["rirx"]) && $_GET["rirx"] == $modtype )
				$whereclause .= " and (v_modality_config.ri = false or msd.ri = false)";
		}

		if ( isset($_GET["pname"]) && $_GET["pname"] != '' )
		{
			$pname = $_GET["pname"];
			$whereclause .= " and patient.name ilike '%{$pname}%'";
			$filteralert .= " and patient.name ilike '%{$pname}%'";
		}

		if ( isset($_GET["acn"]) && $_GET["acn"] != '' )
		{
			$acn = $_GET['acn'];
			$whereclause .= " and study.accessionnumber ilike '{$acn}%'";
		}

		if ( isset ($_GET['modalities']) && $_GET['modalities'] != '' )
		{
			$modalities = urldecode($_GET['modalities']);
			$whereclause .= " and v_modality_config.mod_id in({$modalities})";
			$filteralert .= " and modality.mod_id in({$modalities})";
		}

		if ( isset ($_GET['study']) && $_GET['study'] != '' )
		{
			$study = $_GET['study'];
			$whereclause .= " and study.description_auto ilike '%{$study}%'";
			$filteralert .= " and study.description_auto ilike '%{$study}%'";
		}


		if(isset($_GET["dhx_filter"]))
		{
			foreach($_GET["dhx_filter"] as $k => $v)
			{
				if($v != ''){
					switch($k)
					{

     					case 8:
            			{
              				$whereclause .= " and patient.id ilike '{$v}%'";
              				$filteralert .= " and patient.id ilike '{$v}%'";

            			}break;


						case 10:
						{
							$whereclause .= " and v_modality_config.mod_id in({$v})";
							$filteralert .= " and modality.mod_id in({$v})";
						}
						break;

						case 11:
						{
							$whereclause .= " and study.description_auto ilike '%{$v}%'";
							$filteralert .= " and study.description_auto ilike '%{$v}%'";
						}
						break;

						default: break;
					}
				}
			}
		}
	}




 	$conn = get_dbconnection();

  custom_filter($modtype);

  $alertclause = '';
  if(isset($_GET['alertraised']) && $_GET['alertraised'] == 'true')
  {
     	$alertclause = 'and alertwarning.stu_id is not null';
     	if(isset($_GET['nrdid']) && $_GET['nrdid'] != '')
     	{
       		$alertclause .= " and alertwarning.nrd_id in({$_GET['nrdid']})";
     	}
   }

  	$unreadalert = $_GET['unreadalert'] ?? 'false';
   	if($unreadalert == 'true')
   	{
     	$alertclause .= ' and ack_id is null';
   	}

	$psql = "select distinct case when alertwarning.stu_id  is not null = true then './dbconnector/examlist/db_get_alertforstudy.php?stuid='||study.stu_id else '' end  as subrow,study.stu_id,
   		ack_id as ack_id, case when(msd.ri or v_modality_config.ri) then 'RI' else '{$modtype}' end as isri, to_char(date,'DD/MM/YYYY') as date, patient.pat_id, patient.id as pid, replace(patient.name,'^',' ') as pname, v_modality_config.name as mname, study.description_auto as description,
   coalesce(round(study.dap_total::numeric,2)::text,'') || coalesce(coalesce(' ('||coalesce(round(study.fluoro_dap_total::numeric,2)::text || '|' || coalesce(study.total_fluoro_time/1000||'s',''),round(study.fluoro_dap_total::numeric,2)::text,study.total_fluoro_time/1000||'s',null)||')'),'') as dap_total,round(study.dgm_auto::numeric,2) as dgm_auto,round(study.dlp_auto::numeric,2) as dlp_auto,radioelement_auto, round(study.dosenm_auto::numeric,2) as dosenm_auto, coalesce(max(alertwarning.value/nullif(alertwarning.nrd_value,0)) over(partition by (study.stu_id)),0) as alertraise, accessionnumber from master_study_description msd,study left join alertwarning on study.stu_id = alertwarning.stu_id, patient,v_modality_config where patient.pat_id = study.pat_id and study.pro_id = v_modality_config.pro_id
   and msd.mstud_id = mstud_id_auto {$whereclause} {$alertclause}";



		$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
			);

		$result = json_encode ( $arr );

		echo $result;

?>