<?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 	pur_mst.pur_mst_porqnnum,   
				pur_ls1.pur_ls1_pr_lineno,   
				pur_mst.pur_mst_rqn_date,  	
				pur_ls1.pur_ls1_supplier,   
				pur_mst.pur_mst_status,    
				pur_mst.pur_mst_req_date,  
				pur_ls1.pur_ls1_stk_locn,   
				pur_ls1.pur_ls1_ord_qty,
				pur_mst_cur_app_level, 
				pur_mst_app_level,
				pur_mst_requested_by,
				pur_mst_purq_approve, 
				pur_mst_op_flag,
				pur_ls1.pur_ls1_ord_uom
				
		FROM 	pur_mst, pur_ls1

		WHERE	pur_mst.site_cd = pur_ls1.site_cd
		AND		pur_mst.RowID = pur_ls1.mst_RowID
		AND		pur_mst.pur_mst_purq_approve IN ( 'W', 'A' )		
		AND		pur_ls1.pur_ls1_po_no IS NULL
		AND		pur_ls1_stockno IS NOT NULL
		AND 	pur_mst.site_cd ='".$site_cd."'
		AND 	pur_ls1.pur_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();
		
}
	

 
?>