<?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 = 'id';
$call_back   = 'description-title';
$table       = 'parameter_title';

## Search 
$searchQuery = " ";
if($searchValue != ''){
	$searchQuery = " and ( PT.title like '%".$searchValue."%' or 
        S.service_name like '%".$searchValue."%' ) ";
}
## Total number of records without filtering
$sel = mysqli_query($con,"SELECT count(*) as allcount FROM parameter_title PT JOIN services S ON PT.service_id = S.id WHERE 1 ");
$records = mysqli_fetch_assoc($sel);
$totalRecords = $records['allcount'];

## Total number of records with filtering
$sel = mysqli_query($con,"SELECT count(*) as allcount FROM parameter_title PT JOIN services S ON PT.service_id = S.id WHERE 1 ".$searchQuery);
$records = mysqli_fetch_assoc($sel);
$totalRecordwithFilter = $records['allcount'];

## Fetch records
$childQuery = "SELECT PT.*, S.service_name AS service_name FROM parameter_title PT JOIN services S ON PT.service_id = S.id WHERE 1 ".$searchQuery." order by ".$columnName." ".$columnSortOrder." limit ".$row.",".$rowperpage;
$childRecords = mysqli_query($con, $childQuery);
$data = array();
while ($row = mysqli_fetch_assoc($childRecords)) {
      $id           = $row['id'];
      $serviceName  = $row['service_name'];
      $discTitle    = $row['title'];
      $order        = $row['sort_order'];
      $status       = $row['active'];
      ( $row['active'] == 1 ) ? $active = 'Yes': $active = 'No';
    $data[] = array(
   		"service_name" =>$serviceName,            
   		"title"        =>$discTitle,
      "sort_order"   =>$order,
  		"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['id'].' data-table = "'.$table.'" data-call_back = "'.$call_back.'" data-discTitle = "'.$discTitle.'"  data-serviceName ="'.$serviceName.'" data-order = "'.$order.'" data-status = "'.$status.'" 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['id'].' data-table = "'.$table.'" 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);
