<?php
require_once '../../Server/connection.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

## Custom Field value
$searchByPermName = $_POST['searchByPermName'];
//$searchByroleName = $_POST['searchByroleName'];
$userId = $_POST['userId'];
## Search 

$searchQuery = " ";
if($searchByPermName != ''){
    $searchQuery .= " and (permissions.permission_name like '%".$searchByPermName."%') ";
}




if($userId != ''){
    $searchQuery .= " and (assigned_permissions.user_id='".$userId."') ";
}

if($userId != ''){
    $searchQuery1 .= " and (assigned_permissions.user_id='".$userId."') ";
}



if($searchValue != ''){ 
    $searchQuery .= " and (permissions.permission_name like '%".$searchValue."%')";
}



## Total number of records without filtering
$sel = mysqli_query($conn,"select count(*) as allcount from permissions,assigned_permissions where permissions.permission_id=assigned_permissions.permission_id and 1".$searchQuery1);
$records = mysqli_fetch_assoc($sel);
$totalRecords = $records['allcount'];

## Total number of records with filtering
$sel = mysqli_query($conn,"select count(*) as allcount from permissions,assigned_permissions where permissions.permission_id=assigned_permissions.permission_id and 1 ".$searchQuery);
$records = mysqli_fetch_assoc($sel);
$totalRecordwithFilter = $records['allcount'];

## Fetch records
$empQuery = "select assigned_permissions.assign_id,permissions.action,permissions.permission_name from permissions,assigned_permissions where permissions.permission_id=assigned_permissions.permission_id and 1 ".$searchQuery." order by ".$columnName." ".$columnSortOrder." limit ".$row.",".$rowperpage;
$empRecords = mysqli_query($conn, $empQuery);
$data = array();
$x = 1;
while ($row = mysqli_fetch_assoc($empRecords)){
	
	$productId = $row['assign_id'];
	$permName = $row['permission_name'];
	$permAction = $row['action'];
	
		
	
     
		
	
	$button = '<!-- Single button -->
	<div class="btn-group">
	<a type="button" class="btn btn-primary" data-toggle="modal" data-target="#removeProductModal" id="removeProductModalBtn" onclick="removeProduct('.$productId.')"> <i class="glyphicon glyphicon-trash"></i></a>
	
	</div>';
	

	
	
	
    $data[] = array(
    		"assign_id"=>$x,
			"Permissions"=>$permName,
			"Actions"=>$permAction,
    		"delete"=>$button
			//"edit"=>$button1
    	);
		$x++;
		
		
}

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

echo json_encode($response);
