<?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;
	
	foreach($result->Header as $Heade){
		
		$site_cd= $Heade->site_cd;
		$wko_RowID= $Heade->wko_RowID;
		$wko_mst_wo_no= $Heade->wko_mst_wo_no;
		$wko_mst_assetno= $Heade->wko_mst_assetno;
		$wko_mst_chg_costcenter= $Heade->wko_mst_chg_costcenter_id;
		
		$wko_det_laccount= $Heade->wko_det_laccount;
		$wko_det_caccount= $Heade->wko_det_caccount;
		$wko_det_maccount= $Heade->wko_det_maccount_id;
		
		$remark= $Heade->remark;
		
		$Issue_to =$Heade->issue_to_id;
		$Issue_date =$Heade->issue_date;
		
		$audit_user= $Heade->audit_user;
		$audit_date= $Heade->audit_date;
		$LogingID= $Heade->LOGINID;
		
		$type= $Heade->type;
		
		if($type === 'G'){
			
			$data2 = array();
		
			$y =-1;
		
			$x= 0;
			
			foreach($result->Details as $Detail){
				
				$stockno = $Detail->stock_no;
				$stockloc = $Detail->stock_location;
				$description = $Detail->itm_mst_desc;
				$uom = $Detail->rcv_uom;
				$issueqty = '0.00';
				$quantity = $Detail->rcv_qty;
				$chargecostcenter = $Detail->itm_mst_costcenter;
				$chargeaccount = $Detail->itm_mst_account;
				$itemcost = $Detail->itm_mst_issue_price;
				$Assetno = $Detail->Assetno;
				
				$x = $x + 1;
				if($x === 1 || $Assetno <> $old_assetno){
					
					$ldc_tot_costs = 0;
					$y = $y + 1;
					
					$sql = "Select cnt_mst_prefix + SUBSTRING(CONVERT(VARCHAR(7), cnt_mst_counter + 1000000), 2, 6)  ls_doc_no
							From 	cnt_mst WITH (UPDLOCK)
							Where 	site_cd ='".$site_cd."'
							And 	cnt_mst_module_cd =  'MTR'
							UPDATE 	cnt_mst WITH (UPDLOCK)
							SET 		cnt_mst_counter = cnt_mst_counter + 1
							WHERE 	site_cd ='".$site_cd."' 
							AND 	cnt_mst_module_cd = 'MTR'";			
					
					
					$stmt = sqlsrv_query( $conn, $sql);			
					if( !$stmt ) {
						$error_message = "Error update table (itm_mst)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
					}
					do {
						while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {	
						
							$mtr_mst_mtr_no = $row['ls_doc_no'];
						}
					} while ( sqlsrv_next_result($stmt));
					
					$sql = "SELECT 	dft_mst_mtr_sts,dft_mst_mr_release_for_app,dft_mst_mtr_email_requestor,dft_mst_mtr_email
							FROM	dft_mst(NOLOCK)
							WHERE	( dft_mst.site_cd = '".$site_cd."' )";

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

					do {
						while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
							$ls_mr_status = $row['dft_mst_mtr_sts'];	
							$dft_mst_mr_release_for_app = $row['dft_mst_mr_release_for_app'];	
							$dft_mst_mtr_email_requestor = $row['dft_mst_mtr_email_requestor'];	
							$dft_mst_mtr_email = $row['dft_mst_mtr_email'];	
						}
					} while ( sqlsrv_next_result($stmt) );

					if(empty($mtr_sts_status)){
						
						$sql = "SELECT TOP 1 mtr_sts.mtr_sts_status 
								FROM mtr_sts (NOLOCK)
								WHERE mtr_sts.site_cd ='".$site_cd."' 
								AND mtr_sts.mtr_sts_st_cat ='MR' 
								AND mtr_sts.mtr_sts_status_type ='OPEN' 
								AND mtr_sts.mtr_sts_disable_flag ='0'";


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

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

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

					$sql_insert_mtr_mst = "INSERT mtr_mst 
							(	site_cd ,					mtr_mst_mtr_no ,			mtr_mst_assetno ,				mtr_mst_costcenter ,				
								mtr_mst_account ,			mtr_mst_org_date ,			mtr_mst_req_date ,				mtr_mst_cmpl_date ,
								mtr_mst_wo_no ,				mtr_mst_requester ,			mtr_mst_entered_by ,			mtr_mst_status ,
								mtr_mst_mr_status ,			mtr_mst_email_notification ,mtr_mst_note ,					mtr_mst_tot_cost ,
								mtr_mst_release_for_app ,	mtr_mst_email_requestor ,	mtr_mst_create_by ,				mtr_mst_create_date ,			
								audit_user ,				audit_date,					mbl_audit_user,					mbl_audit_date ) 
					VALUES 	(	?,							?,							?,								?,		
								?,							getDate(),					getDate(),						Null,							
								?,							?,							?,								'W',						
								'MTR',						?,							Null,							'0',
								?,							?,							?,								getDate(),
								?,							getDate(),					?,							getDate())";
												
												
					$params_mtr_mst = array($site_cd,$mtr_mst_mtr_no,$Assetno,$wko_mst_chg_costcenter,$wko_det_maccount,$wko_mst_wo_no,$audit_user,$audit_user,$dft_mst_mtr_email,$dft_mst_mr_release_for_app,$dft_mst_mtr_email_requestor,$LogingID,$LogingID,$LogingID);				
					$stmt = sqlsrv_query( $conn, $sql_insert_mtr_mst,$params_mtr_mst);

					if( !$stmt ) {
						$error_message = "Error insert table (INSERT Table mtr_mst)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
					}	
					sqlsrv_free_stmt( $stmt);		

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


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

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

					do {
						 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
							 
							$ll_RowID = $row['RowID'];	
							
						 }
					} while ( sqlsrv_next_result($stmt) );	
					
					$sql_insert_mtr_det = "INSERT mtr_det 
												(	 site_cd,		mst_RowID, 		audit_user, 		audit_date,					mbl_audit_user,					mbl_audit_date )
										VALUES	(	 ?,				?,				?,					GETDATE(),					?,								GETDATE());";
											
											
					$params_mtr_det = array($site_cd,$ll_RowID,$LogingID,$LogingID);				
					$stmt = sqlsrv_query( $conn, $sql_insert_mtr_det,$params_mtr_det);

					if( !$stmt ) {
						$error_message = "Error insert table (INSERT Table mtr_det)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
					}	
					sqlsrv_free_stmt( $stmt);	
				
		
		
					$sql_insert_mtr_ls2 = "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,				mbl_audit_user,			mbl_audit_date ) 
							VALUES  (		?,						?,						?,						'MTR',					
											?,						GETDATE ( ), 			 NULL,					 NULL,					
											?,						GETDATE ( ),			?,						GETDATE ( ))";
												
												
					$params_mtr_ls2 = array($site_cd,$ll_RowID,$mtr_mst_mtr_no,$audit_user,$LogingID,$LogingID);							
					$stmt = sqlsrv_query( $conn, $sql_insert_mtr_ls2,$params_mtr_ls2);

					if( !$stmt ) {
						$error_message = "Error insert table (INSERT Table mtr_ls2)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
					}	
					sqlsrv_free_stmt( $stmt);
					
					$ll_row++;
					
					
					$sql_insert_mtr_ls1 = "INSERT mtr_ls1 
											(	site_cd ,					mst_RowID ,					mtr_ls1_mtr_lineno ,			mtr_ls1_stockno , 
												mtr_ls1_stk_locn ,			mtr_ls1_mtl_uom ,			mtr_ls1_desc ,					mtr_ls1_status , 
												mtr_ls1_chg_costcenter ,	mtr_ls1_chg_account ,		mtr_ls1_req_qty ,				mtr_ls1_rcv_qty , 
												mtr_ls1_bo_qty ,			mtr_ls1_clear_qty ,			mtr_ls1_item_cost ,				mtr_ls1_po_no , 
												mtr_ls1_po_lineno ,			mtr_ls1_rec_supplier ,		mtr_ls1_supplier_partno ,		audit_user , 
												audit_date,					mbl_audit_user,				mbl_audit_date  )
									VALUES (	? ,							?,							?,								?, 
												? ,							?,							?,								'W' , 
												?,							?,							?,								0, 
												?,							0,							?,								NULL , 
												NULL ,						 NULL ,						NULL ,							?, 
												GetDate( ),					?,							GetDate( ) ) ";
									
									
					//echo $sql_insert_mtr_ls1;
					$params_mtr_ls1 = array($site_cd,$ll_RowID,'1',$stockno,$stockloc,$uom,$description,$chargecostcenter,$chargeaccount,$quantity,$quantity,$itemcost,$LogingID,$LogingID);			
					$stmt = sqlsrv_query( $conn, $sql_insert_mtr_ls1,$params_mtr_ls1);

					if( !$stmt ) {
						$error_message = "Error insert table (INSERT Table mtr_ls1)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
					}	
					sqlsrv_free_stmt( $stmt);
			
			
			
					$sql_insert_wko_ls2 = "INSERT INTO wko_ls2 
							(	site_cd,				wko_ls2_assetno,			wko_ls2_activity_code,			wko_ls2_stockno,			wko_ls2_desc, 
								wko_ls2_qty_needed,		wko_ls2_item_cost,			wko_ls2_mr_no,					wko_ls2_mr_lineno,			wko_ls2_rec_supplier, 
								wko_ls2_act_qty,		wko_ls2_act_cost,			wko_ls2_mtl_uom,				wko_ls2_pr_no,				wko_ls2_pr_lineno, 
								wko_ls2_po_no,			wko_ls2_po_lineno,			wko_ls2_craft,					wko_ls2_nonrefpono,			wko_ls2_com_code, 
								wko_ls2_taxable,		wko_ls2_chg_costcenter,		wko_ls2_chg_account,			wko_ls2_stk_locn,			wko_ls2_info_src, 
								wko_ls2_inv_no,			wko_ls2_inv_lineno,			wko_ls2_varchar1,				wko_ls2_varchar2,			wko_ls2_varchar3, 
								wko_ls2_varchar4,		wko_ls2_varchar5,			wko_ls2_numeric1,				wko_ls2_numeric2,			wko_ls2_numeric3, 
								wko_ls2_numeric4,		wko_ls2_numeric5,			wko_ls2_datetime1,				wko_ls2_datetime2,			wko_ls2_datetime3, 
								wko_ls2_datetime4,		wko_ls2_datetime5,			audit_user,						audit_date,					column1, 
								column2,				column3,					column4,						column5,					mst_RowID,
								mbl_audit_user,			mbl_audit_date)
					VALUES (	?,						?,							NULL,							?,							?,
								?,						?,							?,								?,							NULL,
								?,						?,							?,								NULL,						NULL,
								NULL,					NULL,						NULL,							NULL,						NULL,
								'0',					?,							?,								?,							NULL,
								NULL,					NULL,						NULL,							NULL,						NULL,
								NULL,					NULL,						NULL,							NULL,						NULL,
								NULL,					NULL,						NULL,							NULL,						NULL,
								NULL,					NULL,						?,								GetDate( ),					NULL,
								NULL,					NULL,						NULL,							NULL,						?,
								?,						GetDate())";
											
											
					$params_wko_ls2 = array($site_cd,$Assetno,$stockno,$description,$quantity,$itemcost,$mtr_mst_mtr_no,'1',$issueqty,$issueqty,$uom,$chargecostcenter,$chargeaccount,$stockloc,$LogingID,$wko_RowID,$LogingID,);			
					$stmt = sqlsrv_query( $conn, $sql_insert_wko_ls2,$params_wko_ls2);

					if( !$stmt ) {
						$error_message = "Error insert table (INSERT Table wko_ls2)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
					}	
					sqlsrv_free_stmt( $stmt);
					
					
					
					$ldc_tot_costs = ($quantity * $itemcost);
					
					$data[$y] =  $ldc_tot_costs;
					$Row[$y] =  $ll_RowID;
					
				}else{
					
					$sql = "SELECT 	Row_no = MAX(wko_ls2_mr_lineno) +1  FROM 	wko_ls2 (NOLOCK) WHERE	site_cd = '".$site_cd."' AND wko_ls2_mr_no = '".$mtr_mst_mtr_no."'";
					$stmt = sqlsrv_query( $conn, $sql);				
					if( !$stmt ) {
						 $error_message = "Error select table (dft_mst)";
						 returnError($error_message);
						 die( print_r( sqlsrv_errors(), true));
					}
					do {
						while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
						 
							$wko_ls2_mr_lineno = $row['Row_no'];	
						
						}
					} while ( sqlsrv_next_result($stmt) );
					
					$ll_row_no = $wko_ls2_mr_lineno ;
					
					$ldc_tot_cost = ($quantity * $itemcost);
					
					$sql_insert_mtr_ls1 = "INSERT mtr_ls1 
											(	site_cd ,					mst_RowID ,					mtr_ls1_mtr_lineno ,			mtr_ls1_stockno , 
												mtr_ls1_stk_locn ,			mtr_ls1_mtl_uom ,			mtr_ls1_desc ,					mtr_ls1_status , 
												mtr_ls1_chg_costcenter ,	mtr_ls1_chg_account ,		mtr_ls1_req_qty ,				mtr_ls1_rcv_qty , 
												mtr_ls1_bo_qty ,			mtr_ls1_clear_qty ,			mtr_ls1_item_cost ,				mtr_ls1_po_no , 
												mtr_ls1_po_lineno ,			mtr_ls1_rec_supplier ,		mtr_ls1_supplier_partno ,		audit_user , 
												audit_date,					mbl_audit_user,				mbl_audit_date  )
									VALUES (	? ,							?,							?,								?, 
												? ,							?,							?,								'W' , 
												?,							?,							?,								0, 
												?,							0,							?,								NULL , 
												NULL ,						 NULL ,						NULL ,							?, 
												GetDate( ),					?,							GetDate( ) ) ";
									
									
					//echo $sql_insert_mtr_ls1;
					$params_mtr_ls1 = array($site_cd,$ll_RowID,$ll_row_no,$stockno,$stockloc,$uom,$description,$chargecostcenter,$chargeaccount,$quantity,$quantity,$itemcost,$LogingID,$LogingID);			
					$stmt = sqlsrv_query( $conn, $sql_insert_mtr_ls1,$params_mtr_ls1);

					if( !$stmt ) {
						$error_message = "Error insert table (INSERT Table mtr_ls1)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
					}	
					sqlsrv_free_stmt( $stmt);
					
					$sql_insert_wko_ls2 = "INSERT INTO wko_ls2 
						(	site_cd,				wko_ls2_assetno,			wko_ls2_activity_code,			wko_ls2_stockno,			wko_ls2_desc, 
							wko_ls2_qty_needed,		wko_ls2_item_cost,			wko_ls2_mr_no,					wko_ls2_mr_lineno,			wko_ls2_rec_supplier, 
							wko_ls2_act_qty,		wko_ls2_act_cost,			wko_ls2_mtl_uom,				wko_ls2_pr_no,				wko_ls2_pr_lineno, 
							wko_ls2_po_no,			wko_ls2_po_lineno,			wko_ls2_craft,					wko_ls2_nonrefpono,			wko_ls2_com_code, 
							wko_ls2_taxable,		wko_ls2_chg_costcenter,		wko_ls2_chg_account,			wko_ls2_stk_locn,			wko_ls2_info_src, 
							wko_ls2_inv_no,			wko_ls2_inv_lineno,			wko_ls2_varchar1,				wko_ls2_varchar2,			wko_ls2_varchar3, 
							wko_ls2_varchar4,		wko_ls2_varchar5,			wko_ls2_numeric1,				wko_ls2_numeric2,			wko_ls2_numeric3, 
							wko_ls2_numeric4,		wko_ls2_numeric5,			wko_ls2_datetime1,				wko_ls2_datetime2,			wko_ls2_datetime3, 
							wko_ls2_datetime4,		wko_ls2_datetime5,			audit_user,						audit_date,					column1, 
							column2,				column3,					column4,						column5,					mst_RowID,
							mbl_audit_user,			mbl_audit_date)
					VALUES (	?,						?,							NULL,							?,							?,
								?,						?,							?,								?,							NULL,
								?,						?,							?,								NULL,						NULL,
								NULL,					NULL,						NULL,							NULL,						NULL,
								'0',					?,							?,								?,							NULL,
								NULL,					NULL,						NULL,							NULL,						NULL,
								NULL,					NULL,						NULL,							NULL,						NULL,
								NULL,					NULL,						NULL,							NULL,						NULL,
								NULL,					NULL,						?,								GetDate( ),					NULL,
								NULL,					NULL,						NULL,							NULL,						?,
								?,						GetDate())";
											
											
					$params_wko_ls2 = array($site_cd,$Assetno,$stockno,$description,$quantity,$itemcost,$mtr_mst_mtr_no,$ll_row_no,$issueqty,$issueqty,$uom,$wko_mst_chg_costcenter,$chargeaccount,$stockloc,$LogingID,$wko_RowID,$LogingID,);			
					$stmt = sqlsrv_query( $conn, $sql_insert_wko_ls2,$params_wko_ls2);

					if( !$stmt ) {
						$error_message = "Error insert table (INSERT Table wko_ls2)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
					}	
					sqlsrv_free_stmt( $stmt);
					
					$data[$y] =  $data[$y] + $ldc_tot_cost;
					$Row[$y] =  $ll_RowID;
					
				}
				
				$old_assetno =   $Assetno;
			}
			
			//echo json_encode($data);
			//echo json_encode($Row);
			
			for($i = 0; $i < count($data); $i++) {
				
			  $loop_RowID = $Row[$i];
			  $loop_total_cost = $data[$i];
			  
			  $sql = "SELECt 'count' = COUNT (*) 
					  FROM	 cf_cost_center (NOLOCK),emp_ls3 (NOLOCK)
					  WHERE	 cf_cost_center.site_cd = emp_ls3.site_cd
					  AND	cf_cost_center.costcenter = emp_ls3.emp_ls3_costcenter
					  AND	emp_ls3.emp_ls3_approver_flag = '1'
					  AND	cf_cost_center.site_cd = '".$site_cd."'
					  AND	cf_cost_center.costcenter = '".$wko_mst_chg_costcenter."'";


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

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

				do {
					 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
						 
						$count = $row['count'];	
						
					 }
				} while ( sqlsrv_next_result($stmt) );
				
				if($count >0){
					
					$sql = "SELECt cf_cost_center.costcenter,
									cf_cost_center.descs,
									emp_ls3.emp_ls3_empl_id,   
									emp_ls3.emp_ls3_approval_limit,
									emp_ls3.emp_ls3_approver_flag,   
									emp_ls3.emp_ls3_level,
									emp_ls3.RowID 
					FROM		cf_cost_center (NOLOCK),emp_ls3 (NOLOCK)
					WHERE	cf_cost_center.site_cd = emp_ls3.site_cd
					AND		cf_cost_center.costcenter = emp_ls3.emp_ls3_costcenter
					AND		emp_ls3.emp_ls3_approver_flag = '1'
					AND		cf_cost_center.site_cd = '".$site_cd."'
					AND		cf_cost_center.costcenter = '".$wko_mst_chg_costcenter."'
					ORDER BY emp_ls3.emp_ls3_level "	;


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

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

					$json = array();
					
					
					do {
						 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
							 
							$costcenter = $row['costcenter'];	
							$descs = $row['descs'];	
							$emp_ls3_empl_id = $row['emp_ls3_empl_id'];	
							$emp_ls3_approval_limit = $row['emp_ls3_approval_limit'];	
							$emp_ls3_approver_flag = $row['emp_ls3_approver_flag'];	
							$emp_ls3_level = $row['emp_ls3_level'];	
							$RowID = $row['RowID'];				
							
							
							if ($first_row) {
								//echo $first_row;
								$next_approver = $emp_ls3_empl_id;
								$first_row = false;
							}
							
							//$next_approver = $emp_ls3_empl_id
							
							$sql_insert_mtr_app = "Insert mtr_app 
											(	site_cd ,				mst_RowID ,							mtr_app_level,				mtr_app_cost_center, 
												mtr_app_empl_id,		mtr_app_mr_limit,					mtr_app_date,				mtr_app_status, 
												mtr_app_approval,		audit_user ,						audit_date,					mbl_audit_user,			mbl_audit_date )
								Values 		(	?,						?,									?,							?, 
												?,						? ,									NULL ,						'P', 
												NULL,					?,									GetDate (),					?,						GetDate () ) ";								
													
							$params_mtr_app = array($site_cd,$loop_RowID,$emp_ls3_level,$wko_mst_chg_costcenter,$emp_ls3_empl_id,$emp_ls3_approval_limit,$LogingID,$LogingID);		
							$stmt2 = sqlsrv_query( $conn, $sql_insert_mtr_app,$params_mtr_app);

							if( !$stmt2 ) {
								$error_message = "Error insert table (INSERT Table mtr_app)";
								returnError($error_message);
								die( print_r( sqlsrv_errors(), true));
							}	
							sqlsrv_free_stmt( $stmt2);
							
							//$json[]= $row;	
							
							
						}			 
						 
					} while ( sqlsrv_next_result($stmt) );
					
					/* for ($x = 0; $x <= $count; $x++) {
					
						$sql_insert_wko_ls2 = "Insert mtr_app 
										(	site_cd ,				mst_RowID ,							mtr_app_level,				mtr_app_cost_center, 
											mtr_app_empl_id,		mtr_app_mr_limit,					mtr_app_date,				mtr_app_status, 
											mtr_app_approval,		audit_user ,						audit_date )
							Values 		(	'".$site_cd."',			'".$ll_RowID."',					'".$emp_ls3_level."',		'".$wko_mst_chg_costcenter."' , 
											'".$audit_user."',		'".$emp_ls3_approval_limit."' ,		NULL ,			'P', 
											NULL,					'".$audit_user."' ,					GetDate () ) ";								
												
								
						$stmt = sqlsrv_query( $conn, $sql_insert_wko_ls2);

						if( !$stmt ) {
							$error_message = "Error insert table (INSERT Table mtr_app)";
							returnError($error_message);
							die( print_r( sqlsrv_errors(), true));
						}	
						sqlsrv_free_stmt( $stmt);
					
				  
					}*/
					
					$sql = "SELECt 'Max' =MAX(emp_ls3_level) 
							FROM	cf_cost_center (NOLOCK),emp_ls3 (NOLOCK)
							WHERE	cf_cost_center.site_cd = emp_ls3.site_cd
							AND		cf_cost_center.costcenter = emp_ls3.emp_ls3_costcenter
							AND		emp_ls3.emp_ls3_approver_flag = '1'
							AND		cf_cost_center.site_cd = '".$site_cd."'
							AND		cf_cost_center.costcenter = '".$wko_mst_chg_costcenter."'";


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

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

					do {
						 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
							 
							$Max = $row['Max'];	
							
						 }
					} while ( sqlsrv_next_result($stmt) );
					
					
					$sql = "UPDATE mtr_mst 
								SET mtr_mst_app_level = ?, 
									mtr_mst_cur_app_level = ?, 
									mtr_mst_approver = ?, 
									mtr_mst_tot_cost = ?,
									mbl_audit_user = ?, 
									mbl_audit_date = GetDate () 
							WHERE 	site_cd = ? 
							AND 	RowID = ?";

					$params_mtr_mst = array($Max,0,$next_approver,$loop_total_cost,$LogingID,$site_cd,$loop_RowID);								
					$stmt = sqlsrv_query( $conn, $sql,$params_mtr_mst);				
									
					if( !$stmt ) {
						 $error_message = "Error update table (mtr_mst)";
						 returnError($error_message);
						 die( print_r( sqlsrv_errors(), true));
					}
					sqlsrv_free_stmt( $stmt);
						
				}else{
				
				
					$sql = "UPDATE mtr_mst 
							SET mtr_mst_app_level = ?, 
								mtr_mst_cur_app_level = ?, 
								mtr_mst_approver =Null, 
								mtr_mst_tot_cost = ?,
								mbl_audit_user = ?, 
								mbl_audit_date = GetDate () 
						WHERE 	site_cd = ? 
						AND 	RowID = ?";	

					$params_mtr_mst = array(0,0,$loop_total_cost,$LogingID,$site_cd,$loop_RowID);						
					$stmt = sqlsrv_query( $conn, $sql,$params_mtr_mst);				
									
					if( !$stmt ) {
						 $error_message = "Error update table (mtr_mst)";
						 returnError($error_message);
						 die( print_r( sqlsrv_errors(), true));
					}
					sqlsrv_free_stmt( $stmt);

				}
				
				$sql = "UPDATE wko_det 
						SET wko_det_est_mtl_cost = wko_det_est_mtl_cost + '".$loop_total_cost."', 
						audit_user = '".$LogingID."', 
						audit_date = GetDate (),
						mbl_audit_user = '".$LogingID."', 
						mbl_audit_date = GetDate () 				
						WHERE mst_RowID = '".$wko_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_free_stmt( $stmt);
			}
		}
		//C & P 
		else{
			
			$sql = "Select cnt_mst_prefix + SUBSTRING(CONVERT(VARCHAR(7), cnt_mst_counter + 1000000), 2, 6)  ls_doc_no
			From 	cnt_mst WITH (UPDLOCK)
			Where 	site_cd ='".$site_cd."'
			And 	cnt_mst_module_cd =  'MTR'
			UPDATE 	cnt_mst WITH (UPDLOCK)
			SET 		cnt_mst_counter = cnt_mst_counter + 1
			WHERE 	site_cd ='".$site_cd."' 
			AND 	cnt_mst_module_cd = 'MTR'";			
			
			
			$stmt = sqlsrv_query( $conn, $sql);			
			if( !$stmt ) {
				$error_message = "Error update table (itm_mst)";
				returnError($error_message);
				die( print_r( sqlsrv_errors(), true));
			
			
			}
			
			do {
				while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {	
				
					$mtr_mst_mtr_no = $row['ls_doc_no'];	 	 
				}
			} while ( sqlsrv_next_result($stmt));
			
			$sql = "SELECT 	dft_mst_mtr_sts,dft_mst_mr_release_for_app,dft_mst_mtr_email_requestor,dft_mst_mtr_email
				FROM	dft_mst(NOLOCK)
				WHERE	( dft_mst.site_cd = '".$site_cd."' )";


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

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

			do {
				 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
					$ls_mr_status = $row['dft_mst_mtr_sts'];	
					$dft_mst_mr_release_for_app = $row['dft_mst_mr_release_for_app'];	
					$dft_mst_mtr_email_requestor = $row['dft_mst_mtr_email_requestor'];	
					$dft_mst_mtr_email = $row['dft_mst_mtr_email'];	
				 }
			} while ( sqlsrv_next_result($stmt) );	
			
			if(empty($mtr_sts_status)){
			
				$sql = "SELECT TOP 1 mtr_sts.mtr_sts_status 
						FROM mtr_sts (NOLOCK)
						WHERE mtr_sts.site_cd ='".$site_cd."' 
						AND mtr_sts.mtr_sts_st_cat ='MR' 
						AND mtr_sts.mtr_sts_status_type ='OPEN' 
						AND mtr_sts.mtr_sts_disable_flag ='0'";


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

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

				do {
					 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
						$ls_mr_status = $row['mtr_sts_status'];					
					 }
				} while ( sqlsrv_next_result($stmt) );
			}
			
			$sql_insert_mtr_mst = "INSERT mtr_mst 
					(	site_cd ,					mtr_mst_mtr_no ,			mtr_mst_assetno ,				mtr_mst_costcenter ,				
						mtr_mst_account ,			mtr_mst_org_date ,			mtr_mst_req_date ,				mtr_mst_cmpl_date ,
						mtr_mst_wo_no ,				mtr_mst_requester ,			mtr_mst_entered_by ,			mtr_mst_status ,
						mtr_mst_mr_status ,			mtr_mst_email_notification ,mtr_mst_note ,					mtr_mst_tot_cost ,
						mtr_mst_release_for_app ,	mtr_mst_email_requestor ,	mtr_mst_create_by ,				mtr_mst_create_date ,			
						audit_user ,				audit_date,					mbl_audit_user,					mbl_audit_date ) 
			VALUES 	(	?,							?,							?,								?,		
						?,							getDate(),					getDate(),						Null,							
						?,							?,							?,								'W',						
						'MTR',						?,							Null,							'0',
						?,							?,							?,								getDate(),
						?,							getDate(),					?,							getDate())";
										
										
			$params_mtr_mst = array($site_cd,$mtr_mst_mtr_no,$wko_mst_assetno,$wko_mst_chg_costcenter,$wko_det_maccount,$wko_mst_wo_no,$audit_user,$audit_user,$dft_mst_mtr_email,$dft_mst_mr_release_for_app,$dft_mst_mtr_email_requestor,$LogingID,$LogingID,$LogingID);				
			$stmt = sqlsrv_query( $conn, $sql_insert_mtr_mst,$params_mtr_mst);

			if( !$stmt ) {
				$error_message = "Error insert table (INSERT Table mtr_mst)";
				returnError($error_message);
				die( print_r( sqlsrv_errors(), true));
			}	
			sqlsrv_free_stmt( $stmt);	
			
			$sql = "SELECT 	RowID FROM 	mtr_mst (NOLOCK)
					WHERE	site_cd = '".$site_cd."'
					AND		mtr_mst_mtr_no = '".$mtr_mst_mtr_no."'";


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

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

			do {
				 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
					 
					$ll_RowID = $row['RowID'];	
					
				 }
			} while ( sqlsrv_next_result($stmt) );	
			
			
			$sql_insert_mtr_det = "INSERT mtr_det 
												(	 site_cd,		mst_RowID, 		audit_user, 		audit_date,					mbl_audit_user,					mbl_audit_date )
										VALUES	(	 ?,				?,				?,					GETDATE(),					?,								GETDATE());";
									
									
			$params_mtr_det = array($site_cd,$ll_RowID,$LogingID,$LogingID);				
			$stmt = sqlsrv_query( $conn, $sql_insert_mtr_det,$params_mtr_det);

			if( !$stmt ) {
				$error_message = "Error insert table (INSERT Table mtr_det)";
				returnError($error_message);
				die( print_r( sqlsrv_errors(), true));
			}	
			sqlsrv_free_stmt( $stmt);
			
			
			$sql_insert_mtr_ls2 = "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,				mbl_audit_user,			mbl_audit_date ) 
				VALUES  (		?,						?,						?,						'MTR',					
								?,						GETDATE ( ), 			 NULL,					 NULL,					
								?,						GETDATE ( ),			?,						GETDATE ( ))";
									
									
			$params_mtr_ls2 = array($site_cd,$ll_RowID,$mtr_mst_mtr_no,$audit_user,$LogingID,$LogingID);							
			$stmt = sqlsrv_query( $conn, $sql_insert_mtr_ls2,$params_mtr_ls2);

			if( !$stmt ) {
				$error_message = "Error insert table (INSERT Table mtr_ls2)";
				returnError($error_message);
				die( print_r( sqlsrv_errors(), true));
			}	
			sqlsrv_free_stmt( $stmt);
			
			foreach($result->Details as $Detail){
				
				$stockno = $Detail->stock_no;
				$stockloc = $Detail->stock_location;
				$description = $Detail->itm_mst_desc;
				$uom = $Detail->rcv_uom;
				$issueqty = '0.00';
				$quantity = $Detail->rcv_qty;
				$chargecostcenter = $Detail->itm_mst_costcenter;
				$chargeaccount = $Detail->itm_mst_account;
				$itemcost = $Detail->itm_mst_issue_price;
				
				$ll_row++;
				$ldc_tot_cost = $ldc_tot_cost + ($quantity * $itemcost);
				
				
				$sql_insert_mtr_ls1 = "INSERT mtr_ls1 
											(	site_cd ,					mst_RowID ,					mtr_ls1_mtr_lineno ,			mtr_ls1_stockno , 
												mtr_ls1_stk_locn ,			mtr_ls1_mtl_uom ,			mtr_ls1_desc ,					mtr_ls1_status , 
												mtr_ls1_chg_costcenter ,	mtr_ls1_chg_account ,		mtr_ls1_req_qty ,				mtr_ls1_rcv_qty , 
												mtr_ls1_bo_qty ,			mtr_ls1_clear_qty ,			mtr_ls1_item_cost ,				mtr_ls1_po_no , 
												mtr_ls1_po_lineno ,			mtr_ls1_rec_supplier ,		mtr_ls1_supplier_partno ,		audit_user , 
												audit_date,					mbl_audit_user,				mbl_audit_date  )
									VALUES  (	? ,							?,							?,								?, 
												? ,							?,							?,								'W' , 
												?,							?,							?,								0, 
												?,							0,							?,								NULL , 
												NULL ,						 NULL ,						NULL ,							?, 
												GetDate( ),					?,							GetDate( ) 
											) ";
									
									
				//echo $sql_insert_mtr_ls1;
				$params_mtr_ls1 = array($site_cd,$ll_RowID,$ll_row,$stockno,$stockloc,$uom,$description,$chargecostcenter,$chargeaccount,$quantity,$quantity,$itemcost,$LogingID,$LogingID);			
				$stmt = sqlsrv_query( $conn, $sql_insert_mtr_ls1,$params_mtr_ls1);

				if( !$stmt ) {
					$error_message = "Error insert table (INSERT Table mtr_ls1)";
					returnError($error_message);
					die( print_r( sqlsrv_errors(), true));
				}	
				sqlsrv_free_stmt( $stmt);
				
				
				$sql_insert_wko_ls2 = "INSERT INTO wko_ls2 
												(	site_cd,				wko_ls2_assetno,			wko_ls2_activity_code,			wko_ls2_stockno,			wko_ls2_desc, 
													wko_ls2_qty_needed,		wko_ls2_item_cost,			wko_ls2_mr_no,					wko_ls2_mr_lineno,			wko_ls2_rec_supplier, 
													wko_ls2_act_qty,		wko_ls2_act_cost,			wko_ls2_mtl_uom,				wko_ls2_pr_no,				wko_ls2_pr_lineno, 
													wko_ls2_po_no,			wko_ls2_po_lineno,			wko_ls2_craft,					wko_ls2_nonrefpono,			wko_ls2_com_code, 
													wko_ls2_taxable,		wko_ls2_chg_costcenter,		wko_ls2_chg_account,			wko_ls2_stk_locn,			wko_ls2_info_src, 
													wko_ls2_inv_no,			wko_ls2_inv_lineno,			wko_ls2_varchar1,				wko_ls2_varchar2,			wko_ls2_varchar3, 
													wko_ls2_varchar4,		wko_ls2_varchar5,			wko_ls2_numeric1,				wko_ls2_numeric2,			wko_ls2_numeric3, 
													wko_ls2_numeric4,		wko_ls2_numeric5,			wko_ls2_datetime1,				wko_ls2_datetime2,			wko_ls2_datetime3, 
													wko_ls2_datetime4,		wko_ls2_datetime5,			audit_user,						audit_date,					column1, 
													column2,				column3,					column4,						column5,					mst_RowID,
													mbl_audit_user,			mbl_audit_date)
										VALUES 	(	?,						?,							NULL,							?,							?,
													?,						?,							?,								?,							NULL,
													?,						?,							?,								NULL,						NULL,
													NULL,					NULL,						NULL,							NULL,						NULL,
													'0',					?,							?,								?,							NULL,
													NULL,					NULL,						NULL,							NULL,						NULL,
													NULL,					NULL,						NULL,							NULL,						NULL,
													NULL,					NULL,						NULL,							NULL,						NULL,
													NULL,					NULL,						?,								GetDate( ),					NULL,
													NULL,					NULL,						NULL,							NULL,						?,
													?,						GetDate()
													
												)";
										
										
				$params_wko_ls2 = array($site_cd,$wko_mst_assetno,$stockno,$description,$quantity,$itemcost,$mtr_mst_mtr_no,$ll_row,$issueqty,$issueqty,$uom,$wko_mst_chg_costcenter,$chargeaccount,$stockloc,$LogingID,$wko_RowID,$LogingID,);			
				$stmt = sqlsrv_query( $conn, $sql_insert_wko_ls2,$params_wko_ls2);

				if( !$stmt ) {
					$error_message = "Error insert table (INSERT Table wko_ls2)";
					returnError($error_message);
					die( print_r( sqlsrv_errors(), true));
				}	
				sqlsrv_free_stmt( $stmt);
				
			}
			
			
			$sql = "SELECt 'count' = COUNT (*) 
			FROM	cf_cost_center (NOLOCK),emp_ls3 (NOLOCK)
			WHERE	cf_cost_center.site_cd = emp_ls3.site_cd
			AND		cf_cost_center.costcenter = emp_ls3.emp_ls3_costcenter
			AND		emp_ls3.emp_ls3_approver_flag = '1'
			AND		cf_cost_center.site_cd = '".$site_cd."'
			AND		cf_cost_center.costcenter = '".$wko_mst_chg_costcenter."'";


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

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

			do {
				 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
					 
					$count = $row['count'];	
					
				 }
			} while ( sqlsrv_next_result($stmt) );
			
			if($count >0){
				
				
				$sql = "SELECt cf_cost_center.costcenter,
								cf_cost_center.descs,
								emp_ls3.emp_ls3_empl_id,   
								emp_ls3.emp_ls3_approval_limit,
								emp_ls3.emp_ls3_approver_flag,   
								emp_ls3.emp_ls3_level,
								emp_ls3.RowID 
				FROM		cf_cost_center (NOLOCK),emp_ls3 (NOLOCK)
				WHERE	cf_cost_center.site_cd = emp_ls3.site_cd
				AND		cf_cost_center.costcenter = emp_ls3.emp_ls3_costcenter
				AND		emp_ls3.emp_ls3_approver_flag = '1'
				AND		cf_cost_center.site_cd = '".$site_cd."'
				AND		cf_cost_center.costcenter = '".$wko_mst_chg_costcenter."'
				ORDER BY emp_ls3.emp_ls3_level "	;


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

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

				$json = array();
				
				
				do {
					while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
						 
						$costcenter = $row['costcenter'];	
						$descs = $row['descs'];	
						$emp_ls3_empl_id = $row['emp_ls3_empl_id'];	
						$emp_ls3_approval_limit = $row['emp_ls3_approval_limit'];	
						$emp_ls3_approver_flag = $row['emp_ls3_approver_flag'];	
						$emp_ls3_level = $row['emp_ls3_level'];	
						$RowID = $row['RowID'];				
						
						
						if ($first_row) {
							//echo $first_row;
						 $next_approver = $emp_ls3_empl_id;
						 $first_row = false;
						}
						
						//$next_approver = $emp_ls3_empl_id
						
						$sql_insert_mtr_app = "Insert mtr_app 
										(	site_cd ,				mst_RowID ,							mtr_app_level,				mtr_app_cost_center, 
											mtr_app_empl_id,		mtr_app_mr_limit,					mtr_app_date,				mtr_app_status, 
											mtr_app_approval,		audit_user ,						audit_date,					mbl_audit_user,			mbl_audit_date )
							Values 		(	?,						?,									?,							?, 
											?,						? ,									NULL ,						'P', 
											NULL,					?,									GetDate (),					?,						GetDate () ) ";								
												
						$params_mtr_app = array($site_cd,$ll_RowID,$emp_ls3_level,$wko_mst_chg_costcenter,$emp_ls3_empl_id,$emp_ls3_approval_limit,$LogingID,$LogingID);		
						$stmt2 = sqlsrv_query( $conn, $sql_insert_mtr_app,$params_mtr_app);

						if( !$stmt2 ) {
							$error_message = "Error insert table (INSERT Table mtr_app)";
							returnError($error_message);
							die( print_r( sqlsrv_errors(), true));
						}	
						sqlsrv_free_stmt( $stmt2);
						
						//$json[]= $row;	
						
						
					}			 
					 
				} while ( sqlsrv_next_result($stmt) );
				
				/* for ($x = 0; $x <= $count; $x++) {
				
					$sql_insert_wko_ls2 = "Insert mtr_app 
									(	site_cd ,				mst_RowID ,							mtr_app_level,				mtr_app_cost_center, 
										mtr_app_empl_id,		mtr_app_mr_limit,					mtr_app_date,				mtr_app_status, 
										mtr_app_approval,		audit_user ,						audit_date )
						Values 		(	'".$site_cd."',			'".$ll_RowID."',					'".$emp_ls3_level."',		'".$wko_mst_chg_costcenter."' , 
										'".$audit_user."',		'".$emp_ls3_approval_limit."' ,		NULL ,			'P', 
										NULL,					'".$audit_user."' ,					GetDate () ) ";								
											
							
					$stmt = sqlsrv_query( $conn, $sql_insert_wko_ls2);

					if( !$stmt ) {
						$error_message = "Error insert table (INSERT Table mtr_app)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
					}	
					sqlsrv_free_stmt( $stmt);
				} */
				
				$sql = "SELECt 'Max' =MAX(emp_ls3_level) 
						FROM		cf_cost_center (NOLOCK),emp_ls3 (NOLOCK)
						WHERE	cf_cost_center.site_cd = emp_ls3.site_cd
						AND		cf_cost_center.costcenter = emp_ls3.emp_ls3_costcenter
						AND		emp_ls3.emp_ls3_approver_flag = '1'
						AND		cf_cost_center.site_cd = '".$site_cd."'
						AND		cf_cost_center.costcenter = '".$wko_mst_chg_costcenter."'";


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

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

				do {
					 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
						 
						$Max = $row['Max'];	
						
					 }
				} while ( sqlsrv_next_result($stmt) );
				
				
				$sql = "UPDATE mtr_mst 
							SET mtr_mst_app_level = ?, 
								mtr_mst_cur_app_level = ?, 
								mtr_mst_approver = ?, 
								mtr_mst_tot_cost = ?,
								mbl_audit_user = ?, 
								mbl_audit_date = GetDate () 
						WHERE 	site_cd = ? 
						AND 	RowID = ?";	

				$params_mtr_mst = array($Max,0,$next_approver,$ldc_tot_cost,$LogingID,$site_cd,$ll_RowID);
				$stmt = sqlsrv_query( $conn, $sql,$params_mtr_mst);				
								
				if( !$stmt ) {
					 $error_message = "Error update table (mtr_mst)";
					 returnError($error_message);
					 die( print_r( sqlsrv_errors(), true));
				}
				sqlsrv_next_result($stmt);
				
			}else{
				
				
				$sql = "UPDATE mtr_mst 
					SET mtr_mst_app_level =0, 
						mtr_mst_cur_app_level =0, 
						mtr_mst_approver =Null, 
						mtr_mst_tot_cost = ?,
						mbl_audit_user = ?, 
						mbl_audit_date = GetDate () 
				WHERE 	site_cd = ? 
				AND 	RowID = ?";
				
				$params_mtr_mst = array($ldc_tot_cost,$LogingID,$site_cd,$ll_RowID);				
				$stmt = sqlsrv_query( $conn, $sql,$params_mtr_mst);				
								
				if( !$stmt ) {
					
					$error_message = "Error update table (mtr_mst)";
					returnError($error_message);
					die( print_r( sqlsrv_errors(), true));
				}
				sqlsrv_next_result($stmt);
				
			}
			
			
			$sql = "UPDATE wko_det 
					SET wko_det_est_mtl_cost = wko_det_est_mtl_cost + '".$ldc_tot_cost."', 
					audit_user = '".$LogingID."', 
					audit_date = GetDate (),
					mbl_audit_user = '".$LogingID."', 
					mbl_audit_date = GetDate () 				
					WHERE mst_RowID = '".$wko_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($mtr_mst_mtr_no){
		
		//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  			= $mtr_mst_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				= Null;
				$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,
						lslRow_ID = mtr_ls1.RowID
			
				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'];
						$lslRow_ID = $row['lslRow_ID'];
						$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,
										itm_mtu_po_costcenter,		itm_mtu_po_account										)
								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,$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,								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,					itm_mtu_po_costcenter,		
											itm_mtu_po_account )
									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,$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,								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));
					}
					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);
						}
					}
				}

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

				//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));
				}
				sqlsrv_next_result($stmt_update_mtr_mst);
			
				//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));
				}
				sqlsrv_next_result($stmt_update_mtr_ls1);				

				//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));
				}
				sqlsrv_next_result($stmt_update_mtr_app);

				//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));
				}
				sqlsrv_next_result($stmt_update_mtr_det);
			}
			
			$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' => "Transaction 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();
}
 
?>