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

$error_message;
$valid = 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;

// Takes raw data from the request
$json = file_get_contents('php://input');
$result = json_decode($json);
 
foreach($result->Header as $Heade){
	
	$site_cd 			= $Heade->site_cd;
	$itm_mst_rowid   	= $Heade->itm_mst_rowid;
	$mtr_no  			= $Heade->mtr_no;
	$wo_no 				= $Heade->wo_no;
	$asset_no			= $Heade->mtr_mst_assetno;
	$mst_costcenter		= $Heade->mst_costcenter;
	$mst_account		= $Heade->mst_account;
	$audit_user			= $Heade->mst_empl_id;
	$isu_empl_id		= $Heade->isu_empl_id;
	$mr_status			= $Heade->mr_status;
	$remark				= $Heade->remark;
	$issue_date			= $Heade->issue_date;
	//echo $issue_date;
	

foreach($result->Details as $Detail){
	
	$stock_no 			= $Detail->mtr_ls1_stockno;
	$mtr_ls1_desc 		= $Detail->mtr_ls1_desc;
	$stock_location 	= $Detail->mtr_ls1_stk_locn;
	$cost_center 		= $Detail->crd_costcenter;
	$account 			= $Detail->crd_account;
	$issue_qty 			= $Detail->issue_qty;
	$mtr_ls1_mtr_lineno = $Detail->mtr_ls1_mtr_lineno;	
	$serial				= $Detail->mtr_ls1_varchar1;
	$lslRow_ID			= $Detail->LslRow_ID;
	$p_issue_qty 		= $issue_qty;
	
	
		
/*Double Check On Hand Quantity And Required Qty */
$sql = "SELECT 	itm_loc.itm_loc_oh_qty, 
				itm_loc_oh_qty = CASE 	WHEN ( itm_loc.itm_loc_oh_qty - itm_loc_hard_resrv ) >= 0 
										THEN ( itm_loc.itm_loc_oh_qty - itm_loc_hard_resrv ) 
										ELSE 0 END +( 	SELECT 	COALESCE(SUM(itm_rsv_rsv_qty), 0) 
														FROM	itm_rsv (NOLOCK)
														WHERE	itm_rsv.site_cd = mtr_mst.site_cd
														AND		itm_rsv.itm_rsv_mtr_no = mtr_mst.mtr_mst_mtr_no
														AND		itm_rsv.itm_rsv_mtr_lineno = mtr_ls1.mtr_ls1_mtr_lineno 
														AND		itm_rsv.itm_rsv_itm_loc = itm_loc.itm_loc_stk_loc ),
				itm_mst.RowID,
				itm_loc_lockout4count
	
	FROM 		mtr_mst (NOLOCK),
				mtr_ls1 (NOLOCK),
				itm_mst (NOLOCK),
				itm_loc (NOLOCK)
	WHERE 		mtr_mst.site_cd = mtr_ls1.site_cd
	AND 		mtr_mst.rowid = mtr_ls1.mst_rowid
	AND 		itm_mst.site_cd = mtr_ls1.site_cd
	AND 		itm_mst.itm_mst_stockno = mtr_ls1.mtr_ls1_stockno
	AND 		itm_mst.RowID = itm_loc.mst_RowID 
	AND			itm_loc_inc_ttloh = '1'
	AND			itm_mst.site_cd = '".$site_cd."'
	AND			itm_mst.itm_mst_stockno = '".$stock_no."'
	AND			itm_loc.itm_loc_stk_loc = '".$stock_location."' 
	AND 		mtr_mst.mtr_mst_mtr_no = '".$mtr_no."'
	AND 		mtr_ls1.mtr_ls1_mtr_lineno = '".$mtr_ls1_mtr_lineno."'";

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

if( !$stmt ) {
     $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)) {
		 
		$ttl_oh_qty = $row['itm_loc_oh_qty'];
		$itm_oh_qty = $row['itm_loc_oh_qty'];
		$itm_RowID = $row['RowID'];
		$itm_lockout = $row['itm_loc_lockout4count'];
		
     }
} while ( sqlsrv_next_result($stmt) );

if ($itm_lockout == '1') {
	returnError("The Stock Number " . $stock_no . " is lockout for stock count.") ;
}	

$sql = "SELECT 		mtr_ls1_req_qty = 	COALESCE ( mtr_ls1_req_qty, 0 ),
					mtr_ls1_rcv_qty =	COALESCE ( mtr_ls1_rcv_qty, 0 ),
					mtr_ls1_bo_qty 	= 	COALESCE ( mtr_ls1_bo_qty, 0 )	
		FROM 		mtr_ls1 (NOLOCK)				
		WHERE 		( mtr_ls1.RowID = '".$lslRow_ID."' )";

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

if( !$stmt ) {
     $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)) {
		 
		$req_qty = $row['mtr_ls1_req_qty'];
		$rcv_qty = $row['mtr_ls1_rcv_qty'];
		$bo_qty = $row['mtr_ls1_bo_qty'];
	
     }
} while ( sqlsrv_next_result($stmt) );
	

if ($issue_qty > $itm_oh_qty) {
	returnError("Issue quantity cannot be more than the on-hand quantity.") ;
}

if ($issue_qty > $req_qty) {
	returnError("Issue quantity cannot be more than the required quantity.") ;
}

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 )
			VALUES 
				( 	?,							'', 						?,								?,						?,
					?,							?,							?,								?,						GetDate(),
					GetDate(),					?,							?,								?,						?,
					?,							?,							?,								?,						'',								
					'',							'',							?,								'',						?,			
					0,							0,							?,								0,						?,					
					?,							GetDate(), 					NULL,							?,						GetDate())";
					
					
			$params_itm_mtu = array( $site_cd,$doc_no,$wo_no,$stock_no,$stock_location,$mtr_no,$mtr_ls1_mtr_lineno,$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 );
				

			$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,								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,$mtr_ls1_mtr_lineno,$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 )
			VALUES 
				( 	?,									'', 							?,								?,								?,
					?,									?,								?,								?,								GetDate(),
					GetDate(),							?,								?,								?,								?,
					?,									?,								?,								?,								'',								
					'',									'',								?,								'',								?,			
					0,									0,								?,								0,								?,					
					?,									GetDate(),						?,								GetDate() )";

			$params_itm_mtu = array( $site_cd,$doc_no,$wo_no,$stock_no,$stock_location,$mtr_no,$mtr_ls1_mtr_lineno,$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);
			$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));
		}

		$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));
		}
		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,								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,$mtr_ls1_mtr_lineno,$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));
	}
}



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));
	}
	
	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));
			}
		}
	}
}

$sql = "UPDATE 	mtr_ls1
		SET 	mtr_ls1_rcv_qty = mtr_ls1_rcv_qty + '".$issue_qty."',
				mtr_ls1_bo_qty = mtr_ls1_req_qty - ( mtr_ls1_rcv_qty + '".$issue_qty."'),
				mbl_audit_user='".$audit_user."',		
				mbl_audit_date=getdate()
		WHERE rowid = '".$lslRow_ID."'";
		
$stmt = sqlsrv_query( $conn, $sql);		
					
if( !$stmt ) {
     $error_message = "Error update table (mtr_ls1)";
	 returnError($error_message);
     die( print_r( sqlsrv_errors(), true));
}


$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);

//Update mtr_mst status
$sql_update_mtr_mst = "UPDATE 	mtr_mst
						SET 	mtr_mst_status = 'A',
								mtr_mst_approver = NULL,
								mtr_mst_cur_app_level = mtr_mst_app_level,
								mbl_audit_user='".$audit_user."',		
								mbl_audit_date=getdate()
						WHERE 	mtr_mst.mtr_mst_mtr_no = '".$mtr_no."'
						AND 	mtr_mst.mtr_mst_status IN ('W', 'N', 'L')";
		
$stmt_update_mtr_mst = sqlsrv_query( $conn, $sql_update_mtr_mst);		
					
if( !$stmt_update_mtr_mst ) {
     $error_message = "Error update table (mtr_mst)";
	 returnError($error_message);
     die( print_r( sqlsrv_errors(), true));
}
	
//Update mtr line status
$sql_update_mtr_ls1 = "UPDATE 	mtr_ls1
						SET 	mtr_ls1_status = 'A',
								mbl_audit_user='".$audit_user."',		
								mbl_audit_date=getdate()
						WHERE 	mtr_ls1.mst_RowID = (Select rowid from mtr_mst where mtr_mst.mtr_mst_mtr_no = '".$mtr_no."' and mtr_mst.site_cd = '".$site_cd."')";
		
$stmt_update_mtr_ls1 = sqlsrv_query( $conn, $sql_update_mtr_ls1);		
					
if( !$stmt_update_mtr_ls1 ) {
     $error_message = "Error update table (mtr_ls1)";
	 returnError($error_message);
     die( print_r( sqlsrv_errors(), true));
}	

//Update mtr_app
$sql_update_mtr_app = "UPDATE 	mtr_app
						SET 	mtr_app_date = getdate(),
								mtr_app_status = 'Y',
								mtr_app_desc = '* Approved **',
								mbl_audit_user='".$audit_user."',		
								mbl_audit_date=getdate()
						WHERE 	mtr_app.site_cd = '".$site_cd."'
						AND		mst_RowID = (Select rowid from mtr_mst where mtr_mst.mtr_mst_mtr_no = '".$mtr_no."' and mtr_mst.site_cd = '".$site_cd."')
						AND		mtr_app_status = 'P'";
		
$stmt_update_mtr_app = sqlsrv_query( $conn, $sql_update_mtr_app);		
					
if( !$stmt_update_mtr_app ) {
     $error_message = "Error update table (mtr_app)";
	 returnError($error_message);
     die( print_r( sqlsrv_errors(), true));
}

//Update mtr_det
$sql_update_mtr_det = "UPDATE 	mtr_det
						SET 	mtr_det_approver = '".$audit_user."',
								mtr_det_appr_date = getdate(),
								mbl_audit_user='".$audit_user."',		
								mbl_audit_date=getdate()
						WHERE 	mtr_det.site_cd = '".$site_cd."'
						AND		mst_RowID = (Select rowid from mtr_mst where mtr_mst.mtr_mst_mtr_no = '".$mtr_no."' and mtr_mst.site_cd = '".$site_cd."')
						AND		mtr_det_approver IS NULL
						AND		mtr_det_appr_date IS NULL";
		
$stmt_update_mtr_det = sqlsrv_query( $conn, $sql_update_mtr_app);		
					
if( !$stmt_update_mtr_app ) {
     $error_message = "Error update table (mtr_app)";
	 returnError($error_message);
     die( print_r( sqlsrv_errors(), true));
}





	
} //2nd loop
	
$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) );


// Remove this in standard, this is only for the Etika
// if ($mtr_mst_status <> 'M4' & $balance_qty == 0){
	
	//Update MR Balace
	// $sql = "UPDATE 		mtr_mst
			// SET 		mtr_mst_mr_status = 'M4',
						// mtr_mst_cmpl_date = GetDate()
			// WHERE		mtr_mst.site_cd = '".$site_cd."'
			// AND 		mtr_mst.mtr_mst_mtr_no = '".$mtr_no."'" ;
	
	// $stmt = sqlsrv_query( $conn, $sql);				
							
	// if( !$stmt ) {
		 // $error_message = "Error update table (MR Balance)";
		 // returnError($error_message);
		 // die( print_r( sqlsrv_errors(), true));
	// }
	
	// $sql = "UPDATE 		mtr_ls2
			// SET 		mtr_ls2_numeric1 = 0,
						// mtr_ls2_datetime2 = GetDate(),
						// audit_user = '".$audit_user."',
						// audit_date =  GETDATE()
			// WHERE		mtr_ls2.site_cd = '".$site_cd."'
			// AND 		mtr_ls2.mtr_ls2_varchar1 = '".$mtr_no."'
			// AND 		mtr_ls2.mtr_ls2_varchar2 = '".$mr_status."'" ;
			
	
	// $stmt = sqlsrv_query( $conn, $sql);				
							
	// if( !$stmt ) {
		 // $error_message = "Error update table (MR Status Audit Update)";
		 // returnError($error_message);
		 // die( print_r( sqlsrv_errors(), true));
	// }
	
	// $sql = "INSERT 	mtr_ls2 (	
					// site_cd ,
					// mst_RowID,
					// mtr_ls2_varchar1 ,
					// mtr_ls2_varchar2 ,
					// mtr_ls2_varchar3 ,
					// mtr_ls2_datetime1 ,                                    
					// mtr_ls2_datetime2 ,                                       
					// mtr_ls2_numeric1 ,                                   
					// audit_user ,    
					// audit_date ) 						
			// VALUES	('".$site_cd."',
					// '".$mtr_mst_rowid."',
					// '".$mtr_no."',
					// 'M4',
					// '".$audit_user."',
					// GETDATE(),
					// NULL,
					// NULL,
					// '".$audit_user."',
					// GETDATE()) ";

	// $stmt = sqlsrv_query( $conn, $sql);				
							
	// if( !$stmt ) {
		 // $error_message = "Error update table (MR Status Audit Update)";
		 // returnError($error_message);
		 // die( print_r( sqlsrv_errors(), true));
	// }			
	
// }


} //1st loop

if ($valid) {	
	returnData('');	
}

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

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

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