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

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

	$toProcess = true;

	$description 	= '';

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

	$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 = "with t1 as (select
				itei.init_id as init_id,
				itei.group_id as group_id,
				itei.tag as tag,
				itei.condition as dicom_condition,
				itei.modalitytitle as modalitytitle,
				itei.sopuid as sopuid,
				itei.description as description,
				itei.extract_order as extract_order,
				itei.unit as unit,
				itei.parse_function as parse_function,
				itei.cvt_factor as cvt_factor,
				dm.match_id as match_id,
				dm.id as storage_id,
				dm.description as storage_id_description
	 		from
				info_to_extract_init itei
			left join dicomtag_matching dm on dm.match_id=itei.match_id) select * from t1 where sopuid='{$_GET['sopuid']}' and modalitytitle='{$_GET['modalitytitle']}' and group_id='{$_GET['group_id']}' and tag ilike '%{$_GET['tag']}%' and description ilike'%{$_GET['description']}%'";


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

?>