<?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 = 'category_id';
$call_back   = 'primary-category';
$table       = 'parent_categories';

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

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

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

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

while ($row = mysqli_fetch_assoc($empRecords)) {
    $id         = $row['category_id'];
    $catName    = $row['category_name'];
    $imgPath    = $row['category_img_path'];
    $order      = $row['sort_order'];
    $status     = $row['active'];
    
    ( $row['active'] == 1 ) ? $active = 'Yes': $active = 'No';
    $data[] = array(
    		"category_name"       => $catName,
    		"sort_order"          => $order,
    		"category_img_path"   => $imgPath,
    		"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-order = "'.$order.'" data-status = "'.$status.'" data-id = '.$id.' data-categoryName = '.$row['category_name'].' data-imgPath = "'.$imgPath.'" 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['category_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);
