<?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 v1 as (select
				a.desc_id as desc_id ,
				a.description_fr || ' ('||string_agg(distinct modalitytitle,'-')||')' as description_fr
			from
				description_afcn a,
				export_afcn l,
				annexe_afcn b
  			where
  				a.desc_id = l.desc_id and l.ann_id = b.ann_id and not(b.id = 'afcnannexe7' and a.description_fr = 'Thorax') group by a.desc_id )
  			select desc_id, description_fr from v1 where description_fr ilike '%{$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;

?>