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

	session_start();	


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

	if(isset($_GET['extid']))
  {
     $whereclause = "and document_link.ext_id = {$_GET['extid']}";
  }else{
        $whereclause = "and document_link.ext_id = -1"; //no result;
    }

    if(isset($_GET['versioning']) &&  $_GET['versioning'] == '1')
    {
        $config->setColHidden(array("1","1","0","0","0","0","0","0","0","1"));
    }else{
        $whereclause .=' and v_last_documentstatus.status_id=1';
    }
  
  	$document_link_type = '';
    if(isset($_GET['doctype']))
    {
        $document_link_type = $_GET['doctype'];
    }

	
    $psql = "select document.id as id, document.revision as revision,document.label as label,to_char(creation_date,'MM/DD/YYYY') as date,staff_member.lastname || ' ' ||staff_member.firstname as author,document.label as label, document_master.name as name,document.comment as comment, to_char(creation_date,'MM/DD/YYYY') || ' ' || document_master.name||'_'||doc_master_id as doc_master_groupid
	from document_master,staff_member,document_link,document,v_last_documentstatus,statuslist
	where document_master.removed = false and staff_member.id = document.uploadedby and document_link.type='{$document_link_type}'and document_link.doc_id =
	document.id and document.id=v_last_documentstatus.doc_id and v_last_documentstatus.status_id = statuslist.id and document.removed = false and document_master.id = document.doc_master_id {$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;
	
 
?>