<?php
// get these values from your DB.
require_once('config.php');
$error_message;
$valid = true;

$site_cd = $_REQUEST['site_cd'];


if (isset($_REQUEST['itm_mst_stockno'])){
	$where = " AND itm_mst.itm_mst_stockno = '".$_REQUEST['itm_mst_stockno']. "' ";
}else{
	$where = "";
}


$sql="SELECT DISTINCT  
		itm_mst.site_cd,
		itm_mst.itm_mst_stockno, 
		itm_mst_costcenter,
		itm_mst_mstr_locn,
		itm_mst.itm_mst_desc, 
		itm_mst_ext_desc 		= COALESCE(cast(itm_mst.itm_mst_ext_desc as varchar(2000)),'' ),
		itm_mst.itm_mst_type,   
		itm_mst.itm_mst_com_code, 
		itm_mst.itm_mst_itm_grp,
		itm_mst.itm_mst_issue_price,
		itm_mst_issue_uom,
		itm_mst_account,
		itm_mst_rec_supplier,
		itm_det_issue_price,
		itm_mst_partno = COALESCE(itm_mst_partno,''),
		itm_mst.itm_mst_ttl_oh
		
		FROM 		itm_mst (NOLOCK), itm_det (NOLOCK),  itm_sts (NOLOCK),  				
		itm_loc  WHERE (	( itm_mst.site_cd = itm_det.site_cd )  
		AND			( itm_mst.RowID = itm_det.mst_RowID ) 
		AND			( itm_mst.site_cd = itm_loc.site_cd )  
		AND			( itm_mst.RowID = itm_loc.mst_RowID )  
		AND			( itm_det.site_cd = itm_sts.site_cd ) 
		AND			( itm_det.itm_det_part_deac_status = itm_sts.itm_sts_status )  
		AND			( itm_sts_typ_cd = 'ACTIVE' )) ".$where."
		AND itm_mst.site_cd = '".$site_cd."'" ;
		
	$stmt = sqlsrv_query( $conn, $sql);

	if( !$stmt ) {
		 $error_message = "Error selecting table (itm_mst)";
		 returnError($error_message);
		 die( print_r( sqlsrv_errors(), true));
		 
	}

	$json = array();

	do {
		 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {		
			$json[] = $row;	
		
		 }
	} while ( sqlsrv_next_result($stmt) );


if ($valid) {

	//echo $sql;
	returnData($json);	
	
}

function returnData($json){
	 $json1 = json_encode($json);
	 //echo$json;
	 
	 if(empty(json_decode($json1,1))) {
     $returnData = array(
	'status' => 'Error',
	'message' => 'No Records found',
	'data' => $json);
}else{
	$returnData = array(
	'status' => 'SUCCESS',
	'message' => 'Successfully',
	'data' => $json);
}
	 
	
	
	echo json_encode($returnData);
}

function returnError($error_message){
	$json = array();
	
	$returnData = array(
	'status' => 'ERROR',
	'message' => $error_message,
	'data' => $json);
	
	echo json_encode($returnData);
		
}
	sqlsrv_free_stmt( $stmt);
	sqlsrv_close( $conn);	
 
?>