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

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

	$toProcess = true;

	$tag 		= '';
	$attribute 	= '';

	if ( isset ($_GET ['tag'] ) )  			$tag 		= $_GET['tag'];
	if ( isset ($_GET ['attribute'] ) )  	$attribute 	= $_GET['attribute'];

	$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
				dicom_tag.match_id as match_id,
				dicom_tag.dicom_id as dicom_id,
				dicom_tag.tag as tag,
				dicom_tag.condition as condition,
				attribute,
				type,
				custom_description,
				from_table,
				dm.id as storage_id
			from
				dicom_tag
			left join
				info_to_extract_init itei
			on itei.match_id = dicom_tag.match_id
				and itei.tag = dicom_tag.tag
				and itei.condition = dicom_tag.condition
				and sopuid='{$_GET['sopuid']}'
				and modalitytitle='{$_GET['modalitytitle']}'
			left join dicomtag_matching dm
			on dm.match_id =dicom_tag.match_id
			where
				itei.tag is null
				and visible = true
				and dicom_tag.match_id != -1 and dicom_tag.tag ilike '%".$tag."%' and dicom_tag.attribute ilike '%".$attribute."%'";

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

?>