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

	RightsCheck ("VIEW_INCIDENTREPORTING");


	$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		= '';

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

  	if ( $fromdate != '' )
  		$whereclause .= " and report.reportdate >= to_timestamp('{$fromdate} 00:00:00', 'DD/MM/YYYY HH24:MI:SS')";
  	if ( $todate != '' )
  		$whereclause .= " and report.reportdate <= to_timestamp('{$todate} 23:59:59', 'DD/MM/YYYY HH24:MI:SS')";

 	$psql = "select report.id as id, report.dep_id, v_fullinfo_department.fullname as department,title, report.status_id as status_id,  staff_member.lastname || ' ' || staff_member.firstname as reporterby,report.reporter as reporter,to_char(reportdate,'YYYYMMDD') as reportdate,  to_char(closeddate,'YYYYMMDD') as closeddate,comment,statuscomment,status_name,severity, listofactiondescription
	from report left join tag_link on report.dep_id = tag_link.ext_id and tag_link.type = 'department' left join (select ext_id,string_agg('&#x2022; '||description,'\n') as listofactiondescription from action,action_link where action.id = action_link.action_id and action_link.scope = 'report' group by ext_id) actionlink on actionlink.ext_id = report.id,staff_member,statuslist,v_fullinfo_department
	where report.reporter = staff_member.id and report.removed = false and statuslist.id = report.status_id and v_fullinfo_department.dep_id = report.dep_id and (v_fullinfo_department.instordepremoved = false or (v_fullinfo_department.inst_id=-1 and v_fullinfo_department.dep_id =-1)) and (tag_id is null or tag_id = any('{{$_SESSION['alltagidallow']}}'::integer[])) $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;
	
 
?>