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

	RightsCheck ("VIEW_STAFF");

	$name			= $_GET ['name'];
	$job			= $_GET ['job'];

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

	$whereclause2='';
  
  	if(isset($_GET['hasactivejob']))
  	{
	  	if($_GET['hasactivejob']=='false')
			$whereclause2 = "where jobactif!=".$_GET['hasactivejob']."::integer";
  	}

	$psql = "select id, login, password, lastname, firstname, fullname, job, jobactif from ( with temp as(select staff_member.id as id, login, password, lastname, firstname, lastname ||' '|| firstname as fullname, string_agg(distinct staff_role.name,',') as job, bool_or(tag_link.tag_id = any ('{{$_SESSION['alltagidallow']}}'::integer[]) and staff_job.enddate::date >now()::date)::integer as jobactif
from staff_member, staff_job, staff_role,v_staff_member_historyjobdeptagidlist,tag_link
where staff_job.removed = false and  staff_member.id = staff_job.staff_id and staff_role.id = staff_job.staff_role_id
and tag_link.type ='department' and tag_link.ext_id = staff_job.dep_id
and v_staff_member_historyjobdeptagidlist.staff_id = staff_member.id and v_staff_member_historyjobdeptagidlist.deptagidlist && '{{$_SESSION['alltagidallow']}}'::integer[]
and staff_member.removed = false group by staff_member.id order by lastname ||' '|| firstname asc)
select * from temp {$whereclause2} ) sub where fullname ilike '%".$name."%' and job ilike '%".$job."%'";


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