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

	RightsCheck ("VIEW_DOSIMETRY");

	$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='';
  
  	$fromdate 	= '';
  	$todate		= '';
  	$status_id	= '-1';

  	if(isset($_GET['fromdate']))  		$fromdate 	= $_GET['fromdate'];
  	if(isset($_GET['todate']))  		$todate 	= $_GET['todate'];
  	if(isset($_GET['status_id']))  		$status_id 	= $_GET['status_id'];

  	if ( $fromdate != '' )
  		$whereclause .= " and afcnsend.senddate >= to_timestamp('{$fromdate} 00:00:00', 'YYYY-MM-DD HH24:MI:SS')";
  	if ( $todate != '' )
  		$whereclause .= " and afcnsend.senddate <= to_timestamp('{$todate} 23:59:59', 'YYYY-MM-DD HH24:MI:SS')";
  	if ( $status_id != '-1' )
  	 	$whereclause .= " and afcnsend.status_id = {$status_id}";

	$psql = "select distinct afcnsend.id, institution.name as institution, department.name as department, statuslist.status_name as status, staff_member.firstname || ' ' || staff_member.lastname as sender, to_char(senddate,'YYYYMMDD') as senddate, status_id, afcnsend.inst_id, afcnsend.dep_id as dep_id, title,comment,afcnsend.device_id as dev_id, device.name as device
 	from institution, department, statuslist, afcnsend left join device on device_id=device.id left join tag_link on (tag_link.type = 'department' and tag_link.ext_id = dep_id) or (tag_link.type = 'institution' and tag_link.ext_id = inst_id),staff_member
 	where afcnsend.inst_id =institution.id and afcnsend.dep_id =department.id and afcnsend.status_id =statuslist.id and afcnsend.removed=false and afcnsend.sender = staff_member.id and (tag_id = any('{{$_SESSION['alltagidallow']}}'::integer[]) or afcnsend.dep_id in(null,-1)) $whereclause";

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