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

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

	$psql = "select staff_job.id as id ,institution.name as institutionname,department.name as departmentname,staff_role.name as rolename,to_char(staff_job.begdate,'YYYYMMDD') as begdate,to_char(staff_job.enddate,'YYYYMMDD') as enddate, staff_member.id as staff_id,staff_job.staff_role_id, staff_job.dep_id as dep_id
		from institution,department,staff_member, staff_job, staff_role
		where staff_role.id = staff_job.staff_role_id and institution.id = department.inst_id and department.id= staff_job.dep_id and staff_member.id = staff_job.staff_id and staff_job.removed =false";

	if(!isset($_GET['staffid']))
		error_log ("staffid not set !!!");
	
	if(!isset($_GET['jobid']))
		$psql.= " and staff_member.id = {$_GET['staffid']}";
	else
		$psql.= " and staff_job.id = {$_GET['jobid']}";


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