<?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']);
	}

	// $psql = "select * from study where stu_id=-42";

	$psql = "";

	if ( isset($_GET['value']) && $_GET['value'] != '' )
  	{
  		$conn = get_dbconnection();
		$escapev = pg_escape_string($conn,$_GET['value']);
	}

	if ( isset($_GET['value']) && $_GET['value'] != '' )
	{
	 	$whereclause = '';
	 	$escapev = pg_escape_string($conn,$_GET['value']);
	 	$conditionstudy = "where study.accessionnumber = '{$escapev}'";
	 	$conditionpatient = "where patient.id = '{$escapev}' or patient.name ilike '{$escapev}%'";

	 	$psql = "with filtered_study as (select pat_id, accessionnumber
  								from study
  									$conditionstudy
									),
									filtered_patient as (
  									select pat_id,id,name,to_char(birthdate, 'DD/MM/YYYY') as birthdate_formatted
  									,extract(year from age(now(), birthdate)) AS age
  									from patient
										 $conditionpatient
									)
									select distinct
  									coalesce (filtered_patient.pat_id, patient.pat_id) as pat_id,
  									coalesce (filtered_patient.id, patient.id) as id,
  									coalesce (filtered_patient.name, patient.name) as name,
  									coalesce (filtered_patient.birthdate_formatted, to_char(patient.birthdate, 'DD/MM/YYYY') ) as birthdate,
  									coalesce (filtered_patient.age, extract(year from age(now(), patient.birthdate)) ) as age,
  									filtered_study.accessionnumber as accessionnumber
										from filtered_patient full outer join filtered_study on filtered_study.pat_id = filtered_patient.pat_id
										left join patient on patient.pat_id=filtered_study.pat_id";
	}
	else
		if ( isset($_GET['stuid']) && $_GET['stuid'] != '' )
	 	{
 	 		// $conditionstudy = " where study.stu_id = ".$_GET['stuid'];
			// $conditionpatient = "";

			$psql = "with filtered_study as
					(
						select
							pat_id, accessionnumber
  						from
  							study
  						where study.stu_id = {$_GET['stuid']}
					)
					select distinct
						coalesce (patient.pat_id, patient.pat_id) as pat_id,
						coalesce (patient.id, patient.id) as id,
						coalesce (patient.name, patient.name) as name,
						to_char(patient.birthdate, 'DD/MM/YYYY') as birthdate,
						extract(year from age(now(), birthdate)) AS age,
						filtered_study.accessionnumber as accessionnumber
					from
						filtered_study, patient
					where
						patient.pat_id = filtered_study.pat_id";
	 	}


	error_log ( "GetDTPatientList : " .$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;

?>