<?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   = 'descriptions-map';
$table       = 'child_category_parameters';


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

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

## Fetch records
$childQuery = "SELECT CCP.*, PT.title AS child_category_desc_title, PT.sort_order AS parent_sort_order FROM child_category_parameters CCP JOIN parameter_title PT ON PT.id = CCP.title_id WHERE 1 ".$searchQuery." order by ".$columnName." ".$columnSortOrder." limit ".$row.",".$rowperpage;
$childRecords = mysqli_query($con, $childQuery);
$data = array();

while ($row = mysqli_fetch_assoc($childRecords)) {
    $status = $row['active'];
    ( $row['active'] == 1 ) ? $active = 'Yes': $active = 'No';
    $description = $row['description'];
    $order = $row['sort_order'];
    $data[] = array(
   		"child_category_desc_title"=> $row['child_category_desc_title'],            
   		"description"              => $description,
      "sort_order"               => $order,
  		"active"                   => $active,  		
      "edit"                     => '<a href="javascript:void(0);" data-description = "'.$description.'" data-order = "'.$order.'" data-status = "'.$status.'" data-extension = "'.$extension.'" data-identifier = "'.$primary_key.'" id = '.$row['id'].' data-table = "'.$table.'" 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['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);
