<?php
	require_once '../../autoload.php';
	require( '../GetDataFromDB.php' );
	
	RightsCheck ("VIEW_PROCEDURE");

	$toProcess = true;
	
	$name		 	= $_GET ['name'];
	
	$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;

	error_log ( "=== alltagidallow : " .$_SESSION['alltagidallow'] );
	error_log ( "=== alltagiddeny : " .$_SESSION['alltagiddeny'] );
        
	$limit = '';

	if ( isset($_GET['start']) && $_GET['length'] != -1 ) 
	{
		$limit = " OFFSET ".intval($_GET['start'])." LIMIT ".intval($_GET['length']);
	}

	$whereclause = '';
  	if ( isset($_GET['procedureid']) )
    	 $whereclause = "and procedure.id = {$_GET['procedureid']}";

	$psql = "select id, name_en, name_fr, name_nl, comment, type, alltagidallow from ( select distinct procedure.id as id, name_en, name_fr, name_nl, comment, procedure.type as type,translate(alltagidallow::text, '{}', '') as alltagidallow, procedure.removed
      from  procedure left join v_taginfo on procedure.id  = v_taginfo.ext_id  and v_taginfo.link_type = 'procedure' and v_taginfo.removed = false where
       procedure.removed = false and name_fr ilike '%".$name."%' and (alltagidallow is null or ((alltagidallow & '{{$_SESSION['alltagiddeny']}}'::integer[]) = '{}'::integer[]) or tag_id = any('{{$_SESSION['alltagidallow']}}'::integer[]))
       or alltagidinducedallow @> '{{$_SESSION['alltagidallow']}}'::integer[] $whereclause ) sub where removed=false and name_fr ilike '%".$name."%'";

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