<?php
require_once('config.php');
require_once('f_update_budget.php');
require_once('f_update_purchase_budget.php');
require_once('f_clear_shortage.php');

// Takes raw data from the request
$json = file_get_contents('php://input');
$result = json_decode($json);

$ldc_tax_amt = 0;
$li_grn_line = 0;
$current_datetime = date("Y-m-d h:i:s");
$surcharge = 0;
$lb_receive = false;

//React check all the line mandatory stock location fill up (for line with stock no)

if (sqlsrv_begin_transaction($conn) === false)
{
    die(print_r(sqlsrv_errors() , true));
}

foreach($result->Header as $Header){
	
	$site_cd			= $Header->site_cd;
	$ls_empl_id			= $Header->emp_mst_empl_id;
	$ls_po_no			= $Header->puo_mst_po_no;	
	$ls_po_status		= $Header->puo_mst_status;
	$ls_pkg_slip		= $Header->pkg_slip;
	$ls_remark			= $Header->itm_trx_remark;	
	$ls_supplier		= $Header->puo_mst_supplier;
	$ls_crd_costcenter	= $Header->puo_det_crd_costcenter;
	$ls_crd_account		= $Header->puo_det_crd_account;
	$ll_po_rowid		= $Header->RowID;	
	$ld_trx_date		= $Header->doc_date;	
	$ld_po_date			= $Header->puo_mst_po_date;
	$ls_pr_chg_costcenter= $Header->puo_det_chg_costcenter;
	$ls_pr_chg_account	= $Header->puo_det_chg_account;
	$audit_user			= $Header->audit_user;
	$audit_date			= $Header->audit_date;
	$is_mr_reserver		= $Header->is_mr_reserver;
	$is_auto_close		= $Header->is_auto_close;
}

foreach($result->Details as $Detail){
	
	$ls_category 			= $Detail->puo_ls1_item_category;
	$ls_stock_no 			= $Detail->puo_ls1_stockno;
	$ls_desc 				= $Detail->puo_ls1_description;
	$ls_stk_locn 			= $Detail->puo_ls1_stk_locn;
	
	$ldc_rcv_qty			= $Detail->receive_qty;
		
	$ls_chg_costcenter 		= $Detail->puo_ls1_chg_costcenter;
	$ls_chg_account 			= $Detail->puo_ls1_chg_account;
	$ls_project 			= $Detail->puo_ls1_projectid;
			
	$ls_rcv_uom 			= $Detail->puo_ls1_ord_uom;
	
	$ll_po_lineno			= $Detail->puo_ls1_po_lineno;
	$ll_po_line_rowid 		= $Detail->Rowid;
	
	$ls_wo 					= $Detail->puo_ls1_wo_no;
	$ls_pr 					= $Detail->puo_ls1_pr_no;
	$ll_pr_lineno 			= $Detail->puo_ls1_pr_lineno;
	
			
	
	
	If ($ldc_rcv_qty > 0){ 
		$lb_receive = true;
	}
	
	//Check stock location if valid
	$sql = "SELECT 	'count' = count(*)
			FROM 	loc_mst (NOLOCK)
			WHERE 	site_cd = '".$site_cd."'
			AND		loc_mst_stk_loc = '".$ls_stk_locn."'";

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

	if( !$stmt ) {
		sqlsrv_rollback($conn);
		sqlsrv_close($conn);
		 $error_message = "Error select table (itm_mst, itm_loc) - 1";
		 returnError($error_message);
		 die( print_r( sqlsrv_errors(), true));
	}

	do {
		 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
			$count_stk_loc = $row['count'];	
		
		 }
	} while ( sqlsrv_next_result($stmt) );	
	
	if ($count_stk_loc == 0) {
		returnError("The stock location not found in the location master, Please select a valid stock location") ;
	}
	
	//Check if stock exist
	$li_cnt = 0;
	
	$sql = "SELECT		'li_cnt' = COUNT(*)
			FROM 		itm_mst (NOLOCK), 
						itm_loc (NOLOCK)
			WHERE 		( itm_mst.RowID = itm_loc.mst_RowID )
			AND			( itm_mst.site_cd = '".$site_cd."' ) 
			AND			( itm_mst.itm_mst_stockno = '".$ls_stock_no."' ) 
			AND			( itm_loc.itm_loc_stk_loc = '".$ls_stk_locn."' )";

	$stmt = sqlsrv_query( $conn, $sql);				
					
	if( !$stmt ) {
		sqlsrv_rollback($conn);
		sqlsrv_close($conn);
		 $error_message = "Error select table (itm_mst, itm_loc)";
		 returnError($error_message);
		 die( print_r( sqlsrv_errors(), true));
	}

	do {
		 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
			$li_cnt = $row['li_cnt'];		
		 }
	} while ( sqlsrv_next_result($stmt) );	
	
	if($li_cnt == 0 && strlen($ls_stock_no ?? '') > 0){
		//Get itm_mst RowiID
		$sql = "SELECT 	'll_RowID' = itm_mst.rowid
				FROM 	itm_mst (NOLOCK)
				WHERE 	site_cd = '".$site_cd."'
				AND		itm_mst_stockno	= '".$ls_stock_no."'";

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

		if( !$stmt ) {
			sqlsrv_rollback($conn);
			sqlsrv_close($conn);
			 $error_message = "Error select table (itm_mst.rowid)";
			 returnError($error_message);
			 die( print_r( sqlsrv_errors(), true));
		}

		do {
			 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
				$ll_RowID = $row['ll_RowID'];	
			
			 }
		} while ( sqlsrv_next_result($stmt) );	
		
		//Get loc_mst_stock_cost_flag
		$sql = "SELECT 		loc_mst_stock_cost_flag
				FROM		loc_mst (NOLOCK)
				WHERE		site_cd = '".$site_cd."'
				AND			loc_mst_stk_loc = '".$ls_stk_locn."'";

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

		if( !$stmt ) {
			sqlsrv_rollback($conn);
			sqlsrv_close($conn);
			 $error_message = "Error select table (loc_mst)";
			 returnError($error_message);
			 die( print_r( sqlsrv_errors(), true));
		}

		do {
			 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
				$loc_mst_stock_cost_flag = $row['loc_mst_stock_cost_flag'];	
			
			 }
		} while ( sqlsrv_next_result($stmt) );	
		
		//Insert itm_loc
		//Select stock location loc_mst_stock_cost_flag
		$sql = "INSERT itm_loc (	
				site_cd, 						itm_loc_stk_loc, 					mst_RowID, 				
				itm_loc_oh_qty, 				itm_loc_item_cost, 					itm_loc_create_date,  
				itm_loc_stock_cost_flag,		itm_loc_lockout4count, 				itm_loc_order_pt, 
				itm_loc_maximum, 				itm_loc_minimum, 					itm_loc_inc_ttloh, 
				itm_loc_prim_locn_flg, 			itm_loc_pr_due_in, 					itm_loc_due_in, 
				itm_loc_hard_resrv, 			itm_loc_short_qty,  				audit_user, 
				audit_date,						mbl_audit_user,						mbl_audit_date )
		VALUES (
				'".$site_cd."', 				'".$ls_stk_locn."', 				".$ll_RowID.", 				
				0, 								0, 									GETDATE(),  
				'".$loc_mst_stock_cost_flag."', '0', 								0, 
				0,								0, 									'1', 
				'0',							0, 									0, 
				0, 								0, 									'".$audit_user."', 
				GETDATE(),						'".$audit_user."', 					GETDATE() )";

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

		if( !$stmt ) {
			sqlsrv_rollback($conn);
			sqlsrv_close($conn);
			 $error_message = "Error insert table (itm_loc)";
			 returnError($error_message);
			 die( print_r( sqlsrv_errors(), true));
		}
		
	}
	
	$itm_lockout = "0";
	
	//Select item lockout status	
	$sql = "SELECT 	'itm_lockout' = itm_loc_lockout4count 
			FROM 	itm_mst (NOLOCK), 
					itm_loc (NOLOCK)
			WHERE 	( itm_mst.RowID = itm_loc.mst_RowID )
			AND		( itm_mst.site_cd = '".$site_cd."' ) 
			AND		( itm_mst.itm_mst_stockno = '".$ls_stock_no."' ) 
			AND		( itm_loc.itm_loc_stk_loc = '".$ls_stk_locn."' )";

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

	if( !$stmt ) {
		sqlsrv_rollback($conn);
		sqlsrv_close($conn);
		 $error_message = "Error select table (itm_mst, itm_loc) - 2";
		 returnError($error_message);
		 die( print_r( sqlsrv_errors(), true));
	}

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



	if ($itm_lockout == '1') {
		returnError("Item lockout for stock count") ;
	}
	
	
}

//Select ls_input_acc	
$sql = "SELECT	'ls_input_acc' = dft_mst_gst_input_tax_cd
		FROM		dft_mst (NOLOCK)
		WHERE	site_cd = '".$site_cd."'";

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

if( !$stmt ) {
	sqlsrv_rollback($conn);
	sqlsrv_close($conn);
	 $error_message = "Error select table (dft_mst)";
	 returnError($error_message);
	 die( print_r( sqlsrv_errors(), true));
}

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

if($lb_receive === true){
	//Select document number			
	$sql = "Select		doc_no = trx_cnt_prefix + SUBSTRING(CONVERT(VARCHAR(7), trx_cnt_counter + 1000000), 2, 6)
			From 		trx_cnt WITH (UPDLOCK)
			Where 		site_cd = '".$site_cd."' And 		trx_cnt_module_cd = 'RCV'";

	$stmt = sqlsrv_query( $conn, $sql);				
					
	if( !$stmt ) {
		sqlsrv_rollback($conn);
		sqlsrv_close($conn);
		 $error_message = "Error select table (cnt_mst)";
		 returnError($error_message);
		 die( print_r( sqlsrv_errors(), true));
	}


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

	$sql = "UPDATE trx_cnt WITH (UPDLOCK) SET trx_cnt_counter = trx_cnt_counter + 1 WHERE site_cd = '".$site_cd."' AND trx_cnt_module_cd = 'RCV'";			
	$stmt = sqlsrv_query( $conn, $sql);				
					
	if( !$stmt ) {
		sqlsrv_rollback($conn);
		sqlsrv_close($conn);
		 $error_message = "Error update table (cnt_mst)";
		 returnError($error_message);
		 die( print_r( sqlsrv_errors(), true));
	}
	
	//Loop Detail
	foreach($result->Details as $Detail){
	
		$ls_category 			= $Detail->puo_ls1_item_category;
		$ls_stock_no 			= $Detail->puo_ls1_stockno;
		$ls_desc 				= $Detail->puo_ls1_description;
		$ls_stk_locn 			= $Detail->puo_ls1_stk_locn;
		
		$ldc_rcv_qty			= $Detail->receive_qty;
			
		$ls_chg_costcenter 		= $Detail->puo_ls1_chg_costcenter;
		$ls_chg_account 		= $Detail->puo_ls1_chg_account;
		$ls_project 			= $Detail->puo_ls1_projectid;
				
		$ls_rcv_uom 			= $Detail->puo_ls1_ord_uom;
		
		$ll_po_lineno			= $Detail->puo_ls1_po_lineno;
		$ll_po_line_rowid 		= $Detail->Rowid;
		
		$ls_wo 					= $Detail->puo_ls1_wo_no;
		$ls_pr 					= $Detail->puo_ls1_pr_no;
		$ll_pr_lineno 			= $Detail->puo_ls1_pr_lineno;
		
		if($ldc_rcv_qty > 0 ){
			$ll_Rowid = 0;
			$ls_issue_uom = '';
			$ls_cr_code = '';
			$ldc_tot_oh = 0;
			$ldc_avg_cost = 0;
			$ldc_itm_cost = 0;
			$latest_itm_cost = 0;
			$ldc_std_cost = 0;
			$ls_serialize_flg = "0";
			
			
			//Select Item detail from itm_mst and itm_det
			$sql = "SELECT 	'itm_mst_rowid' = itm_mst.RowID,
							itm_mst_desc,
							itm_mst_ttl_oh,
							itm_det_std_cost,
							itm_det_item_cost,
							itm_det_avg_cost,         			
							itm_det_cr_code,			
							itm_mst_serialize_flg,
							itm_mst_auto_serialize_flg,
							itm_mst_serialize_counter,
							itm_det_issue_uom
					FROM 	itm_mst (NOLOCK),
							itm_det (NOLOCK)
					WHERE 	( itm_mst.RowID =itm_det.mst_RowID ) 
					AND 	( itm_mst.itm_mst_stockno = '".$ls_stock_no."' ) 
					AND 	( itm_mst.site_cd ='".$site_cd."' )";

			$stmt = sqlsrv_query( $conn, $sql);
							
			if( !$stmt ) {
				
				sqlsrv_rollback($conn);
				sqlsrv_close($conn);
				 $error_message = "Error select table (itm_mst , itm_det)";
				 returnError($error_message);
				 die( print_r( sqlsrv_errors(), true));
			}

			do {
				 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
					$ll_Rowid	 				= $row['itm_mst_rowid'];
					$ldc_tot_oh 				= $row['itm_mst_ttl_oh'];
					$ldc_std_cost 				= $row['itm_det_std_cost'];
					$ldc_itm_cost 				= $row['itm_det_item_cost'];
					$ldc_avg_cost 				= $row['itm_det_avg_cost'];	
					$ls_cr_code 				= $row['itm_det_cr_code'];
					$ls_serialize_flg 			= $row['itm_mst_serialize_flg'];
					$ls_auto_serialize_flg 		= $row['itm_mst_auto_serialize_flg'];
					$ll_serialize_counter		= $row['itm_mst_serialize_counter'];
					$ls_issue_uom 				= $row['itm_det_issue_uom'];
	
	
				 }
			} while ( sqlsrv_next_result($stmt) );	
			
			$itm_loc_stock_cost_flag = "";
			$itm_loc_inc_ttloh = "0";
			
			//Select Stock Cost Flag
			 $sql = "SELECT	itm_loc_stock_cost_flag,
							itm_loc_inc_ttloh
					FROM	itm_loc (NOLOCK)
					WHERE	site_cd = '".$site_cd."'
					AND		mst_RowID = ".$ll_Rowid." 
					AND		itm_loc_stk_loc = '".$ls_stk_locn."'";

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

			 if( !$stmt ) {
					sqlsrv_rollback($conn);
					sqlsrv_close($conn);
				  $error_message = "Error Select table (itm_loc)";
				  returnError($error_message);
				  die( print_r( sqlsrv_errors(), true));
			 }

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


			If ($itm_loc_stock_cost_flag == "" OR IS_NULL($itm_loc_stock_cost_flag)){
				$itm_loc_stock_cost_flag = '1';
			}
			
			//Select puo_ls1 cost and qty
			 $sql = "SELECT 'ldc_ord_qty' = COALESCE ( puo_ls1_ord_qty, 0 ),
							'ldc_invoice_qty' = COALESCE ( puo_ls1_invoice_qty, 0 ) ,
							'ldc_rcvd_qty' = COALESCE ( puo_ls1_rcv_qty, 0 ),
							'ldc_rcv_item_cost' = COALESCE ( puo_ls1_item_cost, 0),
							'ldc_ord_retail_price' = COALESCE ( puo_ls1_retail_price, 0),
							puo_ls1_tax_code,
							'ldc_tax_rate' = COALESCE ( puo_ls1_tax_rate, 0 )	
			FROM 		puo_ls1 (NOLOCK)
			WHERE 		( puo_ls1.RowID = '".$ll_po_line_rowid."' )";

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

			 if( !$stmt ) {
					sqlsrv_rollback($conn);
					sqlsrv_close($conn);
				  $error_message = "Error Select table (puo_ls1)";
				  returnError($error_message);
				  die( print_r( sqlsrv_errors(), true));
			 }

			 do {
				 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
					$ldc_ord_qty 		= $row['ldc_ord_qty'];
					$ldc_invoice_qty 	= $row['ldc_invoice_qty'];
					$ldc_rcvd_qty 		= $row['ldc_rcvd_qty'];
					$ldc_rcv_item_cost 	= $row['ldc_rcv_item_cost'];
					$ldc_ord_retail_price 	= $row['ldc_ord_retail_price'];
					$ls_tax			 	= $row['puo_ls1_tax_code'];
					$ldc_tax_rate 		= $row['ldc_tax_rate'];
					
				 }
			} while ( sqlsrv_next_result($stmt) );
			
			if($ldc_tax_rate > 0){
				$ldc_tax_amt = $ldc_rcv_qty * (( $ldc_rcv_item_cost * $ldc_tax_rate ) / 100	);
			}
			
			// To capture the last received date
			//dw_2.SetItem(ll_cnt, "puo_ls1_clo_date", ld_trx_date )	
			
			$ldc_rcv_cost = $ldc_rcv_qty * $ldc_rcv_item_cost;
			if($ldc_rcv_qty > ( $ldc_ord_qty - $ldc_rcvd_qty + $ldc_invoice_qty )){
				$error_message = "Receive quantity cannot be more than the remain quantity";
				returnError($error_message);
				die( print_r( sqlsrv_errors(), true));
			}
			
			$li_grn_line =$li_grn_line +1;
			
			If ($ls_issue_uom == '' ){
				$ls_issue_uom = $ls_rcv_uom;
			}
			
			//Conversion Factor
			if ($ls_issue_uom == "" OR is_null($ls_issue_uom)){
				$ls_issue_uom = $ls_rcv_uom;
			}
			
			if ($ls_rcv_uom <> $ls_issue_uom){
				//Select convertion factor
				 $sql = "SELECT	uom_con_factor
						FROM	uom_con (NOLOCK)
						WHERE	site_cd = '".$site_cd."'
						AND		uom_con_from_uom = '".$ls_rcv_uom."'
						AND		uom_con_to_uom = '".$ls_issue_uom."'";

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

				 if( !$stmt ) {
						sqlsrv_rollback($conn);
						sqlsrv_close($conn);
					  $error_message = "Error Select table (uom_con)";
					  returnError($error_message);
					  die( print_r( sqlsrv_errors(), true));
				 }
					$uom_con_factor = 0;
				 do {
					 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
						$uom_con_factor = $row['uom_con_factor'];			
					}
				} while ( sqlsrv_next_result($stmt) );
				
				if (is_null($uom_con_factor) or $uom_con_factor <= 0 ){
					$uom_con_factor = 1;
				}
				
				$ldc_rcv_conversion_qty = $ldc_rcv_qty * $uom_con_factor;
				$rcv_con_itm_cost = $ldc_rcv_item_cost / $uom_con_factor;
				
			}else{
				$ldc_rcv_conversion_qty = $ldc_rcv_qty;
				$rcv_con_itm_cost = $ldc_rcv_item_cost;
				
			}
			
			$ldc_avg_cost = (( $ldc_tot_oh * $ldc_avg_cost ) + ( $ldc_rcv_cost )) / ( $ldc_tot_oh + $ldc_rcv_conversion_qty );

			$fifo_avg_cost = (( $ldc_tot_oh * $ldc_itm_cost ) + ( $ldc_rcv_cost )) / ( $ldc_tot_oh + $ldc_rcv_conversion_qty );
			
			switch ($ls_cr_code) {

			  case 'AVG':
				$latest_itm_cost = $ldc_avg_cost;	
				break;
			  case 'STD':
				$latest_itm_cost = $ldc_std_cost;
				break;
			  case 'LST':
				$latest_itm_cost = $rcv_con_itm_cost;
				break;
			  case 'FIFO':
				$latest_itm_cost = $fifo_avg_cost;
				break;
			  default:

			}
			
			$latest_issue_price = $latest_itm_cost * ( (100.00 + $surcharge) / 100 );
			
			switch ($itm_loc_stock_cost_flag) {
			  case "1":
				switch ($itm_loc_inc_ttloh) {
				  case "1":
					//update itm_det
					 $sql = "UPDATE 	itm_det
							SET 		itm_det_ttl_oh = COALESCE(itm_det_ttl_oh, 0) + ".$ldc_rcv_conversion_qty.",
										itm_det_item_cost = ".$latest_itm_cost.",
										itm_det_issue_price = ".$latest_issue_price.",				
										itm_det_avg_cost = ".$ldc_avg_cost.",
										itm_det_last_cost = ".$rcv_con_itm_cost.",
										itm_det_lastactdate = GetDate(),
										mbl_audit_user='".$audit_user."',		
										mbl_audit_date=getdate()
							WHERE		( itm_det.mst_RowID = ".$ll_Rowid." )";

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

					 if( !$stmt ) {
							sqlsrv_rollback($conn);
							sqlsrv_close($conn);	
						  $error_message = "Error update table (itm_det 1)";
						  returnError($error_message);
						  die( print_r( sqlsrv_errors(), true));
					 }
					 
					 //update itm_mst
					 $sql = "UPDATE 	itm_mst
							SET 		itm_mst_ttl_oh = COALESCE(itm_mst_ttl_oh, 0) + ".$ldc_rcv_conversion_qty.",	
										itm_mst_issue_price = ".$latest_issue_price.",
										mbl_audit_user='".$audit_user."',		
										mbl_audit_date=getdate()
							WHERE		( itm_mst.RowID = ".$ll_Rowid." ) ";

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

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

					break;
				  case "0":
					//update itm_det
					 $sql = "UPDATE 	itm_det
							SET 		itm_det_due_in = COALESCE(itm_det_due_in, 0) - ".$ldc_rcv_conversion_qty.",		
										itm_det_item_cost = ".$latest_itm_cost.",
										itm_det_issue_price = ".$latest_issue_price.",				
										itm_det_avg_cost = ".$ldc_avg_cost.",
										itm_det_last_cost = ".$rcv_con_itm_cost.",
										itm_det_lastactdate = GetDate(),
										mbl_audit_user='".$audit_user."',		
										mbl_audit_date=getdate()
							WHERE		( itm_det.mst_RowID = ".$ll_Rowid." )";

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

					 if( !$stmt ) {
							sqlsrv_rollback($conn);
							sqlsrv_close($conn);
						  $error_message = "Error update table (itm_det 2)";
						  returnError($error_message);
						  die( print_r( sqlsrv_errors(), true));
					 }
					 
					 //update itm_mst
					 $sql = "UPDATE 	itm_mst
							SET 		itm_mst_issue_price = ".$latest_issue_price.",
										mbl_audit_user='".$audit_user."',		
										mbl_audit_date=getdate()
							WHERE		( itm_mst.RowID = ".$ll_Rowid." ) ";

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

					 if( !$stmt ) {
							sqlsrv_rollback($conn);
							sqlsrv_close($conn);
						  $error_message = "Error update table (itm_mst)";
						  returnError($error_message);
						  die( print_r( sqlsrv_errors(), true));
					 }		
					break;
				  default:
				}
				break;
			  case "0":
				switch ($itm_loc_inc_ttloh) {
				  case "1":
					//update itm_det
					 $sql = "UPDATE 	itm_det
							SET 		itm_det_ttl_oh = COALESCE(itm_det_ttl_oh, 0) + ".$ldc_rcv_conversion_qty.",
										itm_det_ttl_repair = COALESCE(itm_det_ttl_repair, 0) + ".$ldc_rcv_conversion_qty.",			
										itm_det_lastactdate = GetDate(),
										mbl_audit_user='".$audit_user."',		
										mbl_audit_date=getdate()
							WHERE		( itm_det.mst_RowID = ".$ll_Rowid.")";

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

					 if( !$stmt ) {
							sqlsrv_rollback($conn);
							sqlsrv_close($conn);
						  $error_message = "Error update table (itm_det 3)";
						  returnError($error_message);
						  die( print_r( sqlsrv_errors(), true));
					 }
					 
					 //update itm_mst
					 $sql = "UPDATE 	itm_mst
							SET 		itm_mst_ttl_oh = COALESCE(itm_mst_ttl_oh, 0) + ".$ldc_rcv_conversion_qty.",
										mbl_audit_user='".$audit_user."',		
										mbl_audit_date=getdate()
							WHERE		( itm_mst.RowID = ".$ll_Rowid." ) ";

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

					 if( !$stmt ) {
							sqlsrv_rollback($conn);
							sqlsrv_close($conn);
						  $error_message = "Error update table (itm_mst)";
						  returnError($error_message);
						  die( print_r( sqlsrv_errors(), true));
					 }
					break;
				  case "0":
					//update itm_det
					 $sql = "UPDATE 	itm_det
							SET 		itm_det_due_in = COALESCE(itm_det_due_in, 0) - ".$ldc_rcv_conversion_qty.",		
										itm_det_ttl_repair = COALESCE(itm_det_ttl_repair, 0) + ".$ldc_rcv_conversion_qty.",			
										itm_det_lastactdate = GetDate(),
										mbl_audit_user='".$audit_user."',		
										mbl_audit_date=getdate()
							WHERE		( itm_det.mst_RowID = ".$ll_Rowid.")";

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

					 if( !$stmt ) {
							sqlsrv_rollback($conn);
							sqlsrv_close($conn);
						  $error_message = "Error update table (itm_det 4)";
						  returnError($error_message);
						  die( print_r( sqlsrv_errors(), true));
					 }
					break;
				  default:
				}
				break;
			  default:
			}
			
			//update itm_loc_oh_qty
			$sql = "UPDATE 	itm_loc
					SET 	itm_loc_oh_qty = COALESCE(itm_loc_oh_qty, 0) + ".$ldc_rcv_conversion_qty.",
							itm_loc_lastactdate = GetDate(),
							mbl_audit_user='".$audit_user."',		
							mbl_audit_date=getdate()
					WHERE	( itm_loc.mst_RowID = ".$ll_Rowid." ) 
					AND		( itm_loc_stk_loc = '".$ls_stk_locn."' )";

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

			if( !$stmt ) {
				sqlsrv_rollback($conn);
				sqlsrv_close($conn);
			  $error_message = "Error update table (itm_loc_oh_qty)";
			  returnError($error_message);
			  die( print_r( sqlsrv_errors(), true));
			}
			
			//Select original location rom puo_ls1
			 $sql = "SELECT	puo_ls1_stk_locn
					FROM	puo_ls1 (NOLOCK)
					WHERE	site_cd = '".$site_cd."'
					AND		puo_ls1.rowid = ".$ll_po_line_rowid;

			$stmt = sqlsrv_query( $syn_conn, $sql);

			 if( !$stmt ) {
					sqlsrv_rollback($conn);
					sqlsrv_close($conn);
				  $error_message = "Error Select table (puo_ls1)";
				  returnError($error_message);
				  die( print_r( sqlsrv_errors(), true));
			 }

			 do {
				 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
					$stock_location_org = $row['puo_ls1_stk_locn'];			
				}
			} while ( sqlsrv_next_result($stmt) );
			
			//update itm_loc_due_in
			$sql = "UPDATE 	itm_loc
					SET 	itm_loc_due_in = COALESCE(itm_loc_due_in, 0) + ".$ldc_rcv_conversion_qty.",
							itm_loc_lastactdate = GetDate(),
							mbl_audit_user='".$audit_user."',		
							mbl_audit_date=getdate()
					WHERE	( itm_loc.mst_RowID = ".$ll_Rowid." ) 
					AND		( itm_loc_stk_loc = '".$stock_location_org."' )";

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

			if( !$stmt ) {
				sqlsrv_rollback($conn);
				sqlsrv_close($conn);
			  $error_message = "Error update table (itm_loc_due_in )";
			  returnError($error_message);
			  die( print_r( sqlsrv_errors(), true));
			}
			
			//insert itm_trx
			$sql_insert_itm_trx = "INSERT INTO itm_trx 
				( 	site_cd,						itm_trx_doc_no, 				itm_trx_trx_type, 				itm_trx_curr_date, 				itm_trx_trx_date,
					itm_trx_isu_empl_id,			itm_trx_rcv_empl_id, 			itm_trx_stockno, 				itm_trx_desc, 					itm_trx_partno,				
					itm_trx_com_code,				itm_trx_isu_qty, 				itm_trx_rcv_qty,				itm_trx_ord_qty, 				itm_trx_rtn_qty, 			
					itm_trx_bo_qty, 				itm_trx_chg_costcenter, 		itm_trx_chg_account, 			itm_trx_crd_costcenter,			itm_trx_crd_account,		
					itm_trx_assetno, 				itm_trx_wo, 					itm_trx_mtlrqnnum, 				itm_trx_item_cost, 				itm_trx_uom, 				
					itm_trx_cnv_qty,				itm_trx_pkguom, 				itm_trx_ext_cost, 				itm_trx_porqnnum, 				itm_trx_approver, 			
					itm_trx_supplier, 				itm_trx_pono, 					itm_trx_po_lineno,				itm_trx_ttl_oh, 				itm_trx_stk_locn, 			
					itm_trx_oh_qty, 				itm_trx_comments, 				itm_trx_to_stk_locn, 			itm_trx_mtlrqn_lineno, 			itm_trx_grn_no, 			
					itm_trx_grn_itm_no, 			itm_trx_posted, 				itm_trx_avg_cost, 				itm_trx_std_cost, 				itm_trx_last_cost, 			
					itm_trx_consigned, 				itm_trx_receive_doc_note,		itm_trx_inv_qty, 				itm_trx_inv_uom,				itm_trx_liability_acc, 		
					itm_trx_raw_cost, 				itm_trx_rcv_cost, 				itm_trx_rcv_date, 				itm_trx_pkg_slip_no, 			itm_trx_mt_special_idno,
					itm_trx_cost_cat_id, 			itm_trx_mtcs_ref_id, 			itm_trx_return_fee, 			itm_trx_mtrtnsup_ref_id,		itm_trx_mtrtnsup_lineno,	
					itm_trx_mtns_ref_id, 			itm_trx_inv_id, 				itm_trx_inv_lineno,				itm_trx_rev_inv, 				itm_trx_ret_supp, 			
					itm_trx_mkey, 					itm_trx_status,					itm_trx_projectid, 				itm_trx_login_id, 				itm_trx_cnx_qty, 			
					itm_trx_fifo_avg_cost,      	itm_trx_remark,					audit_user,                   	audit_date,						mbl_audit_user,
					mbl_audit_date ) 
			VALUES 
				( 	'".$site_cd."',					'".$doc_no."', 					'MT41', 						GetDate(),						'".$ld_trx_date."',				
					'',								'".$ls_empl_id."',				'".$ls_stock_no."',				'".$ls_desc."',					'', 					
					'',								0,								".$ldc_rcv_qty.",				0,								0,						
					0,								'".$ls_chg_costcenter."',		'".$ls_chg_account."',			'".$ls_crd_costcenter."',		'".$ls_crd_account."',						
					'',								'',								0,								".$ldc_rcv_item_cost.",			'".$ls_rcv_uom."',         
					".$ldc_rcv_conversion_qty.",				'',								".$ldc_rcv_cost.",					'',								'',						
					'".$ls_supplier."',				'',								".$ll_po_lineno.",				0,								'".$ls_stk_locn."',	
					0,								'',								'',								0,								'".$doc_no."',			
					".$li_grn_line.",				'',								".$ldc_avg_cost.",				".$ldc_std_cost.",				".$rcv_con_itm_cost.",	
					'',								0,								NULL,							'',								'',						
					0,								0,								0,								'".$ls_pkg_slip."',				'',						
					'',								0,								0,								0,								0,						
					0,								0,								0,								'',								'',						
					'',								'',								'".$ls_project."',				'".$audit_user."',				0,						
					".$fifo_avg_cost.",            	'".$ls_remark."',				'".$audit_user."',        		GetDate(),						'".$audit_user."',      
					GetDate() )";                                                                                                                                            
																																											 
			$stmt_insert_itm_trx = sqlsrv_query( $conn, $sql_insert_itm_trx);	                                                                                             
																																											 
																																											 
			if( !$stmt_insert_itm_trx ) {     
					sqlsrv_rollback($conn);
					sqlsrv_close($conn);			
				 $error_message = "Error insert table (itm_trx)";                                                                                                            
				 returnError($error_message);                                                                                                                                
				 die( print_r( sqlsrv_errors(), true));                                                                                                                      
			}                                                                                                                                                                
																																											 
			//insert itm_mtr                                                                                                                                                 
			$sql_insert_itm_mtr = "INSERT INTO itm_mtr
				( 	site_cd,							itm_mtr_doc_no,					itm_mtr_stockno,				itm_mtr_stk_locn,				itm_mtr_desc,
					itm_mtr_partno,						itm_mtr_rcv_date,				itm_mtr_rcv_qty,				itm_mtr_rcv_uom,				itm_mtr_item_cost,			
					itm_mtr_chg_costcenter,				itm_mtr_chg_account,			itm_mtr_crd_costcenter ,		itm_mtr_crd_account,			itm_mtr_tax_account, 			
					itm_mtr_pr_no,						itm_mtr_pr_lineno,				itm_mtr_po_no,					itm_mtr_po_lineno,				itm_mtr_supplier,				
					itm_mtr_pkg_slip_no,				itm_mtr_wo_no,					itm_mtr_activity_code,			itm_mtr_tax_cd,					audit_user,						
					audit_date,							mbl_audit_user,					mbl_audit_date  	)
			VALUES 
				( 	'".$site_cd."',						'".$doc_no."', 					'".$ls_stock_no."',				'".$ls_stk_locn."',				'".$ls_desc."',
					'',                           		GETDATE(),                  	".$ldc_rcv_qty.",            	'".$ls_rcv_uom."',     			".$ldc_rcv_item_cost.",
					'".$ls_chg_costcenter."',			'".$ls_chg_account."',			'".$ls_crd_costcenter."',		'".$ls_crd_account."',			'".$ls_input_acc."',			
					'',									0,								'".$ls_po_no."',				".$ll_po_lineno.",				'".$ls_supplier."',								
					'".$ls_pkg_slip."',					'',								'',								'".$ls_tax."',			 		'".$audit_user."',				
					GetDate(),							'".$audit_user."',				GetDate() ) ";

			$stmt_insert_itm_mtr = sqlsrv_query( $conn, $sql_insert_itm_mtr);				
							
			if( !$stmt_insert_itm_mtr ) {
				sqlsrv_rollback($conn);
				sqlsrv_close($conn);
				 $error_message = "Error insert table (itm_mtr)";
				 returnError($error_message);
				 die( print_r( sqlsrv_errors(), true));
			}
			sqlsrv_free_stmt($stmt_insert_itm_mtr);


			//insert itm_mtc
			$sql_insert_itm_mtc = "INSERT INTO itm_mtc
									( 	site_cd,				itm_mtc_grn_no,					itm_mtc_grn_itm_no,				itm_mtc_rcv_date,				itm_mtc_rcv_empl_id, 		
										itm_mtc_stockno,		itm_mtc_stk_locn,				itm_mtc_uom,					itm_mtc_costcenter,				itm_mtc_account,				
										itm_mtc_crd_costcenter,	itm_mtc_crd_account,			itm_mtc_tax_account,			itm_mtc_pono,					itm_mtc_po_lineno,				
										itm_mtc_nonstkitm,		itm_mtc_rcv_qty,				itm_mtc_rcv_cost,				itm_mtc_isu_qty,				itm_mtc_inv_qty,				
										itm_mtc_inv_cost,		itm_mtc_tax_cd,					itm_mtc_tax_rate,				audit_user,						audit_date,						
										mbl_audit_user,			mbl_audit_date  	)
									VALUES 
								   (    '".$site_cd."',         '".$doc_no."',                	".$li_grn_line.",               GETDATE(),                 		'".$ls_empl_id."',                  
										'".$ls_stock_no."',		'".$ls_stk_locn."',				'".$ls_issue_uom."',			'".$ls_chg_costcenter."',		'".$ls_chg_account."',	
										'".$ls_crd_costcenter."','".$ls_crd_account."',			'".$ls_input_acc."',			'',								".$ll_po_lineno.",							
										'N',					".$ldc_rcv_conversion_qty.",				".$rcv_con_itm_cost.",			0,								0,								
										".$rcv_con_itm_cost.",	'".$ls_tax."',					".$ldc_tax_rate.",				'".$audit_user."',				GetDate(),						
										'".$audit_user."',		GetDate() 	)	";

			$stmt_insert_itm_mtc = sqlsrv_query( $conn, $sql_insert_itm_mtc);				
							
			if( !$stmt_insert_itm_mtc ) {
				sqlsrv_rollback($conn);
				sqlsrv_close($conn);
				 $error_message = "Error insert table (itm_mtc 1)";
				 returnError($error_message);
				 die( print_r( sqlsrv_errors(), true));
			}
			sqlsrv_free_stmt($stmt_insert_itm_mtc);
			
			$ldc_rcvd_qty = $ldc_rcvd_qty + $ldc_rcv_qty;
			$ldc_bo_qty = $ldc_ord_qty - $ldc_rcv_qty;
			
			//update puo_ls1
			$sql_update_puo_ls1 = "UPDATE 	puo_ls1
									SET 	puo_ls1_item_cost 		= ".$ldc_rcv_item_cost.",
											puo_ls1_retail_price 	= ".$ldc_ord_retail_price.",
											puo_ls1_ord_qty 		= ".$ldc_ord_qty.",
											puo_ls1_rcv_qty 		= ".$ldc_rcvd_qty.",
											puo_ls1_bo_qty 			= ".$ldc_bo_qty.",
											puo_ls1_clo_date 		= '".$ld_trx_date."',
											mbl_audit_user			='".$audit_user."',		
											mbl_audit_date			=getdate()
									WHERE	( puo_ls1.rowid = ".$ll_po_line_rowid." )";

			$stmt_update_puo_ls1 = sqlsrv_query( $conn, $sql_update_puo_ls1);

			if( !$stmt_update_puo_ls1 ) {
				sqlsrv_rollback($conn);
				sqlsrv_close($conn);
			  $error_message = "Error update table (puo_ls1 )";
			  returnError($error_message);
			  die( print_r( sqlsrv_errors(), true));
			}
			
			if ($ls_serialize_flg == '1'){
				for ($ll_serial_cnt = 1; $ll_serial_cnt <= $ldc_rcv_conversion_qty; $ll_serial_cnt++){
					if ($ls_auto_serialize_flg == '1'){
						$serial_no = $ls_stock_no.strval($ll_serialize_counter);
						//insert itm_ser
						$sql_insert_itm_ser = "INSERT INTO itm_ser
							( 	site_cd,					mst_RowID,					itm_ser_serial_no,			itm_ser_stk_loc,				itm_ser_create_date,
								itm_ser_warranty_date,		itm_ser_item_cost,			itm_ser_oh_qty,				itm_ser_supplier,				itm_ser_varchar1,
								audit_user,					audit_date,					itm_ser_repair_cost,		itm_ser_total_repair_cost,		itm_ser_total_repair,
								itm_ser_total_attach,		mbl_audit_user,				mbl_audit_date )
						VALUES
							(	'".$site_cd."',				".$ll_Rowid.",				'".$serial_no."',			'".$ls_stk_locn."',				GetDate(),
								NULL,						".$rcv_con_itm_cost.",		1,							'".$ls_supplier."',				'0',
								'".$audit_user."',			GetDate(),					0,							0,								0,
								0,							'".$audit_user."',			GetDate())";

						$stmt_insert_itm_ser = sqlsrv_query( $conn, $sql_insert_itm_ser);				
										
						if( !$stmt_insert_itm_ser ) {
							sqlsrv_rollback($conn);
							sqlsrv_close($conn);
							 $error_message = "Error insert table (itm_ser)";
							 returnError($error_message);
							 die( print_r( sqlsrv_errors(), true));
						}
						
						sqlsrv_free_stmt($stmt_insert_itm_ser);
						
					}
					$ll_serialize_counter = $ll_serialize_counter + 1;
				}
				
				//update itm_mst
				$sql_update_itm_mst = "UPDATE 	itm_mst
										SET		itm_mst_serialize_counter = ".$ll_serialize_counter.",
												mbl_audit_user='".$audit_user."',		
												mbl_audit_date=getdate()
										WHERE	itm_mst.RowID = ".$ll_Rowid;

				$stmt_update_itm_mst = sqlsrv_query( $conn, $sql_update_itm_mst);				
								
				if( !$stmt_update_itm_mst ) {
					sqlsrv_rollback($conn);
					sqlsrv_close($conn);
					 $error_message = "Error update table (itm_mst)";
					 returnError($error_message);
					 die( print_r( sqlsrv_errors(), true));
				}
				
				sqlsrv_free_stmt($stmt_update_itm_mst);

			}
			
			$charge_valid = f_update_budget($site_cd, $ld_trx_date, $ls_chg_costcenter, $ls_chg_account, "CHARGE", $ldc_rcv_cost, $conn, $audit_user);
			$charge_valid = f_update_budget($site_cd, $ld_trx_date, $ls_chg_costcenter, $ls_input_acc, "CHARGE", $ldc_tax_amt, $conn, $audit_user);
			
			$charge_valid = f_update_budget($site_cd, $ld_trx_date, $ls_crd_costcenter, $ls_crd_account, "CREDIT", $ldc_rcv_cost + $ldc_tax_amt, $conn, $audit_user);
			
			$charge_valid = f_update_purchase_budget($site_cd, $ld_po_date, $ls_pr_chg_costcenter, $ls_pr_chg_account, "MINUS_PO", $ldc_rcv_cost, $conn, $audit_user);
			
			
			/*Update Work Order and Asset Cost */
			if(strlen($ls_wo ?? '') > 0){
				$sql = "SELECT 	'll_wko_rowid' = wko_mst.rowid
						FROM 	wko_mst (NOLOCK)
						WHERE 	site_cd = '".$site_cd."'
						AND		wko_mst_wo_no	= '".$ls_wo."'";

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

				if( !$stmt ) {
					sqlsrv_rollback($conn);
					sqlsrv_close($conn);
					 $error_message = "Error select table (wko_mst.rowid)";
					 returnError($error_message);
					 die( print_r( sqlsrv_errors(), true));
				}

				do {
					 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
						$ll_wko_rowid = $row['ll_wko_rowid'];	
					
					 }
				} while ( sqlsrv_next_result($stmt) );	
				
				
				
				
				/*Update Work Order Actual Cost*/
				If ($ls_category == "Material"){
					$sql_update_itm_mst = "UPDATE	wko_det
											SET 	wko_det_mtl_cost = COALESCE(wko_det_mtl_cost ,0) + ".$ldc_rcv_cost."  
											WHERE 	wko_det.mst_RowID = ".$ll_wko_rowid."";

					$stmt_update_itm_mst = sqlsrv_query( $conn, $sql_update_itm_mst);				
									
					if( !$stmt_update_itm_mst ) {
						sqlsrv_rollback($conn);
						sqlsrv_close($conn);
						 $error_message = "Error update table (wko_det)";
						 returnError($error_message);
						 die( print_r( sqlsrv_errors(), true));
					}
					
					
					$ls_assetno = '';

					 $sql = "SELECT	'ls_assetno' = wko_ls3_assetno
							FROM		wko_ls3 (NOLOCK)
							WHERE	site_cd = '".$site_cd."'
							AND		mst_RowID = ".$ll_wko_rowid." 
							AND		wko_ls3_pr_no = '".$ls_pr."' 
							AND		wko_ls3_pr_lineno = ".$ll_pr_lineno."";

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

					 if( !$stmt ) {
							sqlsrv_rollback($conn);
							sqlsrv_close($conn);
						  $error_message = "Error Select table (wko_ls3)";
						  returnError($error_message);
						  die( print_r( sqlsrv_errors(), true));
					 }

					 do {
						 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
							$ls_assetno = $row['ls_assetno'];			
						}
					} while ( sqlsrv_next_result($stmt) );
					
					
					/*Update Asset Actual Cost*/
					if (strlen($ls_stock_no ?? '') > 0) {
						//Select asset rowid
						$sql = "SELECT	'll_ast_RowID' = RowID
								FROM	ast_mst (NOLOCK)
								WHERE	site_cd = '".$site_cd."'
								AND		ast_mst_asset_no = '".$ls_assetno."'";

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

						 if( !$stmt ) {
								sqlsrv_rollback($conn);
								sqlsrv_close($conn);
							  $error_message = "Error Select table (ast_mst)";
							  returnError($error_message);
							  die( print_r( sqlsrv_errors(), true));
						 }

						 do {
							 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
								$ll_ast_RowID = $row['ll_ast_RowID'];			
							}
						} while ( sqlsrv_next_result($stmt) );
						
						$sql_update_itm_mst = "UPDATE 	ast_det
												SET 	ast_det_ltdmtlcost = COALESCE(ast_det_ltdmtlcost ,0) + ".$ldc_rcv_cost." 
												WHERE 	ast_det.mst_RowID = ".$ll_ast_RowID."";

						$stmt_update_itm_mst = sqlsrv_query( $conn, $sql_update_itm_mst);				
										
						if( !$stmt_update_itm_mst ) {
							sqlsrv_rollback($conn);
							sqlsrv_close($conn);
							 $error_message = "Error update table (ast_det)";
							 returnError($error_message);
							 die( print_r( sqlsrv_errors(), true));
						}
					}
					
				}elseif($ls_category == "Service"){
					$sql_update_itm_mst = "UPDATE	wko_det
											SET 	wko_det_con_cost = COALESCE(wko_det_con_cost ,0) + ".$ldc_rcv_cost."  
											WHERE 	wko_det.mst_RowID = ".$ll_wko_rowid."";

					$stmt_update_itm_mst = sqlsrv_query( $conn, $sql_update_itm_mst);				
									
					if( !$stmt_update_itm_mst ) {
						sqlsrv_rollback($conn);
						sqlsrv_close($conn);
						 $error_message = "Error update table (wko_det)";
						 returnError($error_message);
						 die( print_r( sqlsrv_errors(), true));
					}
					
					$ls_assetno = '';
					
					 $sql = "SELECT	'ls_assetno' = wko_ls4_assetno
							FROM		wko_ls4 (NOLOCK)
							WHERE	site_cd = '".$site_cd."'
							AND		mst_RowID = ".$ll_wko_rowid." 
							AND		wko_ls4_pr_no = '".$ls_pr."' 
							AND		wko_ls4_pr_lineno = ".$ll_pr_lineno."";

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

					 if( !$stmt ) {
							sqlsrv_rollback($conn);
							sqlsrv_close($conn);
						  $error_message = "Error Select table (wko_ls4)";
						  returnError($error_message);
						  die( print_r( sqlsrv_errors(), true));
					 }

					 do {
						 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
							$ls_assetno = $row['ls_assetno'];			
						}
					} while ( sqlsrv_next_result($stmt) );
					
					
					/*Update Asset Actual Cost*/
					if (strlen($ls_stock_no ?? '') > 0) {
						//Select asset rowid
						$sql = "SELECT	'll_ast_RowID' = RowID
								FROM	ast_mst (NOLOCK)
								WHERE	site_cd = '".$site_cd."'
								AND		ast_mst_asset_no = '".$ls_assetno."'";

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

						 if( !$stmt ) {
							sqlsrv_rollback($conn);
							sqlsrv_close($conn);
							  $error_message = "Error Select table (ast_mst)";
							  returnError($error_message);
							  die( print_r( sqlsrv_errors(), true));
						 }

						 do {
							 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
								$ll_ast_RowID = $row['ll_ast_RowID'];			
							}
						} while ( sqlsrv_next_result($stmt) );
						
						$sql_update_itm_mst = "UPDATE 	ast_det
												SET 	ast_det_ltdconcost = COALESCE(ast_det_ltdconcost ,0) + ".$ldc_rcv_cost." 
												WHERE 	ast_det.mst_RowID = ".$ll_ast_RowID."";

						$stmt_update_itm_mst = sqlsrv_query( $conn, $sql_update_itm_mst);				
										
						if( !$stmt_update_itm_mst ) {
							sqlsrv_rollback($conn);
							sqlsrv_close($conn);
							 $error_message = "Error update table (ast_det)";
							 returnError($error_message);
							 die( print_r( sqlsrv_errors(), true));
						}
					}
				}
			}//if(strlen($ls_wo))
				
			//Count itm_sup
			$sql = "SELECT	'll_sup_cnt' = COUNT(*)
					FROM	itm_sup (NOLOCK)
					WHERE	site_cd = '".$site_cd."'
					AND 	mst_RowID = ".$ll_Rowid."
					AND		itm_sup_supplier = '".$ls_supplier."'";

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

			 if( !$stmt ) {
					sqlsrv_rollback($conn);
					sqlsrv_close($conn);
				  $error_message = "Error Select table (ast_mst)";
				  returnError($error_message);
				  die( print_r( sqlsrv_errors(), true));
			 }

			 do {
				 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
					$ll_sup_cnt = $row['ll_sup_cnt'];			
				}
			} while ( sqlsrv_next_result($stmt) );
			
			if ($ll_sup_cnt == 0){
				//Increase 1
				//Count itm_sup
				$sql = "SELECT	'li_cnt' = COUNT(*) + 1
						FROM	itm_sup (NOLOCK)
						WHERE	site_cd = '".$site_cd."'
						AND 	mst_RowID = ".$ll_Rowid."";

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

				 if( !$stmt ) {
						sqlsrv_rollback($conn);
						sqlsrv_close($conn);
					  $error_message = "Error Select table (itm_sup)";
					  returnError($error_message);
					  die( print_r( sqlsrv_errors(), true));
				 }

				 do {
					 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
						$li_cnt = $row['li_cnt'];			
					}
				} while ( sqlsrv_next_result($stmt) );
				
				//Insert supplier
				$sql_insert_sup = "INSERT itm_sup (	
				site_cd,							mst_RowID,						itm_sup_curr_code,			itm_sup_last_itemcost,		itm_sup_supplier,
				itm_sup_last_rcvd_date,				itm_sup_supplier_partno,		itm_sup_avg_leadtime, 		itm_sup_min_orderqty,		itm_sup_order_uom,
				itm_sup_rcpts_ctr,					itm_sup_retail_price,			itm_sup_discount_pct,		itm_sup_partmfg,			itm_sup_mfgrank,
				itm_sup_plan_leadtime,				itm_sup_mfg_partno,				itm_sup_ord_qty,			itm_sup_rcv_qty,			itm_sup_late_qty,
				itm_sup_high_qty,					itm_sup_di,						itm_sup_ci,					audit_user,					audit_date,			
				mbl_audit_user,						mbl_audit_date	)
				VALUES (				
				'".$site_cd."',						".$ll_Rowid.",					NULL,						".$ldc_rcv_item_cost.",		'".$ls_supplier."',
				'".$ld_trx_date."',					NULL,							NULL,						0,							'".$ls_rcv_uom."',
				0,									".$ldc_ord_retail_price.",		0,							NULL,						".$li_cnt.",
				0,									NULL,							".$ldc_ord_qty.",			".$ldc_rcv_qty.",			0,
				0,									0,								0,							'".$audit_user."',			getdate(),	
				'".$audit_user."',					getdate() )";

				$stmt_insert_sup = sqlsrv_query( $conn, $sql_insert_sup);				
								
				if( !$stmt_insert_sup ) {
						sqlsrv_rollback($conn);
						sqlsrv_close($conn);
					 $error_message = "Error insert table (itm_sup)";
					 returnError($error_message);
					 die( print_r( sqlsrv_errors(), true));
				}
				
				sqlsrv_free_stmt($stmt_insert_sup);
				
			}else{
				if ($ll_sup_cnt == 1){
				
					//Update itm_sup
					$sql_supplier_ttl_count = "UPDATE 	itm_sup
												SET		itm_sup_tax_cd = '".$ls_tax."',
														itm_sup_last_itemcost = ".$ldc_rcv_item_cost." ,
														itm_sup_retail_price = ".$ldc_ord_retail_price." ,
														itm_sup_last_rcvd_date = '".$ld_trx_date."',
														itm_sup_order_uom = '".$ls_rcv_uom."',
														itm_sup_ord_qty = ".$ldc_ord_qty.",
														itm_sup_rcv_qty = ".$ldc_rcv_qty.",
														mbl_audit_user='".$audit_user."',		
														mbl_audit_date=getdate()
												WHERE 	( itm_sup.mst_RowID = ".$ll_Rowid." )
												AND		( itm_sup_supplier = '".$ls_supplier."' )";

					$stmt_supplier_ttl_count = sqlsrv_query( $conn, $sql_supplier_ttl_count);				
									
					if( !$stmt_supplier_ttl_count ) {
						sqlsrv_rollback($conn);
						sqlsrv_close($conn);
						 $error_message = "Error update table (itm_sup)";
						 returnError($error_message);
						 die( print_r( sqlsrv_errors(), true));
					}
					
					sqlsrv_free_stmt($stmt_supplier_ttl_count);
				}
			}//if ($ll_sup_cnt == 0)
				
			// Auto Update Quotation from PR
			
			if (empty($ll_pr_lineno)){
				$ll_pr_lineno = 'NULL';
			}
			
			$sql = "SELECT	'll_quo_cnt' = COUNT(*)
					FROM	pur_mst (NOLOCK),
							pur_ls1 (NOLOCK),
							quo_mst (NOLOCK)
					WHERE		pur_mst.site_cd = pur_ls1.site_cd
					AND			pur_mst.RowID = pur_ls1.mst_RowID
					AND			pur_ls1.site_cd = quo_mst.site_cd
					AND			pur_ls1.pur_ls1_quo_no = quo_mst.quo_mst_quo_cd
					AND			quo_mst.quo_mst_select_flag  = '1'
					AND			Len(quo_mst.attachment_desc) > 0
					AND			pur_mst.pur_mst_porqnnum = '".$ls_pr."'
					AND			pur_ls1.pur_ls1_pr_lineno = ".$ll_pr_lineno."
					AND			quo_mst.quo_mst_supplier_cd = '".$ls_supplier."'";

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

			 if( !$stmt ) {
					sqlsrv_rollback($conn);
					sqlsrv_close($conn);
				  $error_message = "Error Select table (pur_mst, pur_ls1, quo_mst  count)";
				  returnError($error_message);
				  die( print_r( sqlsrv_errors(), true));
			 }

			 do {
				 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
					$ll_quo_cnt = $row['ll_quo_cnt'];			
				}
			} while ( sqlsrv_next_result($stmt) );
			
			if ($ll_quo_cnt == 1) {
				//Select quo
				$sql = "SELECT	'ls_attach_desc' = quo_mst.attachment_desc,
								'll_ref_rowid' = quo_mst.RowID
						FROM	pur_mst (NOLOCK),
								pur_ls1 (NOLOCK),
								quo_mst (NOLOCK)
						WHERE		pur_mst.site_cd = pur_ls1.site_cd
						AND			pur_mst.RowID = pur_ls1.mst_RowID
						AND			pur_ls1.site_cd = quo_mst.site_cd
						AND			pur_ls1.pur_ls1_quo_no = quo_mst.quo_mst_quo_cd
						AND			quo_mst.quo_mst_select_flag  = '1'
						AND			Len(quo_mst.attachment_desc) > 0
						AND			pur_mst.pur_mst_porqnnum = '".$ls_pr."'
						AND			pur_ls1.pur_ls1_pr_lineno = ".$ll_pr_lineno."
						AND			quo_mst.quo_mst_supplier_cd = '".$ls_supplier."'";

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

				 if( !$stmt ) {
						sqlsrv_rollback($conn);
						sqlsrv_close($conn);
					  $error_message = "Error Select table (pur_mst, pur_ls1, quo_mst)";
					  returnError($error_message);
					  die( print_r( sqlsrv_errors(), true));
				 }

				 do {
					 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
						$ls_attach_desc = $row['ls_attach_desc'];			
						$ll_ref_rowid = $row['ll_ref_rowid'];			
					}
				} while ( sqlsrv_next_result($stmt) );
				
				//Update itm_sup by copying the attachment
				$sql_update_itm_sup_att = "UPDATE 	itm_sup
											SET		itm_sup_file_name = '".$ls_attach_desc."',
													itm_sup.attachment = (Select attachment from quo_mst (NOLOCK) where rowid = '".$ll_ref_rowid."')
													mbl_audit_user='".$audit_user."',		
													mbl_audit_date=getdate()
											WHERE 	( itm_sup.mst_RowID = ".$ll_Rowid." )
											AND		( itm_sup_supplier = '".$ls_supplier."' )";

				$stmt_update_itm_sup_att = sqlsrv_query( $conn, $sql_update_itm_sup_att);				
								
				if( !$stmt_update_itm_sup_att ) {
					sqlsrv_rollback($conn);
					sqlsrv_close($conn);
					 $error_message = "Error update table (itm_sup)";
					 returnError($error_message);
					 die( print_r( sqlsrv_errors(), true));
				}
				
				sqlsrv_free_stmt($stmt_update_itm_sup_att);
				
				
			}//if ($ll_quo_cnt == 1)
				
			//Clear Shortage
			f_clear_shortage($site_cd, $is_mr_reserver, $ls_stock_no, $ll_Rowid, $ls_stk_locn, $ldc_rcv_conversion_qty, $conn);
			
		}//ldc_rcv_qty > 0
	} //For Loop
	
	if ($is_auto_close == '1'){
		if ($ll_po_rowid > 0 ) {
			//Select ldc_balance_qty
			$sql = "SELECT	'ldc_balance_qty' = SUM(COALESCE(puo_ls1.puo_ls1_ord_qty, 0)  - (COALESCE(puo_ls1.puo_ls1_rcv_qty, 0) - COALESCE ( puo_ls1_invoice_qty, 0 )))
					FROM	puo_ls1 (NOLOCK)
					WHERE	site_cd = '".$site_cd."' 
					AND		mst_rowid = ".$ll_po_rowid."";
				
			$stmt = sqlsrv_query( $conn, $sql);

			 if( !$stmt ) {
					sqlsrv_rollback($conn);
					sqlsrv_close($conn);
				  $error_message = "Error Select table (puo_ls1)";
				  returnError($error_message);
				  die( print_r( sqlsrv_errors(), true));
			 }

			 do {
				 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
					$ldc_balance_qty = $row['ldc_balance_qty'];			
				}
			} while ( sqlsrv_next_result($stmt) );
			
			if($ldc_balance_qty == 0){
				$sql = "SELECT 	TOP 1 puo_sts_status,
									puo_sts_description
						FROM		puo_sts (NOLOCK)
						WHERE 	site_cd = '".$site_cd."'
						AND		puo_sts_st_cat_cd = 'PO'
						AND		puo_sts_status_type = 'CLOSE'";
					
				$stmt = sqlsrv_query( $conn, $sql);

				 if( !$stmt ) {
						sqlsrv_rollback($conn);
						sqlsrv_close($conn);
					  $error_message = "Error Select table (puo_ls1)";
					  returnError($error_message);
					  die( print_r( sqlsrv_errors(), true));
				 }

				 do {
					 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
						$ls_close_sts = $row['puo_sts_status'];			
						$puo_sts_description = $row['puo_sts_description'];			
					}
				} while ( sqlsrv_next_result($stmt) );
				
				if (strlen($ls_close_sts ?? '') > 0){
					//Update puo_mst
					$sql_update_puo_mst	 = "UPDATE 	puo_mst
												SET 	puo_mst_status = '".$ls_close_sts."',
														puo_mst_clo_date = GetDate()
												WHERE 	site_cd = '".$site_cd."'
												AND		RowID = ".$ll_po_rowid."";

					$stmt_update_puo_mst = sqlsrv_query( $conn, $sql_update_puo_mst);				
									
					if( !$stmt_update_puo_mst ) {
						sqlsrv_rollback($conn);
						sqlsrv_close($conn);
						 $error_message = "Error update table (puo_mst)";
						 returnError($error_message);
						 die( print_r( sqlsrv_errors(), true));
					}
					
					sqlsrv_free_stmt($stmt_update_puo_mst);
					
					//Update puo_ls2
					$sql_update_puo_ls2	 = "UPDATE	puo_ls2	
											SET		puo_ls2_datetime2 = GetDate(),
														puo_ls2_numeric1 = 0,
														audit_user = '".$audit_user."' ,
														audit_date = GetDate()
											WHERE	site_cd = '".$site_cd."'
											AND		puo_ls2_varchar1 = '".$ls_po_no."'
											AND		puo_ls2_varchar2 = '".$ls_po_status."'";

					$stmt_update_puo_ls2 = sqlsrv_query( $conn, $sql_update_puo_ls2);				
									
					if( !$stmt_update_puo_mst ) {
						sqlsrv_rollback($conn);
						sqlsrv_close($conn);
						 $error_message = "Error update table (puo_ls2)";
						 returnError($error_message);
						 die( print_r( sqlsrv_errors(), true));
					}
					
					sqlsrv_free_stmt($stmt_update_puo_ls2);
					
					//Insert puo_ls2
					$sql_insert_puo_ls2	 = "INSERT 	puo_ls2 (	site_cd ,			mst_RowID,				puo_ls2_varchar1 ,				puo_ls2_varchar2 ,					puo_ls2_varchar3 ,
																puo_ls2_datetime1 ,	puo_ls2_datetime2 ,		puo_ls2_numeric1 ,				audit_user ,    					audit_date ) 		
					VALUES	(									'".$site_cd."' ,	".$ll_po_rowid.",		'".$ls_po_no."' ,				'".$ls_close_sts."' ,				'".$audit_user."' ,
																GetDate(),			NULL,					NULL,							'".$audit_user."' ,					GetDate())";

					$stmt_insert_puo_ls2 = sqlsrv_query( $conn, $sql_insert_puo_ls2);				
									
					if( !$stmt_insert_puo_ls2 ) {
						sqlsrv_rollback($conn);
						sqlsrv_close($conn);
						 $error_message = "Error insert table (puo_ls2)";
						 returnError($error_message);
						 die( print_r( sqlsrv_errors(), true));
					}
					
					sqlsrv_free_stmt($stmt_insert_puo_ls2);
					
				}else{
					//update puo_mst
					$sql_update_puo_mst	 = "UPDATE 	puo_mst
											SET 		puo_mst_clo_date = GetDate()
											WHERE 	site_cd = '".$site_cd."'
											AND		RowID = ".$ll_po_rowid." ";

					$stmt_update_puo_mst = sqlsrv_query( $conn, $sql_update_puo_mst);				
									
					if( !$stmt_update_puo_mst ) {
						sqlsrv_rollback($conn);
						sqlsrv_close($conn);
						 $error_message = "Error update table (puo_mst)";
						 returnError($error_message);
						 die( print_r( sqlsrv_errors(), true));
					}
					
					sqlsrv_free_stmt($stmt_update_puo_mst);
					
				}
			}
		}
	}
	sqlsrv_free_stmt( $stmt);
	sqlsrv_commit($conn);
    sqlsrv_close($conn);
	
	
	
	returnData($doc_no);	
}



function returnData($doc_no){
	
	$returnData = array(
	'status' => 'SUCCESS',
	'message' => 'The PO line receive successfully ' . $doc_no . '');
	
	echo json_encode($returnData);
}

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

?>