<?php
require_once('config.php');

$error_message;
$valid = true;

$sql = "SELECT	DISTINCT

			itm_mst.itm_mst_stockno,
			itm_mst.itm_mst_costcenter,
			itm_mst.itm_mst_account,
			itm_mst.itm_mst_mstr_locn,			
			itm_mst.itm_mst_desc,	
			itm_mst.itm_mst_issue_uom,			
			itm_mst.itm_mst_issue_price,
			itm_mst.itm_mst_ttl_oh,
			itm_mst_ext_desc = COALESCE(cast(itm_mst.itm_mst_ext_desc as varchar (255)),''),	
			itm_det.itm_det_part_deac_status,
			itm_det.itm_det_order_pt,			
			itm_det_ttl_oh= COALESCE(itm_det_ttl_oh,0),
			
			category = CASE
			WHEN		((itm_loc_oh_qty - itm_loc_hard_resrv - itm_loc_short_qty + itm_loc_pr_due_in + itm_loc_due_in) < itm_loc_order_pt )
			AND         ((itm_loc_oh_qty - itm_loc_hard_resrv - itm_loc_short_qty + itm_loc_pr_due_in + itm_loc_due_in) < itm_loc_maximum )
			AND         ( itm_det_maximum  > 0 )
			AND         ( itm_det_order_pt  > 0 )
			AND         ( itm_mst_order_rule = 'L' ) THEN 'BELOW'

			WHEN		((itm_mst_ttl_oh - itm_det_ttl_hard_resrv - itm_det_ttl_short + itm_det_pr_due_in + itm_det_due_in) < itm_det_order_pt )
			AND         ((itm_mst_ttl_oh - itm_det_ttl_hard_resrv - itm_det_ttl_short + itm_det_pr_due_in + itm_det_due_in) < itm_det_maximum )
			AND         ( itm_det_maximum  > 0 )
			AND         ( itm_det_order_pt  > 0 )
			AND         ( itm_mst_order_rule = 'T' ) THEN 'BELOW'

			ELSE 'NORMAL' END,			
			
			itm_mst.RowID
			
FROM		itm_mst (NOLOCK)

INNER JOIN	itm_det (NOLOCK)            
ON          itm_mst.site_cd = itm_det.site_cd
AND         itm_mst.RowID = itm_det.mst_RowID

INNER JOIN  itm_sts (NOLOCK)
ON          itm_det.site_cd = itm_sts.site_cd 
AND         itm_det.itm_det_part_deac_status = itm_sts.itm_sts_status

INNER JOIN	itm_loc
ON			itm_mst.site_cd = itm_loc.site_cd
AND			itm_mst.RowID = itm_loc.mst_RowID

WHERE		itm_mst.site_cd = '".$_REQUEST['site_cd']."'
AND			itm_sts_typ_cd = '".$_REQUEST['status']."'

ORDER BY	itm_mst.itm_mst_stockno";
			
$stmt = sqlsrv_query( $conn, $sql);

if( !$stmt ) {
     $error_message = "Error selecting table (dft_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) {
	sqlsrv_free_stmt( $stmt);
	sqlsrv_close( $conn);	
	
	returnData($json);	
}

function returnData($json){
	$returnData = array(
	'status' => 'SUCCESS',	
	'data' => $json);
	
	echo json_encode($returnData);
}

function returnError($error_message){
	$json = array();
	
	$returnData = array(
	'status' => 'ERROR',	
	'data' => $json);
	
	echo json_encode($returnData);
	
	
		
	exit();
}
	


?>