<?php
require_once('config.php');
require_once('f_update_budget.php');
$error_message;
$valid = true;


$json = file_get_contents('php://input');
$result = json_decode($json);


$validateStockAvailability = validateStockAvailability($conn, $json);

if ($validateStockAvailability === true) {
    // Proceed with next steps
	
		
	$ll_row = 0;
	$mtr_mst_mtr_no;
	$ldc_tot_cost = 0;
	$first_row = true;
	
		
		//Header
		$site_cd;
		$itm_mst_rowid;
		$mtr_mst_rowid;
		$mtr_no;
		$wo_no;
		$asset_no;
		$mst_costcenter;
		$mst_account;
		$audit_user;
		$isu_empl_id;
		$mr_status;
		$remark;
		$issue_date = date("Y-m-d h:i:s");
		$doc_no = '';

		//details
		$mst_RowID;
		$stock_no;
		$mtr_ls1_desc;
		$stock_location;
		$cost_center;
		$account;
		$issue_qty;
		$mtr_ls1_mtr_lineno;
		$serial;
		$lslRow_ID;

		//After 
		$ttl_oh_qty;
		$itm_oh_qty;
		$itm_RowID;
		$itm_lockout;
		$latest_itm_cost;
		$latest_issue_price;
		$surcharge = 0;
		$raw_cost;
		$ext_cost;
		$p_issue_qty;
		$fifo_avg;
		$wko_mst_rowid;
		$ast_mst_rowid;
		$current_datetime = date("Y-m-d h:i:s");
		$stock_cost_flag;

		$itm_rsv_rsv_qty;
		$itm_rsv_short_qty;
		$li_grn_line = 0;
		
		
		foreach($result->Header as $Heade){
			
			$site_cd 			= $Heade->site_cd;
			$itm_mst_rowid   	= $Heade->wko_RowID;
			$mtr_no  			= '';
			$wo_no 				= $Heade->wko_mst_wo_no;
			$asset_no			= $Heade->wko_mst_assetno;
			$mst_costcenter		= $Heade->wko_mst_chg_costcenter_id;
			$mst_account		= $Heade->wko_det_maccount_id;
			$audit_user			= $Heade->audit_user;
			$isu_empl_id		= $Heade->issue_to_id;
			$mr_status			= 'MTR';
			$remark				= $Heade->remark;
			$issue_date			= $Heade->issue_date;
			//echo $issue_date;
			
			foreach($result->Details as $Detail){
				
				$stock_no 			= $Detail->stock_no;
				$mtr_ls1_desc 		= $Detail->itm_mst_desc;
				$stock_location 	= $Detail->stock_location;
				$cost_center 		= $Detail->itm_mst_costcenter;
				$account 			= $Detail->itm_mst_account;
				$issue_qty 			= $Detail->rcv_qty;
				$mtr_ls1_mtr_lineno = $Detail->stocklineno;	
				$serial				= '';
				$p_issue_qty 		= $issue_qty;
				
				
				if( $doc_no == '' )
				{
					
					//Select document number ISU			
					$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 = 'ISU'";

					$stmt = sqlsrv_query( $conn, $sql);	
									
					if( !$stmt ) {
						 $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 = 'ISU'";			
					$stmt = sqlsrv_query( $conn, $sql);				
									
					if( !$stmt ) {
						 $error_message = "Error update table (cnt_mst)";
						 returnError($error_message);
						 die( print_r( sqlsrv_errors(), true));
					}

				}
				
				$li_grn_line = $li_grn_line + 1;
				
				//Select Item detail from itm_mst and itm_det
				$sql = "SELECT 	itm_mst.itm_mst_partno , 	
								itm_mst.itm_mst_mstr_locn , 	
								itm_mst.itm_mst_ttl_oh , 	
								itm_mst.itm_mst_issue_uom , 	
								itm_mst.itm_mst_costcenter , 
								itm_mst.itm_mst_account , 
								itm_det.itm_det_cr_code , 	
								itm_det.itm_det_item_cost , 
								itm_det.itm_det_std_cost , 	
								itm_det.itm_det_avg_cost , 		
								itm_det.itm_det_last_cost , 
								itm_mst.RowID , 				
								itm_mst_serialize_flg , 	
								itm_mst.itm_mst_desc , 
								itm_det.itm_det_auto_spare
						FROM 	itm_mst(NOLOCK) , 
								itm_det(NOLOCK) 
						WHERE 	( itm_mst.RowID =itm_det.mst_RowID ) 
						AND 	( itm_mst.itm_mst_stockno = '".$stock_no."' ) 
						AND 	( itm_mst.site_cd ='".$site_cd."' )";

				$stmt = sqlsrv_query( $conn, $sql);
								
				if( !$stmt ) {
					 $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)) {
						$itm_mst_partno 		= $row['itm_mst_partno'];
						$itm_mst_mstr_locn 		= $row['itm_mst_mstr_locn'];
						$itm_mst_ttl_oh 		= $row['itm_mst_ttl_oh'];
						$itm_mst_issue_uom 		= $row['itm_mst_issue_uom'];
						$itm_mst_crd_costcenter = $row['itm_mst_costcenter'];
						$itm_mst_crd_account 	= $row['itm_mst_account'];
						$itm_det_cr_code 		= $row['itm_det_cr_code'];
						$itm_det_item_cost 		= $row['itm_det_item_cost'];
						$itm_det_std_cost 		= $row['itm_det_std_cost'];
						$itm_det_avg_cost 		= $row['itm_det_avg_cost'];
						$itm_det_last_cost 		= $row['itm_det_last_cost'];
						$itm_mst_rowid 			= $row['RowID'];
						$itm_mst_serialize_flg 	= $row['itm_mst_serialize_flg'];
						$itm_mst_desc 			= $row['itm_mst_desc'];
						$itm_det_auto_spare 	= $row['itm_det_auto_spare'];
					}
				} while ( sqlsrv_next_result($stmt) );
				
				//Select Stock Cost Flag
				$sql = "SELECT	itm_loc_stock_cost_flag
						FROM	itm_loc (NOLOCK)
						WHERE	site_cd = '".$site_cd."'
						AND		mst_RowID = ".$itm_mst_rowid."
						AND		itm_loc_stk_loc = '".$stock_location."'";

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

				if( !$stmt ) {
					 $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)) {
						$cost_flag = $row['itm_loc_stock_cost_flag'];		 
					}
				} while ( sqlsrv_next_result($stmt) );
				
				If ($stock_cost_flag = "" OR IS_NULL($stock_cost_flag)){
					$stock_cost_flag = '1';
				}
				
				switch ($itm_det_cr_code) {
				  case 'AVG':
					$latest_itm_cost = $itm_det_avg_cost;
					break;
				  case 'STD':
					$latest_itm_cost = $itm_det_std_cost;
					break;
				  case 'LST':
					$latest_itm_cost = $itm_det_last_cost;
					break;
					case 'FIFO':
					$latest_itm_cost = $itm_det_avg_cost;
					break;
				  default:

				}
				
				$latest_issue_price = $latest_itm_cost * ( (100.00 + $surcharge) / 100 );

				$raw_cost = $issue_qty * $latest_itm_cost;
				$ext_cost  = $issue_qty * $latest_issue_price;
				
				//Select WO rowid
				if ($wo_no != ""){
					$sql = "SELECT 	rowid
							FROM 	wko_mst (NOLOCK)
							WHERE	wko_mst.site_cd = '".$site_cd."'
							AND		wko_mst.wko_mst_wo_no = '".$wo_no."'";

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

					do {
						 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
							$wko_mst_rowid = $row['rowid'];			
						 }
					} while ( sqlsrv_next_result($stmt) );	
				}else{
					$wko_mst_rowid = "";
				}
				
				//Select Asset rowid
				if ($asset_no != ""){
					$sql = "SELECT 	rowid
							FROM 	ast_mst (NOLOCK)
							WHERE	ast_mst.site_cd = '".$site_cd."'
							AND		ast_mst.ast_mst_asset_no = '".$asset_no."'";


					$stmt = sqlsrv_query( $conn, $sql);				
									
					if( !$stmt ) {
						 $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)) {
							$ast_mst_rowid = $row['rowid'];			
						 }
					} while ( sqlsrv_next_result($stmt) );	
				}else{
					$ast_mst_rowid = "";
				}
				
				$sql = "SELECT 	itm_rsv_rsv_qty=COALESCE(SUM(itm_rsv_rsv_qty), 0),itm_rsv_short_qty=COALESCE(SUM(itm_rsv_short_qty), 0) 
					FROM	itm_rsv (NOLOCK)
					WHERE	itm_rsv.site_cd = '".$site_cd."'
					AND		itm_rsv.itm_rsv_mtr_no = '".$mtr_no."'
					AND		itm_rsv.itm_rsv_mtr_lineno = '".$mtr_ls1_mtr_lineno."'
					AND		itm_rsv.itm_rsv_itm_loc = '".$stock_location."'";


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

				do {
					 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
						$itm_rsv_rsv_qty = $row['itm_rsv_rsv_qty'];
						$itm_rsv_short_qty = $row['itm_rsv_short_qty'];
						
					 }
				} while ( sqlsrv_next_result($stmt) );
				
				
				if($itm_rsv_rsv_qty > 0 & $itm_rsv_short_qty = 0){
		
					if($itm_rsv_rsv_qty > $issue_qty ){
				
						$sql = "UPDATE 	itm_rsv
								SET 	itm_rsv_rsv_qty = itm_rsv_rsv_qty - ".$itm_rsv_rsv_qty.",
										mbl_audit_user= ?,		
										mbl_audit_date=getdate()
								WHERE	itm_rsv.site_cd = ?
								AND		itm_rsv.itm_rsv_mtr_no = ?
								AND		itm_rsv.itm_rsv_mtr_lineno = ?
								AND		itm_rsv.itm_rsv_itm_loc = ?";
								
						$params_itm_rsv = array( $audit_user,$site_cd,$mtr_no,$mtr_ls1_mtr_lineno,$stock_location );
						$stmt = sqlsrv_query( $conn, $sql,$params_itm_rsv);				
										
						if( !$stmt ) {
							 $error_message = "Error update table (itm_rsv)";
							 returnError($error_message);
							 die( print_r( sqlsrv_errors(), true));
						}		
					}else if($itm_rsv_rsv_qty = $issue_qty){
				

						$sql = "DELETE 	itm_rsv		
								WHERE	itm_rsv.site_cd = '".$site_cd."'
								AND		itm_rsv.itm_rsv_mtr_no = '".$mtr_no."'
								AND		itm_rsv.itm_rsv_mtr_lineno = '".$mtr_ls1_mtr_lineno."'
								AND		itm_rsv.itm_rsv_itm_loc = '".$stock_location."'";

						$stmt = sqlsrv_query( $conn, $sql);				
										
						if( !$stmt ) {
							 $error_message = "Error update table (itm_rsv)";
							 returnError($error_message);
							 die( print_r( sqlsrv_errors(), true));
						}		
				
					}
				}else if($itm_rsv_rsv_qty = 0 & $itm_rsv_short_qty > 0){
		
					if($itm_rsv_short_qty > $issue_qty){
			
			
						$sql = "UPDATE 	itm_rsv
								SET 	itm_rsv_short_qty = itm_rsv_short_qty - ".$itm_rsv_short_qty.",
										mbl_audit_user= ?,		
										mbl_audit_date=getdate()
								WHERE	itm_rsv.site_cd = ?
								AND		itm_rsv.itm_rsv_mtr_no = ?
								AND		itm_rsv.itm_rsv_mtr_lineno = ?
								AND		itm_rsv.itm_rsv_itm_loc = ?";

						$params_itm_rsv = array( $audit_user,$site_cd,$mtr_no,$mtr_ls1_mtr_lineno,$stock_location );
						$stmt = sqlsrv_query( $conn, $sql,$params_itm_rsv);				
										
						if( !$stmt ) {
							 $error_message = "Error update table (itm_rsv)";
							 returnError($error_message);
							 die( print_r( sqlsrv_errors(), true));
						}		

					}else if($itm_rsv_short_qty = $issue_qty){
			
						$sql = "DELETE 	itm_rsv		
								WHERE	itm_rsv.site_cd = '".$site_cd."'
								AND		itm_rsv.itm_rsv_mtr_no = '".$mtr_no."'
								AND		itm_rsv.itm_rsv_mtr_lineno = '".$mtr_ls1_mtr_lineno."'
								AND		itm_rsv.itm_rsv_itm_loc = '".$stock_location."'";

						$stmt = sqlsrv_query( $conn, $sql);				
										
						if( !$stmt ) {
							 $error_message = "Error update table (itm_rsv)";
							 returnError($error_message);
							 die( print_r( sqlsrv_errors(), true));
						}	
			
					}
		
				}else if($itm_rsv_rsv_qty > 0 & $itm_rsv_short_qty > 0){
		
					if($issue_qty = $itm_rsv_rsv_qty + $itm_rsv_short_qty){
			
						$sql = "DELETE 	itm_rsv		
								WHERE	itm_rsv.site_cd = '".$site_cd."'
								AND		itm_rsv.itm_rsv_mtr_no = '".$mtr_no."'
								AND		itm_rsv.itm_rsv_mtr_lineno = '".$mtr_ls1_mtr_lineno."'
								AND		itm_rsv.itm_rsv_itm_loc = '".$stock_location."'";

						$stmt = sqlsrv_query( $conn, $sql);				
										
						if( !$stmt ) {
						 $error_message = "Error update table (itm_rsv)";
						 returnError($error_message);
						 die( print_r( sqlsrv_errors(), true));
						}	
					}else if ($issue_qty <= $itm_rsv_rsv_qty){
			
						$sql = "UPDATE 	itm_rsv
								SET 	itm_rsv_rsv_qty = itm_rsv_rsv_qty - ".$itm_rsv_rsv_qty.",
										mbl_audit_user= ?,		
										mbl_audit_date=getdate()
								WHERE	itm_rsv.site_cd = ?
								AND		itm_rsv.itm_rsv_mtr_no = ?
								AND		itm_rsv.itm_rsv_mtr_lineno = ?
								AND		itm_rsv.itm_rsv_itm_loc = ?";

						$params_itm_rsv = array( $audit_user,$site_cd,$mtr_no,$mtr_ls1_mtr_lineno,$stock_location );
						$stmt = sqlsrv_query( $conn, $sql,$params_itm_rsv );				
									
						if( !$stmt ) {
						 $error_message = "Error update table (itm_rsv)";
						 returnError($error_message);
						 die( print_r( sqlsrv_errors(), true));
						}		
			
					}else if($issue_qty > $itm_rsv_rsv_qty & $issue_qty < $itm_rsv_rsv_qty + $itm_rsv_short_qty){
			
						$itm_rsv_short_qty = $issue_qty - $itm_rsv_rsv_qty;
				
						$sql = "UPDATE 	itm_rsv
								SET 	itm_rsv_rsv_qty = itm_rsv_rsv_qty - ".$itm_rsv_rsv_qty.",
										itm_rsv_short_qty = itm_rsv_short_qty - ".$itm_rsv_short_qty.",
										mbl_audit_user= ?,		
										mbl_audit_date=getdate()
								WHERE	itm_rsv.site_cd = ?
								AND		itm_rsv.itm_rsv_mtr_no = ?
								AND		itm_rsv.itm_rsv_mtr_lineno = ?
								AND		itm_rsv.itm_rsv_itm_loc = ?";

						$params_itm_rsv = array( $audit_user,$site_cd,$mtr_no,$mtr_ls1_mtr_lineno,$stock_location );
						$stmt = sqlsrv_query( $conn, $sql,$params_itm_rsv);				
									
						if( !$stmt ) {
						 $error_message = "Error update table (itm_rsv)";
						 returnError($error_message);
						 die( print_r( sqlsrv_errors(), true));
						}		
					}
				}
				
				switch ($cost_flag) {
					
					case '1':
						$sql = "UPDATE 	itm_mst
								SET 	itm_mst_ttl_oh = COALESCE(itm_mst_ttl_oh, 0) - ".$issue_qty.",
										itm_mst_issue_price = ?,
										mbl_audit_user= ?,		
										mbl_audit_date=getdate()
								WHERE	itm_mst.RowID = ? ";

						$params_itm_mst = array( $latest_issue_price,$audit_user,$itm_mst_rowid );
						$stmt = sqlsrv_query( $conn, $sql,$params_itm_mst);				
						
						if( !$stmt ) {
							 $error_message = "Error update table (itm_mst)";
							 returnError($error_message);
							 die( print_r( sqlsrv_errors(), true));
						}

						$sql = "UPDATE 	itm_det
								SET 		itm_det_ttl_oh = COALESCE(itm_det_ttl_oh, 0) - ".$issue_qty.",
											itm_det_ytd_usage = COALESCE(itm_det_ytd_usage, 0) + ".$issue_qty.",
											itm_det_item_cost = ?,
											itm_det_issue_price = ?,
											itm_det_lastactdate = GetDate(),
											mbl_audit_user= ?,		
											mbl_audit_date=getdate()
								WHERE	 itm_det.mst_RowID = ? ";

						$params_itm_det = array( $latest_itm_cost,$latest_issue_price,$audit_user,$itm_mst_rowid );
						$stmt = sqlsrv_query( $conn, $sql,$params_itm_det);				
										
						if( !$stmt ) {
							 $error_message = "Error update table (itm_det)";
							 returnError($error_message);
							 die( print_r( sqlsrv_errors(), true));
						}
					break;
					case '0':
						$sql = "UPDATE 	itm_mst
								SET 	itm_mst_ttl_oh = COALESCE(itm_mst_ttl_oh, 0) - ".$issue_qty.",
										mbl_audit_user='".$audit_user."',		
										mbl_audit_date=getdate()
								WHERE	( itm_mst.RowID = ".$itm_mst_rowid." )";
						
						$stmt = sqlsrv_query( $conn, $sql);				
										
						if( !$stmt ) {
							 $error_message = "Error update table (itm_mst)";
							 returnError($error_message);
							 die( print_r( sqlsrv_errors(), true));
						}
					
						$sql = "UPDATE 	itm_det
								SET 	itm_det_ttl_oh = COALESCE(itm_det_ttl_oh, 0) - ".$issue_qty.",
										itm_det_ttl_repair = COALESCE(itm_det_ttl_repair, 0) - ".$issue_qty.",
										itm_det_ytd_usage = COALESCE(itm_det_ytd_usage, 0) + ".$issue_qty.",
										itm_det_lastactdate = GetDate(),
										mbl_audit_user='".$audit_user."',		
										mbl_audit_date=getdate()
								WHERE	( itm_det.mst_RowID = ".$itm_mst_rowid." )";

						$stmt = sqlsrv_query( $conn, $sql);				
							
						if( !$stmt ) {
							 $error_message = "Error update table (itm_det)";
							 returnError($error_message);
							 die( print_r( sqlsrv_errors(), true));
						}
					
						$latest_issue_price = 0;
						$raw_cost = 0;
						$ext_cost  = 0;
						
					break;
					default:
					
					
				}
				
				$sql = "UPDATE 	itm_loc
						SET 	itm_loc_oh_qty = COALESCE(itm_loc_oh_qty, 0) - ".$issue_qty.",
								itm_loc_lastactdate = GetDate(),
								mbl_audit_user='".$audit_user."',		
								mbl_audit_date=getdate()
						WHERE	( itm_loc.mst_RowID = ".$itm_mst_rowid." ) 
						AND		( itm_loc_stk_loc = '".$stock_location."' )";

				$stmt = sqlsrv_query( $conn, $sql);				
									
				if( !$stmt ) {
					 $error_message = "Error update table (itm_loc)";
					 returnError($error_message);
					 die( print_r( sqlsrv_errors(), true));
				}
				
				
				$sql = "UPDATE 	itm_loc
						SET 	itm_loc_hard_resrv = COALESCE(itm_loc_hard_resrv, 0) - ".$itm_rsv_rsv_qty.",
								itm_loc_lastactdate = GetDate(),
								mbl_audit_user='".$audit_user."',		
								mbl_audit_date=getdate()
						WHERE	( itm_loc.mst_RowID = ".$itm_mst_rowid." ) 
						AND		( itm_loc_stk_loc = '".$stock_location."' )";

				$stmt = sqlsrv_query( $conn, $sql);				
									
				if( !$stmt ) {
					 $error_message = "Error update table (itm_loc)";
					 returnError($error_message);
					 die( print_r( sqlsrv_errors(), true));
				}
				
				$sql = 	"SELECT 	itm_mtc.site_cd,   				itm_mtc.itm_mtc_grn_no,   			itm_mtc.itm_mtc_grn_itm_no,   	itm_mtc.itm_mtc_rcv_date,   itm_mtc.itm_mtc_rcv_empl_id,   
									itm_mtc.itm_mtc_stockno,   		itm_mtc.itm_mtc_stk_locn,   		itm_mtc.itm_mtc_uom,   			itm_mtc.itm_mtc_costcenter, itm_mtc.itm_mtc_account,   
									itm_mtc.itm_mtc_crd_costcenter,	itm_mtc.itm_mtc_crd_account,		itm_mtc.itm_mtc_tax_cd,			itm_mtc.itm_mtc_tax_rate,	itm_mtc.itm_mtc_tax_value,
									itm_mtc.itm_mtc_pono,   		itm_mtc.itm_mtc_po_lineno,   		itm_mtc.itm_mtc_nonstkitm,   	itm_mtc.itm_mtc_rcv_qty,   	itm_mtc.itm_mtc_rcv_cost,   
									itm_mtc.itm_mtc_isu_qty,   		itm_mtc.itm_mtc_inv_qty,   			itm_mtc.itm_mtc_inv_cost,   	itm_mtc.audit_user,   		itm_mtc.audit_date,   
									itm_mtc.column1,   				itm_mtc.column2,   					itm_mtc.column3,   				itm_mtc.column4,   			itm_mtc.column5,   
									itm_mtc.RowID  				
						FROM		itm_mtc (NOLOCK)
						WHERE		( itm_mtc.itm_mtc_rcv_qty > itm_mtc.itm_mtc_isu_qty )
						AND			( itm_mtc.site_cd = '".$site_cd."' )
						AND			( itm_mtc.itm_mtc_stockno = '".$stock_no."' )
						AND 		( itm_mtc_stk_locn = '".$stock_location."' )
						ORDER BY itm_mtc_rcv_date, RowID";

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

				 if( !$stmt ) {
					  $error_message = "Error insert table (itm_mtc)";
					  returnError($error_message);
					  die( print_r( sqlsrv_errors(), true));
				 }
		 
				do {
					while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
				 
						$itm_mtc_rcv_qty 		= $row['itm_mtc_rcv_qty'];
						$itm_mtc_isu_qty 		= $row['itm_mtc_isu_qty'];
						$itm_mtc_grn_no 		= $row['itm_mtc_grn_no'];
						$itm_mtc_rowid 			= $row['RowID'];
						$itm_mtc_rcv_cost 		= $row['itm_mtc_rcv_cost'];
						$itm_mtc_costcenter		= $row['itm_mtc_costcenter'];
						$itm_mtc_account		= $row['itm_mtc_account'];
						$itm_mtc_crd_costcenter = $row['itm_mtc_crd_costcenter'];
						$itm_mtc_crd_account 	= $row['itm_mtc_crd_account'];
						
						$balance_qty 			= $itm_mtc_rcv_qty - $itm_mtc_isu_qty;
					
						if ($p_issue_qty <= $balance_qty) {
						
						
							//update MTC
							$sql_update_mtc = "UPDATE 	itm_mtc
												SET		itm_mtc_isu_qty = itm_mtc_isu_qty + ".$p_issue_qty." 
												WHERE	RowID = ".$itm_mtc_rowid;

							$stmt_update_mtc = sqlsrv_query( $conn, $sql_update_mtc);				
											
							if( !$stmt_update_mtc ) {
								 $error_message = "Error update table (itm_mtc)";
								 returnError($error_message);
								 die( print_r( sqlsrv_errors(), true));
							}else{
								if ($itm_det_cr_code == "FIFO"){
									
									$latest_issue_price = $itm_mtc_rcv_cost * ( (100.00 + $surcharge) / 100 );
									$raw_cost 	= $issue_qty * $itm_mtc_rcv_cost;
									$ext_cost  	= $issue_qty * $latest_issue_price;
									
									//Select FIFO Average
									$sql_select_fifo_avg = "SELECT	'fifo_avg' = COALESCE( SUM((itm_mtc_rcv_qty - itm_mtc_isu_qty) * itm_mtc_rcv_cost) / SUM(itm_mtc_rcv_qty - itm_mtc_isu_qty), 0 )
											FROM	itm_mtc (NOLOCK)
											WHERE	( itm_mtc.site_cd = '".$site_cd."' )
											AND		( itm_mtc.itm_mtc_stockno = '".$stock_no."'  )
											AND		( itm_mtc.itm_mtc_rcv_qty > itm_mtc.itm_mtc_isu_qty )
											AND		( itm_mtc.itm_mtc_rcv_qty <> 0 )";

									$stmt_select_fifo_avg = sqlsrv_query( $conn, $sql_select_fifo_avg);				
													
									if( !$stmt_select_fifo_avg ) {
										 $error_message = "Error select table (itm_mtc)";
										 returnError($error_message);
										 die( print_r( sqlsrv_errors(), true));
									}

									do {
										 while ($row = sqlsrv_fetch_array($stmt_select_fifo_avg, SQLSRV_FETCH_ASSOC)) {
											$fifo_avg = $row['fifo_avg'];
										 }
									} while ( sqlsrv_next_result($stmt_select_fifo_avg) );	
								
									sqlsrv_free_stmt( $stmt_select_fifo_avg);
								
									//Insert itm_trx
									//itm_trx_trx_date = entry date for issue, for now is getdate
									//default empl_id to demo
									$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 
										( 	?,								?, 								'MT21', 						GetDate(),						?,					
											?,								'', 							?,								?,								'', 								
											'',								?,								0,								0,								0,								
											0,								?,								?,								?,								?,								
											?,								?,								?,								?,								?,				
											0,								'',								?,								'',								'',								
											'',								'',								0,								0,								?,					
											0,								'',								'',								0,						    	'',								
											?,								'',								?,								?,								?,								
											'',								0,								NULL,							'',								'',								
											?,								0,								0,								0,								'',								
											'',								0,								0,								0,								0,								
											0,								0,								0,								'',								'',								
											'',								'',								'',								?,								0,								
											?,								?,								?,								GetDate(),						?,							GetDate() )";
										
										//echo $sql_insert_itm_trx;

									$params_itm_det = array( $site_cd,$doc_no,$issue_date,$isu_empl_id,$stock_no,$itm_mst_desc,$p_issue_qty,$mst_costcenter,$mst_account,$cost_center,$account,$asset_no,$wo_no,$mtr_no,$latest_issue_price,$itm_mst_issue_uom,$ext_cost,$stock_location,$li_grn_line,$itm_det_avg_cost,$itm_det_std_cost,$itm_det_last_cost,$raw_cost,$audit_user,$fifo_avg,$remark,$audit_user,$audit_user );
								
									$stmt_insert_itm_trx = sqlsrv_query( $conn, $sql_insert_itm_trx,$params_itm_det);				
												
									if( !$stmt_insert_itm_trx ) {
										 $error_message = "Error insert table (itm_trx)";
										 returnError($error_message);
										 die( print_r( sqlsrv_errors(), true));
									}

									// do {
										 // while ($row = sqlsrv_fetch_array($stmt_insert_itm_trx, SQLSRV_FETCH_ASSOC)) {
											// $itm_trx_rowid = $row['rowid'];
										 // }
									// } while ( sqlsrv_next_result($stmt_insert_itm_trx) );
									
									sqlsrv_free_stmt( $stmt_insert_itm_trx);
								}
							
								//Insert itm_mtu
								$sql_insert_itm_mtu = "INSERT INTO itm_mtu  
									(	site_cd, 					itm_mtu_activity_code, 		itm_mtu_doc_no, 				itm_mtu_wo, 			itm_mtu_stockno,
										itm_mtu_stk_locn, 			itm_mtu_mtr_no, 			itm_mtu_mtr_lineno, 			itm_mtu_desc, 			itm_mtu_usg_date,
										itm_mtu_cur_date, 			itm_mtu_used_qty, 			itm_mtu_used_uom, 				itm_mtu_item_cost, 		itm_mtu_chg_costcenter,
										itm_mtu_chg_account, 		itm_mtu_crd_costcenter, 	itm_mtu_crd_account, 			itm_mtu_assetno, 		itm_mtu_projectid, 
										itm_mtu_nonstkitem, 		itm_mtu_supplier, 			itm_mtu_login_id, 				itm_mtu_work_type, 		itm_mtu_ref_doc_no,
										itm_mtu_cost_cat_id, 		itm_mtu_mt_special_idno, 	itm_mtu_mtc_id, 				itm_mtu_mts_id, 		itm_mtu_remark,
										audit_user,					audit_date,					itm_mtu_serial_no,				mbl_audit_user,			mbl_audit_date, 
										itm_mtu_po_costcenter,		itm_mtu_po_account )
								VALUES 
									( 	?,							'', 						?,								?,						?,
										?,							?,							0,								?,						GetDate(),
										GetDate(),					?,							?,								?,						?,
										?,							?,							?,								?,						'',								
										'',							'',							?,								'',						?,			
										0,							0,							?,								0,						?,					
										?,							GetDate(), 					NULL,							?,						GetDate(),
										?,							?)";
										
										
								$params_itm_mtu = array( $site_cd,$doc_no,$wo_no,$stock_no,$stock_location,$mtr_no,$itm_mst_desc,$p_issue_qty,$itm_mst_issue_uom,$latest_issue_price,$mst_costcenter,$mst_account,$cost_center,$account,$asset_no,$audit_user,$itm_mtc_grn_no,$itm_mtc_rowid,$remark,$audit_user,$audit_user,$itm_mtc_costcenter,$itm_mtc_account );
									

								$stmt_insert_itm_mtu = sqlsrv_query( $conn, $sql_insert_itm_mtu,$params_itm_mtu);				
												
								if( !$stmt_insert_itm_mtu ) {
									 $error_message = "Error insert table (itm_mtu)";
									 returnError($error_message);
									 die( print_r( sqlsrv_errors(), true));
								}

								// do {
									 // while ($row = sqlsrv_fetch_array($stmt_insert_itm_mtu, SQLSRV_FETCH_ASSOC)) {
										// $itm_mtu_rowid = $row['rowid'];
									 // }
								// } while ( sqlsrv_next_result($stmt_insert_itm_mtu) );	
								
								sqlsrv_free_stmt( $stmt_insert_itm_mtu);

							}	
							//End
							BREAK;
						}else{
							if ( $p_issue_qty > $balance_qty){
								$p_issue_qty = $p_issue_qty - $balance_qty;
							
								//update MTC
								$sql_update_mtc = "UPDATE 	itm_mtc
													SET		itm_mtc_isu_qty = itm_mtc_isu_qty + ".$balance_qty."
													WHERE	RowID = ".$itm_mtc_rowid;

								$stmt_update_mtc = sqlsrv_query( $conn, $sql_update_mtc);				
										
								if( !$stmt_update_mtc ) {
									$error_message = "Error update table (itm_mtc)";
									returnError($error_message);
									die( print_r( sqlsrv_errors(), true));
								}else{
									if ($itm_det_cr_code == "FIFO"){
										$latest_issue_price = $itm_mtc_rcv_cost * ( (100.00 + $surcharge) / 100 );
										$raw_cost 	= $issue_qty * $itm_mtc_rcv_cost;
										$ext_cost  	= $issue_qty * $latest_issue_price;
								
										//Select FIFO Average
										$sql_select_fifo_avg = "SELECT	'fifo_avg' = COALESCE( SUM((itm_mtc_rcv_qty - itm_mtc_isu_qty) * itm_mtc_rcv_cost) / SUM(itm_mtc_rcv_qty - itm_mtc_isu_qty), 0 )
												FROM	itm_mtc (NOLOCK)
												WHERE	( itm_mtc.site_cd = '".$site_cd."' )
												AND		( itm_mtc.itm_mtc_stockno = '".$stock_no."'  )
												AND		( itm_mtc.itm_mtc_rcv_qty > itm_mtc.itm_mtc_isu_qty )
												AND		( itm_mtc.itm_mtc_rcv_qty <> 0 )";

										$stmt_select_fifo_avg = sqlsrv_query( $conn, $sql_select_fifo_avg);				
														
										if( !$stmt_select_fifo_avg ) {
											 $error_message = "Error select table (itm_mtc)";
											 returnError($error_message);
											 die( print_r( sqlsrv_errors(), true));
										}

										do {
											 while ($row = sqlsrv_fetch_array($stmt_select_fifo_avg, SQLSRV_FETCH_ASSOC)) {
												$fifo_avg = $row['fifo_avg'];
											 }
										} while ( sqlsrv_next_result($stmt_select_fifo_avg) );	
										
										sqlsrv_free_stmt( $stmt_select_fifo_avg);
								
										//Insert itm_trx
										//itm_trx_trx_date = entry date for issue, for now is getdate
										//default empl_id to demo
										$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 
											( 	?,								?, 								'MT21', 						GetDate(),						?,					
												?,								'', 							?,								?,								'', 								
												'',								?,								0,								0,								0,								
												0,								?,								?,								?,								?,								
												?,								?,								?,								?,								?,				
												0,								'',								?,								'',								'',								
												'',								'',								0,								0,								?,					
												0,								'',								'',								0,								'',								
												?,								'',								?,								?,								?,								
												'',								0,								NULL,							'',								'',								
												?,								0,								0,								0,								'',								
												'',								0,								0,								0,								0,								
												0,								0,								0,								'',								'',								
												'',								'',								'',								?,								0,								
												?,								?,								?,								GetDate(),						?,				GetDate() )";

										$params_itm_trx = array( $site_cd,$doc_no,$issue_date,$isu_empl_id,$stock_no,$itm_mst_desc,$balance_qty,$mst_costcenter,$mst_account,$cost_center,$account,$mst_costcenter,$mst_account,$cost_center,$account,$asset_no,$wo_no,$mtr_no,$latest_issue_price,$li_grn_line,$itm_mst_issue_uom,$ext_cost,$stock_location,$itm_det_avg_cost,$itm_det_std_cost,$itm_det_last_cost,$raw_cost,$audit_user,$fifo_avg,$remark,$audit_user,$audit_user );
										
										$stmt_insert_itm_trx = sqlsrv_query( $conn, $sql_insert_itm_trx,$params_itm_trx);				
														
										if( !$stmt_insert_itm_trx ) {
											 $error_message = "Error insert table (itm_trx)";
											 returnError($error_message);
											 die( print_r( sqlsrv_errors(), true));
										}

										// do {
											 // while ($row = sqlsrv_fetch_array($stmt_insert_itm_trx, SQLSRV_FETCH_ASSOC)) {
												// $itm_trx_rowid = $row['rowid'];
											 // }
										// } while ( sqlsrv_next_result($stmt_insert_itm_trx) );
										
										sqlsrv_free_stmt( $stmt_insert_itm_trx);
									}
							
									//Insert itm_mtu
									$sql_insert_itm_mtu = "INSERT INTO itm_mtu  
										(	site_cd, 							itm_mtu_activity_code, 			itm_mtu_doc_no, 				itm_mtu_wo, 					itm_mtu_stockno,
											itm_mtu_stk_locn, 					itm_mtu_mtr_no, 				itm_mtu_mtr_lineno, 			itm_mtu_desc, 					itm_mtu_usg_date,
											itm_mtu_cur_date, 					itm_mtu_used_qty, 				itm_mtu_used_uom, 				itm_mtu_item_cost, 				itm_mtu_chg_costcenter,
											itm_mtu_chg_account, 				itm_mtu_crd_costcenter, 		itm_mtu_crd_account, 			itm_mtu_assetno, 				itm_mtu_projectid, 
											itm_mtu_nonstkitem, 				itm_mtu_supplier, 				itm_mtu_login_id, 				itm_mtu_work_type, 				itm_mtu_ref_doc_no,
											itm_mtu_cost_cat_id, 				itm_mtu_mt_special_idno, 		itm_mtu_mtc_id, 				itm_mtu_mts_id, 				itm_mtu_remark,
											audit_user,							audit_date,						mbl_audit_user,					mbl_audit_date,					itm_mtu_po_costcenter,	
											itm_mtu_po_account )
									VALUES 
										( 	?,									'', 							?,								?,								?,
											?,									?,								0,							?,								GetDate(),
											GetDate(),							?,								?,								?,								?,
											?,									?,								?,								?,								'',								
											'',									'',								?,								'',								?,			
											0,									0,								?,								0,								?,					
											?,									GetDate(),						?,								GetDate(),						?,
											? )";

									$params_itm_mtu = array( $site_cd,$doc_no,$wo_no,$stock_no,$stock_location,$mtr_no,$itm_mst_desc,$balance_qty,$itm_mst_issue_uom,$latest_issue_price,$mst_costcenter,$mst_account,$cost_center,$account,$asset_no,$audit_user,$itm_mtc_grn_no,$itm_mtc_rowid,$remark,$audit_user,$audit_user,$itm_mtc_costcenter,$itm_mtc_account);
									$stmt_insert_itm_mtu = sqlsrv_query( $conn, $sql_insert_itm_mtu,$params_itm_mtu);				
													
									if( !$stmt_insert_itm_mtu ) {
										 $error_message = "Error insert table (itm_mtu)";
										 returnError($error_message);
										 die( print_r( sqlsrv_errors(), true));
									}

									// do {
										 // while ($row = sqlsrv_fetch_array($stmt_insert_itm_mtu, SQLSRV_FETCH_ASSOC)) {
											// $itm_mtu_rowid = $row['rowid'];
										 // }
									// } while ( sqlsrv_next_result($stmt_insert_itm_mtu) );	
									
									sqlsrv_free_stmt( $stmt_insert_itm_mtu);

								}	
							//End	
							}
						}
					}
				} while ( sqlsrv_next_result($stmt) );
				
				if ($itm_det_cr_code == 'FIFO') {
			
					//Select latest issue price
					$sql_select_latest_issue_price = "	SELECT	'latest_issue_price' = COALESCE( SUM((itm_mtc_rcv_qty - itm_mtc_isu_qty) * itm_mtc_rcv_cost) / SUM(itm_mtc_rcv_qty - itm_mtc_isu_qty), 0 )
														FROM	itm_mtc (NOLOCK)
														WHERE	( itm_mtc.site_cd = '".$site_cd."' )
														AND		( itm_mtc.itm_mtc_stockno = '".$stock_no."'  )
														AND		( itm_mtc.itm_mtc_rcv_qty > itm_mtc.itm_mtc_isu_qty )
														AND		( itm_mtc.itm_mtc_rcv_qty <> 0 )";

					$stmt_select_latest_issue_price = sqlsrv_query( $conn, $sql_select_latest_issue_price);				
									
					if( !$stmt_select_fifo_avg ) {
						 $error_message = "Error select table (itm_mtc)";
						 returnError($error_message);
						 die( print_r( sqlsrv_errors(), true));
					}

					do {
						 while ($row = sqlsrv_fetch_array($stmt_select_latest_issue_price, SQLSRV_FETCH_ASSOC)) {
							$latest_issue_price = $row['latest_issue_price'];
						 }
					} while ( sqlsrv_next_result($stmt_select_latest_issue_price) );	
				
					sqlsrv_free_stmt( $stmt_select_latest_issue_price);
			
					switch ($stock_cost_flag) {
					  case '1':
						$sql = "UPDATE 	itm_mst
								SET 	itm_mst_issue_price = ".$latest_issue_price." 
								WHERE	( itm_mst.RowID = ".$itm_mst_rowid." )";

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

						$sql = "UPDATE 	itm_det
								SET 		itm_det_item_cost = ".$latest_issue_price.",
											itm_det_issue_price = ".$latest_issue_price.",
											itm_det_lastactdate = GetDate()
								WHERE	( itm_det.mst_RowID = ".$itm_mst_rowid." )";

						$stmt = sqlsrv_query( $conn, $sql);				
										
						if( !$stmt ) {
							 $error_message = "Error update table (itm_det)";
							 returnError($error_message);
							 die( print_r( sqlsrv_errors(), true));
						}
						sqlsrv_next_result($stmt);
						break;
					  default:
					}
			
				}else{
					//Insert itm_trx
					//itm_trx_trx_date = entry date for issue, for now is getdate
					//default empl_id to demo
					$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_remark,					audit_user, 					audit_date,						mbl_audit_user,					mbl_audit_date ) 
					VALUES 
						( 	?,								?, 								'MT21', 						GetDate(),						'".$issue_date."',					
							?,								'', 							?,								?,								'', 								
							'',								?,								0,								0,								0,								
							0,								?,								?,								?,								?,								
							?,								?,								?,								?,								?,				
							0,								'',								?,								'',								'',								
							'',								'',								0,								0,								?,					
							0,								'',								'',								0,								'',								
							?,								'',								?,								?,								?,								
							'',								0,								NULL,							'',								'',								
							?,								0,								0,								0,								'',								
							'',								0,								0,								0,								0,								
							0,								0,								0,								'',								'',								
							'',								'',								'',								?,								0,								
							?,								?,								GetDate(),						?,								GetDate() )";
						

					$params_itm_trx = array( $site_cd,$doc_no,$isu_empl_id,$stock_no,$itm_mst_desc,$issue_qty,$mst_costcenter,$mst_account,$cost_center,$account,$asset_no,$wo_no,$mtr_no,$latest_issue_price,$itm_mst_issue_uom,$ext_cost,$stock_location,$li_grn_line,$itm_det_avg_cost,$itm_det_std_cost,$itm_det_last_cost,$raw_cost,$audit_user,$remark,$audit_user,$audit_user);

					$stmt_insert_itm_trx = sqlsrv_query( $conn, $sql_insert_itm_trx,$params_itm_trx);				
									
					if( !$stmt_insert_itm_trx ) {
						 $error_message = "Error insert table (itm_trx)";
						 returnError($error_message);
						 die( print_r( sqlsrv_errors(), true));
					}

					// do {
						 // while ($row = sqlsrv_fetch_array($stmt_insert_itm_trx, SQLSRV_FETCH_ASSOC)) {
							// $itm_trx_rowid = $row['rowid'];
						 // }
					// } while ( sqlsrv_next_result($stmt_insert_itm_trx) );
					
					sqlsrv_free_stmt( $stmt_insert_itm_trx);
			
				}
				
				if ($wo_no != "" & $wo_no ==NULL ){
			

					//Update wko_det cost
					$sql = "UPDATE 	wko_det
							SET 	wko_det_mtl_cost = COALESCE(wko_det_mtl_cost ,0) + ".$ext_cost." 
							WHERE 	wko_det.mst_RowID = ".$wko_mst_rowid."";

					$stmt = sqlsrv_query( $conn, $sql);				
										
					if( !$stmt ) {
					 $error_message = "Error update table (wko_det)";
					 returnError($error_message);
					 die( print_r( sqlsrv_errors(), true));
					}
					sqlsrv_next_result($stmt);
				}



				if ($asset_no != "" & $asset_no==NULL){
					//Update asset cost
					$sql = "UPDATE 	ast_det
							SET 	ast_det_ltdmtlcost = COALESCE(ast_det_ltdmtlcost ,0) + ".$ext_cost."
							WHERE 	ast_det.mst_RowID = ".$ast_mst_rowid ;

					$stmt = sqlsrv_query( $conn, $sql);				
											
					if( !$stmt ) {
						 $error_message = "Error update table (ast_det)";
						 returnError($error_message);
						 die( print_r( sqlsrv_errors(), true));
					}
					sqlsrv_next_result($stmt);
				
					if ($itm_det_auto_spare = '1'){
						$sql = "SELECT 	'spare_count' = Count(*)
								FROM	ast_ls1 (NOLOCK)
								WHERE	site_cd = '".$site_cd."'
								AND		mst_RowID = ".$ast_mst_rowid." 
								AND		ast_ls1_stock_no = '".$stock_no."'" ;

						$stmt = sqlsrv_query( $conn, $sql);				
												
						if( !$stmt ) {
							 $error_message = "Error select table (ast_ls1)";
							 returnError($error_message);
							 die( print_r( sqlsrv_errors(), true));
						}
						
						do {
						 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
							$spare_count = $row['spare_count'];
							}
						} while ( sqlsrv_next_result($stmt) );
					
						if ($spare_count == 0) {
							//Insert ast_ls1
							$sql = "INSERT INTO ast_ls1 ( 	site_cd,		mst_RowID,		ast_ls1_stock_no,	ast_ls1_qty_needed,
															ast_ls1_desc,	audit_user,		audit_date,			mbl_audit_user,		mbl_audit_date ) 
															
												VALUES 	(	?,				?,				?,					?,
															?,				?,				GetDate(),			?,					GetDate() ) " ;

							$params_ast_ls1 = array($site_cd,$ast_mst_rowid,$stock_no,$issue_qty,$itm_mst_desc,$audit_user,$audit_user);

							$stmt = sqlsrv_query( $conn, $sql,$params_ast_ls1);				
													
							if( !$stmt ) {
								 $error_message = "Error insert table (ast_ls1)";
								 returnError($error_message);
								 die( print_r( sqlsrv_errors(), true));
							}
							sqlsrv_next_result($stmt);
						}
					}
				}

				$charge_valid = f_update_budget($site_cd, $current_datetime, $mst_costcenter, $mst_account, "CHARGE", $ext_cost, $conn, $audit_user);
				$credit_valid = f_update_budget($site_cd, $current_datetime, $cost_center, $account, "CREDIT", $ext_cost, $conn, $audit_user);
			}
			
			$sql = "	SELECT	balance_qty = SUM(COALESCE(mtr_ls1.mtr_ls1_bo_qty, 0)),
							mtr_mst_rowid = MAX(mtr_mst.RowID),
							mtr_mst_status = MAX(mtr_mst_mr_status)
					FROM	mtr_mst (NOLOCK),
							mtr_ls1 (NOLOCK)
					WHERE	mtr_mst.site_cd = '".$site_cd."'
					AND 	mtr_mst.mtr_mst_mtr_no = '".$mtr_no."'
					AND 	mtr_mst.site_cd = mtr_ls1.site_cd
					AND 	mtr_mst.RowID = mtr_ls1.mst_RowID" ;

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

			do {
			 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
				$balance_qty = $row['balance_qty'];
				$mtr_mst_rowid = $row['mtr_mst_rowid'];	
				$mtr_mst_status = $row['mtr_mst_status'];		
				}
			} while ( sqlsrv_next_result($stmt) );
		}
		
	if ($valid) {	
		returnData($doc_no);	
	}

	sqlsrv_free_stmt( $stmt);
	sqlsrv_close($conn);
	
} 



//Validate Stock Availability
function validateStockAvailability($conn, $json) {
    $result = json_decode($json);

    foreach ($result->Header as $Heade) {
        $site_cd = $Heade->site_cd;

        $x = 0;

        foreach ($result->Details as $Detail) {
            $x++;

            $stockno = $Detail->stock_no;
            $quantity = $Detail->rcv_qty;

            // SQL to fetch stock info
            $sql = "SELECT
                        itm_mst.itm_mst_ttl_oh,
                        itm_loc.itm_loc_lockout4count
                    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
                    LEFT OUTER JOIN itm_loc
                        ON itm_mst.site_cd = itm_loc.site_cd
                        AND itm_mst.RowID = itm_loc.mst_RowID
                        AND itm_mst.itm_mst_mstr_locn = itm_loc.itm_loc_stk_loc
                    WHERE itm_mst.site_cd = ?
                        AND itm_sts_typ_cd = 'ACTIVE'
                        AND itm_mst.itm_mst_stockno = ?";

            $params = array($site_cd, $stockno);
            $stmt = sqlsrv_query($conn, $sql, $params);

            if (!$stmt) {
                returnError("Error retrieving stock info");
                die(print_r(sqlsrv_errors(), true));
            }

            $itm_mst_ttl_oh = 0;
            $itm_lockout = 0;

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

            if ($itm_lockout == '1') {
                returnError("The Stock Number $stockno is locked out for stock count.");
                return false;
            }

            if ($itm_mst_ttl_oh < $quantity) {
                returnError("Stock line No: $x - Required quantity exceeds the Total On-Hand quantity.");
                return false;
            }
        }
    }

    return true; // ✅ No errors encountered
}








function returnData($doc_no){
	
	$returnData = array(
	'status' => 'SUCCESS',
	'message' => "Miscellaneous Issue successfully. ( $doc_no )");
	
	echo json_encode($returnData);
}

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