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

	$alert_type = (isset ($_GET['alert_type'] ))? $_GET['alert_type'] : "";

	$psql = "with t1 as (
				select mail_id from alertmail where type='".$alert_type."'
			)
			select
				t1.mail_id as mail_id,
				acc_id,
				lastname,
				firstname,
				upper(lastname) || ' ' || firstname as fullname,
				mail,
				role,
				status,
				removed
			from
				account
			left join
				alertmail_account_link aal
			on
				account.acc_id=aal.account_id
			left join
				t1
			on t1.mail_id=aal.alert_mail_id where removed=false";

	error_log ( "GetAlertAccountLinkDT : " .$psql );

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