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

$error_message;
$valid = true;

//Header
$site_cd;
$audit_user;
$isu_empl_id;
$remark;
$return_date;

//Details
$stock_no;
$itm_mtu_desc;
$stock_location;
$itm_mtu_used_uom;
$itm_mtu_used_qty;
$itm_mtu_serial_no;
$itm_mtu_mtr_no;
$itm_mtu_mtr_lineno;
$itm_mtu_wo;
$itm_mtu_assetno;
$itm_mtu_chg_costcenter;
$itm_mtu_chg_account;
$itm_mtu_crd_costcenter; 	
$itm_mtu_crd_account; 
$itm_mtu_po_costcenter;
$itm_mtu_po_account;
$itm_mtu_po_crd_costcenter;
$itm_mtu_po_crd_account;
$itm_mtu_item_cost;
$itm_mtu_mtc_id;
$itm_mtu_rowid;
$ret_qty;
$fifo_avg;
$return_cost;
$avg_cost;
$latest_issue_price;
$surcharge = 0;
$li_grn_line = 0;
$ldc_raw_cost;
$ldc_ext_cost;
$itm_loc_inc_ttloh = 0;
$ls_ret_doc = "";
$wkomst_RowID;
$mtr_RowID;
$ast_mst_RowID;
$itm_mtc_tax_account ;
// 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;	
	$audit_user			= $Heade->mst_empl_id;
	$isu_empl_id		= $Heade->isu_empl_id;
	$LOGINID			= $Heade->LOGINID;
	$remark				= $Heade->remark;
	$return_date		= $Heade->return_date;
	
	/* echo $site_cd ,',' ,$audit_user,',' ,$isu_empl_id,',' ,$remark,',' ,$issue_date; */	
	
	
	foreach($result->Details as $Detail){
		
		$stock_no 					= $Detail->itm_mtu_stockno;
		$itm_mtu_desc 				= $Detail->itm_mtu_desc;
		$stock_location 			= $Detail->itm_mtu_stk_locn;
		$itm_mtu_used_uom 			= $Detail->itm_mtu_used_uom;
		$itm_mtu_used_qty 			= $Detail->itm_mtu_used_qty;
		$itm_mtu_serial_no 			= $Detail->itm_mtu_serial_no;
		$itm_mtu_mtr_no 			= $Detail->itm_mtu_mtr_no;
		$itm_mtu_mtr_lineno 		= $Detail->itm_mtu_mtr_lineno;
		$itm_mtu_wo 				= $Detail->itm_mtu_wo;
		$itm_mtu_assetno 			= $Detail->itm_mtu_assetno;
		
		$itm_mtu_chg_costcenter 	= $Detail->itm_mtu_chg_costcenter;
		$itm_mtu_chg_account 		= $Detail->itm_mtu_chg_account;
		
		$itm_mtu_crd_costcenter 	= $Detail->itm_mtu_crd_costcenter;
		$itm_mtu_crd_account 		= $Detail->itm_mtu_crd_account;
		
		$itm_mtu_po_costcenter 		= $Detail->itm_mtu_po_costcenter;
		$itm_mtu_po_account 		= $Detail->itm_mtu_po_account;
		
		$itm_mtu_po_crd_costcenter 	= $Detail->itm_mtu_po_crd_costcenter;
		$itm_mtu_po_crd_account 	= $Detail->itm_mtu_po_crd_account;
		
		$itm_mtu_item_cost 			= $Detail->itm_mtu_item_cost;
		$itm_mtu_mtc_id 			= $Detail->itm_mtu_mtc_id;
		$itm_mtu_rowid 				= $Detail->RowID;
		$ret_qty 					= $Detail->ret_qty;
		
		if( $ls_ret_doc == '' )
		{
			
		//Select document number RET			
		$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 = 'RET'";

		$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)) {
				$ls_ret_doc = $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 = 'RET'";			
		$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;
		
		$return_cost = ( $ret_qty * $itm_mtu_item_cost ); 
		
		/* echo $stock_no ,',',$itm_mtu_desc ,',',$stock_location ,',',$itm_mtu_used_uom ,',',$itm_mtu_used_qty ,',',
		$itm_mtu_serial_no ,',',$itm_mtu_mtr_no ,',',$itm_mtu_mtr_lineno ,',',$itm_mtu_wo ,',',$itm_mtu_assetno ,',',$itm_mtu_chg_costcenter ,',',
		$itm_mtu_chg_account ,',',$itm_mtu_po_costcenter,',',$itm_mtu_po_crd_account,',',$itm_mtu_item_cost,',',$itm_mtu_mtc_id,',',
		$RowID,',',$ret_qty; */
		
$sql = "SELECT 	itm_mst_type,
				itm_mst_ttl_oh,
				itm_det.itm_det_rcv_uom,
				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
	FROM 	itm_mst,itm_det
	WHERE	( itm_mst.RowID = itm_det.mst_RowID )
	AND		( itm_mst.site_cd = '".$site_cd."') 
	AND		( itm_mst.itm_mst_stockno = '".$stock_no."')";
	

$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_type 			= $row['itm_mst_type'];
		$itm_mst_ttl_oh 		= $row['itm_mst_ttl_oh'];
		$itm_det_rcv_uom 		= $row['itm_det_rcv_uom'];
		$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'];
		$ll_stk_RowID 			= $row['RowID'];


/* echo $itm_mst_type ,',',$itm_mst_ttl_oh ,',',$itm_det_rcv_uom ,',',$itm_det_cr_code ,',',$itm_det_item_cost ,',',$itm_det_std_cost ,',',$itm_det_avg_cost ,',',$RowID; */
	
     }
} while ( sqlsrv_next_result($stmt) );	
		

$sql = "SELECT	itm_loc_stock_cost_flag,itm_loc_inc_ttloh	
		FROM	itm_loc
		WHERE	site_cd = '".$site_cd."'
		AND		mst_RowID = '".$ll_stk_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'];
		$itm_loc_inc_ttloh 	= $row['itm_loc_inc_ttloh'];	
		
		//echo $itm_loc_stock_cost_flag ,',',$itm_loc_inc_ttloh;
	 }
} while ( sqlsrv_next_result($stmt) );	


$sql = "SELECT	itm_mtc_rcv_date,
				itm_mtc_pono,
				itm_mtc_po_lineno,
				itm_mtc_tax_cd,
				itm_mtc_tax_rate,
				itm_mtc_tax_account	
		FROM   	itm_mtc
		WHERE 	site_cd = '".$site_cd."'
		AND     rowid = '".$itm_mtu_mtc_id."'";
	
$stmt = sqlsrv_query( $conn, $sql);		
				
if( !$stmt ) {
     $error_message = "Error select 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_date 		= $row['itm_mtc_rcv_date'];
		$itm_mtc_pono 			= $row['itm_mtc_pono'];	
		$itm_mtc_po_lineno 		= $row['itm_mtc_po_lineno'];
		$itm_mtc_tax_cd 		= $row['itm_mtc_tax_cd'];
		$itm_mtc_tax_rate 		= $row['itm_mtc_tax_rate'];
		$itm_mtc_tax_account 	= $row['itm_mtc_tax_account'];	
		
		//echo $itm_mtc_tax_rate;	
		
     }
} while ( sqlsrv_next_result($stmt) );	

If ($itm_loc_stock_cost_flag = "" OR IS_NULL($itm_loc_stock_cost_flag)){
	$itm_loc_stock_cost_flag = '1';
}


$avg_cost = (( $itm_mst_ttl_oh * $itm_det_item_cost ) + ( $return_cost )) / ( $itm_mst_ttl_oh + $ret_qty );

//echo $cost_flag ,',',$itm_loc_inc_ttloh,',',$avg_cost;
//echo $avg_cost;

switch ($itm_det_cr_code) {
  case 'AVG':
    $latest_itm_cost = $itm_det_avg_cost;
	//echo $latest_itm_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 );
//echo $latest_issue_price,',';
$ldc_raw_cost = $ret_qty  * $itm_mtu_item_cost;
//echo $ldc_raw_cost,',';
$ldc_ext_cost  = $ret_qty  * $itm_mtu_item_cost;
//echo $ldc_ext_cost;

// Receive In Repair Location
switch ($cost_flag) {
  case "1":
    switch ($itm_loc_inc_ttloh) {
	  case "1":	  
	  //update itm_mst
		$sql = "UPDATE 	itm_mst
				SET 	itm_mst_ttl_oh = COALESCE(itm_mst_ttl_oh, 0) + ".$ret_qty.",	
						itm_mst_issue_price = ".$latest_issue_price."
				WHERE	( itm_mst.RowID = ".$ll_stk_RowID." ) ";

		$stmt = sqlsrv_query( $conn, $sql);
		
		if( !$stmt ) {
			$error_message = "Error update table (itm_mst)";
			returnError($error_message);
			die( print_r( sqlsrv_errors(), true));
		} 
	  
		//update itm_det
		$sql = "UPDATE 	itm_det
				SET 	itm_det_ttl_oh = COALESCE(itm_det_ttl_oh, 0) + ".$ret_qty.",
						itm_det_ytd_usage = COALESCE(itm_det_ytd_usage, 0) - ".$ret_qty.",
						itm_det_item_cost = ".$latest_itm_cost.",
						itm_det_issue_price = ".$latest_issue_price.",
						itm_det_lastactdate = GetDate(),
						mbl_audit_user='".$LOGINID."',		
						mbl_audit_date=getdate()
				WHERE	( itm_det.mst_RowID = ".$ll_stk_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;		
	  case "0": 
	   //update itm_mst
		$sql = "UPDATE 	itm_mst
				SET 	itm_mst_issue_price = ".$latest_issue_price."
				WHERE	( itm_mst.RowID = ".$ll_stk_RowID." ) ";

		$stmt = sqlsrv_query( $conn, $sql);		
		if( !$stmt ) {
			  $error_message = "Error update table (itm_mst)";
			  returnError($error_message);
			  die( print_r( sqlsrv_errors(), true));
		 } 
		//update itm_det
		 $sql = "UPDATE 	itm_det
				SET 		itm_det_ytd_usage = COALESCE(itm_det_ytd_usage, 0) - ".$ret_qty.",		
							itm_det_item_cost = ".$latest_itm_cost.",
							itm_det_issue_price = ".$latest_issue_price.",
							itm_det_lastactdate = GetDate(),
							mbl_audit_user='".$LOGINID."',		
							mbl_audit_date=getdate()
				WHERE	( itm_det.mst_RowID = ".$ll_stk_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:
	}
    break;
  case "0":
	switch ($itm_loc_inc_ttloh) {
	  case "1":
	  //update itm_mst
		 $sql = "UPDATE 	itm_mst
				SET 		itm_mst_ttl_oh = COALESCE(itm_mst_ttl_oh, 0) + ".$ret_qty.",
							mbl_audit_user='".$LOGINID."',		
							mbl_audit_date=getdate()
				WHERE	( itm_mst.RowID = ".$ll_stk_RowID." ) ";

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

		 if( !$stmt ) {
			  $error_message = "Error update table (itm_mst)";
			  returnError($error_message);
			  die( print_r( sqlsrv_errors(), true));
		 }
		 
		 
		//update itm_det
		 $sql = "UPDATE 	itm_det
				SET 		itm_det_ttl_oh = COALESCE(itm_det_ttl_oh, 0) + ".$ret_qty.",
							itm_det_ttl_repair = COALESCE(itm_det_ttl_repair, 0) + ".$ret_qty.",
							itm_det_ytd_usage = COALESCE(itm_det_ytd_usage, 0) - ".$ret_qty.",						
							itm_det_lastactdate = GetDate(),
							mbl_audit_user='".$LOGINID."',		
							mbl_audit_date=getdate()
				WHERE	( itm_det.mst_RowID = ".$ll_stk_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;
	  case "0":
		//update itm_det
		 $sql = "UPDATE 	itm_det
				SET 		itm_det_ytd_usage = COALESCE(itm_det_ytd_usage, 0) - ".$ret_qty.",		
							itm_det_ttl_repair = COALESCE(itm_det_ttl_repair, 0) + ".$ret_qty.",			
							itm_det_lastactdate = GetDate(),
							mbl_audit_user='".$LOGINID."',		
							mbl_audit_date=getdate()
				WHERE	( itm_det.mst_RowID = ".$ll_stk_RowID.")";

		$stmt = sqlsrv_query( $conn, $sql);
		//echo'0 itm_loc_inc_ttloh itm_det-1 ='.$sql;
		 if( !$stmt ) {
			  $error_message = "Error update table (itm_det)";
			  returnError($error_message);
			  die( print_r( sqlsrv_errors(), true));
		 }
		break;
	  default:
	}
    break;
  default:
}
//update itm_mtu
$sql = "UPDATE itm_mtu
		SET 	itm_mtu_used_qty = COALESCE(itm_mtu_used_qty, 0) - ".$ret_qty.",
				mbl_audit_user='".$LOGINID."',		
				mbl_audit_date=getdate()
		WHERE	( itm_mtu.site_cd = '".$site_cd."')
		And 	( itm_mtu.RowID = ".$itm_mtu_rowid." ) ";

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

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


//update itm_loc
$sql = "UPDATE itm_loc
		SET 	itm_loc_oh_qty = COALESCE(itm_loc_oh_qty, 0) + ".$ret_qty.",itm_loc_lastactdate = GetDate(),
				mbl_audit_user='".$LOGINID."',		
				mbl_audit_date=getdate()
		WHERE	( itm_loc.mst_RowID = ".$ll_stk_RowID.")
		And 	( itm_loc_stk_loc = '".$stock_location."' ) ";

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

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



//insert itm_mtc
$sql_insert_itm_mtc = "INSERT INTO itm_mtc
			( 	site_cd,							itm_mtc_grn_no,						itm_mtc_grn_itm_no,			itm_mtc_rcv_date,			
				itm_mtc_rcv_empl_id,				itm_mtc_stockno,					itm_mtc_stk_locn,			itm_mtc_uom,				
				itm_mtc_costcenter,					itm_mtc_account,					itm_mtc_crd_costcenter,		itm_mtc_crd_account,
				itm_mtc_tax_account,				itm_mtc_pono,						itm_mtc_po_lineno,			itm_mtc_nonstkitm,					
				itm_mtc_rcv_qty,					itm_mtc_rcv_cost,					itm_mtc_isu_qty,			itm_mtc_inv_qty,				
				itm_mtc_inv_cost,					itm_mtc_tax_cd,						itm_mtc_tax_rate,			itm_mtc_tax_value,
				audit_user,							audit_date,							mbl_audit_user,				mbl_audit_date  	)
	VALUES (	'".$site_cd."',						'".$ls_ret_doc."',					'".$li_grn_line."',					GetDate(),
				'".$isu_empl_id."', 				'".$stock_no."',					'".$stock_location."',				'".$itm_mtu_used_uom."',
				'".$itm_mtu_po_costcenter."',		'".$itm_mtu_po_crd_account."',		'".$itm_mtu_po_crd_costcenter."',	'".$itm_mtu_po_crd_account."',
				'".$itm_mtc_tax_account."',			'".$itm_mtc_pono."',				'".$itm_mtc_po_lineno."',				'N',								
				'".$ret_qty."',						'".$itm_mtu_item_cost."',			0,										0,				
				'".$itm_mtu_item_cost."',			'".$itm_mtc_tax_cd."',				0,										0, 	
				'".$audit_user."',					GetDate(),							'".$LOGINID."',					GetDate()   )";

//echo $sql_insert_itm_mtc;
$stmt_insert_itm_mtc = sqlsrv_query( $conn, $sql_insert_itm_mtc);

//echo $sql_insert_itm_mtc;
if( !$stmt_insert_itm_mtc ) {
	 $error_message = "Error insert table (itm_mtc)";
	 returnError($error_message);
	 die( print_r( sqlsrv_errors(), true));
}


//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
						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'];
	//echo $fifo_avg;
	}
} while ( sqlsrv_next_result($stmt_select_fifo_avg) );					
sqlsrv_free_stmt( $stmt_select_fifo_avg);


$sql_insert_itm_trx = "INSERT INTO itm_trx 
					( 	site_cd,						itm_trx_doc_no, 				itm_trx_trx_type, 				itm_trx_curr_date, 				itm_trx_trx_date,
						itm_trx_isu_empl_id,			itm_trx_rcv_empl_id, 			itm_trx_stockno, 				itm_trx_desc, 					itm_trx_partno,				
						itm_trx_com_code,				itm_trx_isu_qty, 				itm_trx_rcv_qty,				itm_trx_ord_qty, 				itm_trx_rtn_qty, 			
						itm_trx_bo_qty, 				itm_trx_chg_costcenter, 		itm_trx_chg_account, 			itm_trx_crd_costcenter,			itm_trx_crd_account,		
						itm_trx_assetno, 				itm_trx_wo, 					itm_trx_mtlrqnnum, 				itm_trx_item_cost, 				itm_trx_uom, 				
						itm_trx_cnv_qty,				itm_trx_pkguom, 				itm_trx_ext_cost, 				itm_trx_porqnnum, 				itm_trx_approver, 			
						itm_trx_supplier, 				itm_trx_pono, 					itm_trx_po_lineno,				itm_trx_ttl_oh, 				itm_trx_stk_locn, 			
						itm_trx_oh_qty, 				itm_trx_comments, 				itm_trx_to_stk_locn, 			itm_trx_mtlrqn_lineno, 			itm_trx_grn_no, 			
						itm_trx_grn_itm_no, 			itm_trx_posted, 				itm_trx_avg_cost, 				itm_trx_std_cost, 				itm_trx_last_cost, 			
						itm_trx_consigned, 				itm_trx_receive_doc_note,		itm_trx_inv_qty, 				itm_trx_inv_uom,				itm_trx_liability_acc, 		
						itm_trx_raw_cost, 				itm_trx_rcv_cost, 				itm_trx_rcv_date, 				itm_trx_pkg_slip_no, 			itm_trx_mt_special_idno,
						itm_trx_cost_cat_id, 			itm_trx_mtcs_ref_id, 			itm_trx_return_fee, 			itm_trx_mtrtnsup_ref_id,		itm_trx_mtrtnsup_lineno,	
						itm_trx_mtns_ref_id, 			itm_trx_inv_id, 				itm_trx_inv_lineno, 			itm_trx_rev_inv, 				itm_trx_ret_supp, 			
						itm_trx_mkey, 					itm_trx_status,					itm_trx_projectid, 				itm_trx_login_id, 				itm_trx_cnx_qty, 			
						itm_trx_fifo_avg_cost,			itm_trx_remark,					audit_user, 					audit_date,						mbl_audit_user,	
						mbl_audit_date ) 
				VALUES 
					( 	'".$site_cd."',					'".$ls_ret_doc."', 				'MT51', 						GetDate(),						'".$return_date."',					
						'".$isu_empl_id."',				'', 							'".$stock_no."',				'".$itm_mtu_desc."',			'', 								
						'',								0,								0,								0,								".$ret_qty.",								
						0,								'".$itm_mtu_chg_costcenter."',	'".$itm_mtu_chg_account."',		'".$itm_mtu_crd_costcenter."',	'".$itm_mtu_crd_account."',								
						'".$itm_mtu_assetno."',			'".$itm_mtu_wo."',				'".$itm_mtu_mtr_no."',			".$itm_mtu_item_cost.",			'".$itm_mtu_used_uom."',				
						0,								'',								".$ldc_ext_cost.",				'',								'',								
						'',								'".$itm_mtc_pono."',			'".$itm_mtc_po_lineno."',		0,								'".$stock_location."',					
						0,								'',								'',								'".$itm_mtu_mtr_lineno."',		'".$ls_ret_doc."',								
						'".$li_grn_line."',				'',								".$avg_cost.",					".$itm_det_std_cost.",			".$itm_det_last_cost.",								
						'',								0,								NULL,							'',								'',								
						".$ldc_raw_cost.",				0,								0,								0,								'',								
						'',								0,								0,								0,								0,								
						0,								0,								0,								'',								'',								
						'',								'',								'',								'".$audit_user."',				0,								
						".$fifo_avg.",				'".$remark."',					'".$audit_user."',				GetDate(),							'".$LOGINID."',				GetDate() )";

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

if ($itm_det_cr_code == 'FIFO') {	
	
	switch ($cost_flag) {
	  case '1':
		$sql = "UPDATE 	itm_mst
				SET 	itm_mst_issue_price = ".$fifo_avg." ,
						mbl_audit_user='".$LOGINID."',		
						mbl_audit_date=getdate()
				WHERE	( itm_mst.RowID = ".$ll_stk_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 = ".$fifo_avg.",
							itm_det_issue_price = ".$fifo_avg.",
							itm_det_lastactdate = GetDate(),
							mbl_audit_user='".$LOGINID."',		
							mbl_audit_date=getdate()
				WHERE	( itm_det.mst_RowID = ".$ll_stk_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:
	}
	
}

if($itm_mtu_wo != ""){

$sql = "SELECT	RowID	
		FROM	wko_mst
		WHERE	wko_mst.site_cd  = '".$site_cd."'
		AND		wko_mst.wko_mst_wo_no = '".$itm_mtu_wo."'";	

$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)) {
		$wkomst_RowID = $row['RowID'];
		//echo $wko_mst_RowID;
	 }
} while ( sqlsrv_next_result($stmt) );	



$sql = "UPDATE 	wko_det
		SET 	wko_det_mtl_cost = COALESCE(wko_det_mtl_cost ,0) - ".$ldc_ext_cost." ,
				mbl_audit_user='".$LOGINID."',		
				mbl_audit_date=getdate()
		WHERE	( wko_det.mst_RowID = ".$wkomst_RowID." )";

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

}

if($itm_mtu_mtr_no != ""){

$sql = "SELECT	RowID	
		FROM	mtr_mst
		WHERE	mtr_mst.site_cd  = '".$site_cd."'
		AND		(mtr_mst.mtr_mst_mtr_no = '".$itm_mtu_mtr_no."')";
	

$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)) {
		$mtr_RowID 	= $row['RowID'];
		//echo $mtr_RowID;
	 }
} while ( sqlsrv_next_result($stmt) );	

$sql = "UPDATE 	mtr_ls1
		SET 	mtr_ls1_rcv_qty = COALESCE(mtr_ls1_rcv_qty ,0) - ".$ret_qty.",
				mtr_ls1_bo_qty = COALESCE(mtr_ls1_bo_qty ,0) + ".$ret_qty.",
				mbl_audit_user='".$LOGINID."',		
				mbl_audit_date=getdate()
		WHERE	( mtr_ls1.site_cd = '".$site_cd."' )
		AND		mtr_ls1.mst_RowID = ".$mtr_RowID."
		AND		mtr_ls1.mtr_ls1_mtr_lineno = '".$itm_mtu_mtr_lineno."'";

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

}


if($itm_mtu_assetno != ""){

$sql = "SELECT	RowID	
		FROM	ast_mst
		WHERE	ast_mst.site_cd  = '".$site_cd."'
		AND		(ast_mst.ast_mst_asset_no = '".$itm_mtu_assetno."')";
	
//echo $sql;
$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)) {
		$ast_mst_RowID = $row['RowID'];
		//echo 'ast_mst_RowID = '.$ast_mst_RowID;
	 }
} while ( sqlsrv_next_result($stmt) );	

$sql = "UPDATE 	ast_det
		SET 	ast_det_ltdmtlcost = COALESCE(ast_det_ltdmtlcost ,0) - ".$ldc_ext_cost.",
				mbl_audit_user='".$LOGINID."',		
				mbl_audit_date=getdate()
		WHERE	( ast_det.mst_RowID = '".$ast_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));
}

}

/*Update Budget Amount*/
/*Charging to header costcenter and account*/
$charge_valid = f_update_budget($site_cd,$return_date, $itm_mtu_chg_costcenter, $itm_mtu_chg_account,  "CHARGE", $ldc_ext_cost, $conn, $audit_user);
/*Crediting to the item costcenter and account*/
$credit_valid=  f_update_budget($site_cd,$return_date, $itm_mtu_chg_costcenter, $itm_mtu_chg_account,  "CREDIT", $ldc_ext_cost, $conn, $audit_user);



}//2nd loop	end
}//1st Loop end

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

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

function returnData($json){
	
	$returnData = array(
	'status' => 'SUCCESS',
	'message' => 'Return 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();
}





?>