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

	RightsCheck ("VIEW_EXAMLIST");

	$toProcess = true;
	
	$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']);
	}

	$whereclause = '';
  if(isset($_GET['name']))
  {
     $whereclause = "and examlist.nameid ilike '%{$_GET['name']}%'";
  }

  if(isset($_GET['description']))
  {
     $whereclause = "and examlist.description ilike '%{$_GET['description']}%'";
  }

  $having = '';
  if(isset($_GET['taglist']) && $_GET['taglist'] != '')
  {
    //(alltagidallow||alltagidinducedallow) & '{3,13}'::integer[]
  //  $having = " having (alltagidallow - '{{$_GET['taglist']}}'::integer[]) != '{}'::integer[]";
    if(isset($_GET['idtaglistand']) && $_GET['idtaglistand'] != '')
    {
      $whereclause .= "and ((alltagidallow||alltagidinducedallow)@> '{{$_GET['idtaglistand']}}'::integer[])";
    }

    if(isset($_GET['idtaglistor']) && $_GET['idtaglistor'] != '')
    {
      $whereclause .= " and tag_id = any('{{$_GET['idtaglistor']}}'::integer[])";
    }

  }

  
   $psql = "select  examlist.id,modality,nameid,description,STRING_AGG (distinct examwarning_link.examwarning_id::text,',') as riskv,translate(alltagidallow::text,'{}','') as taglist
   from examlist left join v_taginfo  on examlist.id = v_taginfo.ext_id and v_taginfo.link_type ='examlist'
   left join examwarning_link on examwarning_link.exam_id = examlist.id
   where examlist.removed = false and (examwarning_link.examwarning_id is null or examwarning_link.examwarning_id is not null)
   $whereclause and (alltagidallow is null or ((alltagidallow & '{{$_SESSION['alltagiddeny']}}'::integer[]) = '{}'::integer[]) or tag_id in({$_SESSION['alltagidallow']})
   or alltagidinducedallow @> '{{$_SESSION['alltagidallow']}}'::integer[])
   group by  examlist.id,modality,nameid,description,alltagidallow,alltagidinducedallow {$having}";
	
	$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;
	
 
?>