<?php
    require('includes/config.php');

## Read value
$draw = $_POST['draw'];
$row = $_POST['start'];
$rowperpage = $_POST['length']; // Rows display per page
$columnIndex = $_POST['order'][0]['column']; // Column index
$columnName = $_POST['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
$searchValue = $_POST['search']['value']; // Search value
$primary_key = 'role_id';
$call_back   =  'roles';

## Search 
$searchQuery = " ";
if($searchValue != ''){
	$searchQuery = " and (role_name like '%".$searchValue."%' ) ";
}

## Total number of records without filtering
$sel = mysqli_query($con,"SELECT count(*) as allcount FROM roles");
$records = mysqli_fetch_assoc($sel);
$totalRecords = $records['allcount'];

## Total number of records with filtering
$sel = mysqli_query($con,"SELECT count(*) as allcount FROM roles WHERE 1 ".$searchQuery);
$records = mysqli_fetch_assoc($sel);
$totalRecordwithFilter = $records['allcount'];

## Fetch records
$roleQuery = "SELECT * FROM roles WHERE 1 ".$searchQuery." order by ".$columnName." ".$columnSortOrder." limit ".$row.",".$rowperpage;
$roleRecords = mysqli_query($con, $roleQuery);
$data = array();

while ($row = mysqli_fetch_assoc($roleRecords)) {
    ( $row['active'] == 1 ) ? $active = 'Yes': $active = 'No';
    $data[] = array(
    		"role_name"=>$row['role_name'],    		
    		"active"=> $active,
    		"created_at"=> date( 'd-m-Y', $row['created_at'] ),
            "edit"=> '<a href="javascript:void(0);" data-extension = "'.$extension.'" data-identifier = "'.$primary_key.'" data-id = '.$row['role_id'].'  data-active = '.$row['active'].'  data-name = "'.$row['role_name'].'"  data-table = "roles" data-call_back = "'.$call_back.'" class = "edit"><i class="fa fa-pencil"></i></a>',
            "delete"=> '<a href="javascript:void(0);" data-extension = "'.$extension.'" data-identifier = "'.$primary_key.'" data-id = '.$row['role_id'].' data-table = "roles" data-call_back = "'.$call_back.'" class = "delete"><i class="fa fa-trash"></i></a>',
    	);
}

## Response
$response = array(
    "draw" => intval($draw),
    "iTotalRecords" => $totalRecords,
    "iTotalDisplayRecords" => $totalRecordwithFilter,
    "aaData" => $data
);

echo json_encode($response);
