<?php 
require "../commonincludefiles.php";
		  
$start   = isset($_REQUEST['start'])  ? $_REQUEST['start']  :  0;
$limit   = isset($_REQUEST['limit'])  ? $_REQUEST['limit']  : 30;
$sort    = isset($_REQUEST['sort'])   ? $_REQUEST['sort']   : 'dist_code';
$dir     = isset($_REQUEST['dir'])    ? $_REQUEST['dir']    : 'ASC';
$filters = isset($_REQUEST['filter']) ? $_REQUEST['filter'] : null;
$condition = "";
	  
if(is_array($filters)){
	$encoded = false;
} else{
	$encoded = true;
	$filters = json_decode($filters);
}
	  
//$condition .= " and company_id = '".$company_id ."'";
$qs = '';
	  
if(is_array($filters)){
	for ($i=0;$i<count($filters);$i++){
    	$filter = $filters[$i];
		if($encoded){
			$field = $filter->field;
			$value = $filter->value;
			$compare = isset($filter->comparison) ? $filter->comparison : null;
			$filterType = $filter->type;
		} else{
			$field = $filter['field'];
			$value = $filter['data']['value'];
			$compare = isset($filter['data']['comparison']) ? $filter['data']['comparison'] : null;
			$filterType = $filter['data']['type'];
		}
		switch($filterType){
			case 'string' : $qs .= " AND ".$field." LIKE '%".$value."%'"; break;
			case 'numeric' :
				switch ($compare) {
					case 'eq' : $qs .= " AND ".$field." = ".$value; break;
					case 'lt' : $qs .= " AND ".$field." < ".$value; break;
					case 'gt' : $qs .= " AND ".$field." > ".$value; break;
				}
				break;
		}
	}
    $condition .= $qs; 
}
	  
if($_SESSION["cCompany_id"]!="" && isset($_SESSION["cCompany_id"])){
	$objDistMgmt = new DistMgmt();
	
	if ($sort != ""){
		$order_field = $sort;
		$order_type  = $dir;		
	}
	$total = $objDistMgmt->getCountRecords(0,0,$condition,"","");
	$order_field = 'dist_nameeng';
	$order_type  = 'ASC';	
	$rs = $objDistMgmt->getAllRecords($limit,$start,$condition,$order_field,$order_type);
    $i = 0;   
	$certificatesData = array("count" => $total, "certificates" => array());
	while($row = dbObject($rs)){
		$certificatesData["certificates"][$i] = $row;   
        $i++;
	}
	echo json_encode($certificatesData);
}
?>