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

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

	$toProcess = true;

	$desc_id 	= '';

	if ( isset ($_GET ['desc_id'] ) )  		$desc_id 	= $_GET['desc_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
				activated::integer,
				nrd.alertname as alertname,
				nrd.nrd_id as nrd_id,
				nrd.type as type,
				valuetype,
				percentile,
				nacquisition,
				age_begin/12 || '-<' ||age_end/12 as age,
				weight_begin || '-<' ||weight_end as weight,
				value || ' ' || case when (valuetype='DAP') then 'mGy.cm²' when (valuetype='DLP') then 'mGy.cm'
   				when (valuetype = 'DGM') then 'mGy' when (valuetype = 'CTDIvol') then 'mGy' when (valuetype = 'SCOPIE') then 's' when (valuetype = 'ACTIVITY') then 'MBq' when (valuetype = 'SACTIVITY') then 'MBq/Kg' else '' end as value,
   				value_vgd,
   				is_main::integer,
   				radioelement,
   				injectiontype
   			from
   				link_nrd, nrd, export_afcn
    		where
    			link_nrd.nrd_id = nrd.nrd_id and
    			link_nrd.type = 0 and
    			coalesce(validity_end,'2999-12-31') > now()::date and
    			export_afcn.desc_id = {$desc_id} and
    			link_nrd.link_id = export_afcn.exp_id";


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

?>