<?php
include 'connection_sql.php';
session_start();
## 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

## Search 
$searchQuery = " ";
if($searchValue != ''){
	$searchQuery = " and (STK_NO like '%".$searchValue."%' or 
        DESCRIPT like '%".$searchValue."%' or 
        BRAND_NAME like '%".$searchValue."%' 
        or SIZE like '%".$searchValue."%') ";
}

## Total number of records without filtering

$sel =  "select count(*) as allcount from s_mas" ;
$result = $conn->query($sel); 
$records = $result->fetch();
    
     
$totalRecords = $records['allcount'];

## Total number of records with filtering
$sel =  "select count(*) as allcount from s_mas WHERE 1 ".$searchQuery ;
 $result = $conn->query($sel); 
    $records = $result->fetch();
    
    
 
$totalRecordwithFilter = $records['allcount'];

## Fetch records
$empQuery = "select * from s_mas WHERE 1 ".$searchQuery." order by ".$columnName." ".$columnSortOrder." limit ".$row.",".$rowperpage;
 
$data = array();
 
foreach ($conn->query($empQuery) as $row) {
           if($_SESSION["CURRENT_DEP"]  ==""){
                $sql2 = "select * from s_submas where STK_NO='".$row['STK_NO']."' order by QTYINHAND desc";
            }else{
                $sql2 = "select * from s_submas   where STO_CODE='".$_SESSION["CURRENT_DEP"] ."'  and STK_NO='".$row['STK_NO']."' order by QTYINHAND desc";    
            }   
            $result2 = $conn->query($sql2); 
            $row2 = $result2->fetch();
            
    $data[] = array(
    		"id"=>'',
    		"STK_NO"=>$row['STK_NO'],
    		"DESCRIPT"=>$row['DESCRIPT'],
    		"SIZE"=>$row['SIZE'],
    		"BRAND_NAME"=>$row['BRAND_NAME'],
    		"SELLING"=>$row['SELLING'],
    		"QTYINHAND"=>$row['QTYINHAND'], 
    		"DQTYINHAND"=>$row2['QTYINHAND']
    	);
}

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

echo json_encode($response);
