<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With" );

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

/* Begin the transaction. */
if ( sqlsrv_begin_transaction( $conn ) === false ) {
     die( print_r( sqlsrv_errors(), true ));
}


$site_cd 	= 	$_REQUEST['site_cd'];
$stockno	=	$_REQUEST['stockno'];



$sql="SELECT 	puo_mst.puo_mst_po_no,   
					puo_ls1.puo_ls1_po_lineno,   
					puo_mst.puo_mst_po_date,   
					puo_mst.puo_mst_po_type,   	 
					puo_mst.puo_mst_supplier,   
					puo_mst.puo_mst_status,   
					puo_mst.puo_mst_promised_date,  
					puo_ls1.puo_ls1_stk_locn,   
					puo_ls1.puo_ls1_ord_qty,   
					puo_ls1.puo_ls1_rcv_qty,
					puo_ls1.puo_ls1_invoice_qty
		FROM 	puo_mst, 
					puo_ls1
		WHERE 	puo_mst.site_cd = puo_ls1.site_cd
		AND 		puo_mst.RowID = puo_ls1.mst_RowID
		AND		puo_mst.puo_mst_clo_date IS NULL
		AND		( puo_ls1.puo_ls1_ord_qty + puo_ls1.puo_ls1_invoice_qty ) > puo_ls1.puo_ls1_rcv_qty
		AND 	puo_mst.site_cd  ='".$site_cd."'
		AND 	puo_ls1.puo_ls1_stockno ='".$stockno."'";

$stmt_pur_mst = sqlsrv_query( $conn, $sql);

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

$json = array();

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


if( $stmt_pur_mst ) {
		 sqlsrv_commit( $conn );
		 sqlsrv_close( $conn);	
		 returnData($json);	
	} else {
		 sqlsrv_rollback( $conn );
		 $error_message = "Transaction rolled back.<br />";
		 returnError($error_message);
	} 



function returnData($json){
	 $json1 = json_encode($json);
	 //echo$json;
	 
	 if(empty(json_decode($json1,1))) {
     $returnData = array(
	'status' => 'SUCCESS',
	'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);
	exit();
		
}
	

 
?>