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

function generate_po($al_Rowid, $gs_site, $audit_user){
	global $syn_conn;
	
	$now = date("Ymdhisa");
	$ld_date = date("Ymd");
	
	$module = "Purchase Request"; 
	$action = "Generate PO";

	/* Begin the transaction. */
	if (sqlsrv_begin_transaction($syn_conn) === false)
	{
		
		die(print_r(sqlsrv_errors() , true));
	}
	
	//Get PR Information
	$sql_get_pr_info = "Select pur_mst_porqnnum,
								pur_mst_rqn_date,	
								pur_mst_chg_costcenter,
								pur_mst_chg_account,
								pur_mst_crd_costcenter,
								pur_mst_crd_account,
								pur_mst_projectid,
								pur_mst_sub_tot_cost
			From 	pur_mst (NOLOCK)
			Where 	site_cd ='" . $gs_site . "'
			AND		pur_mst.rowid = ".$al_Rowid;
			
	$stmt_get_pr_info = sqlsrv_query($syn_conn, $sql_get_pr_info);

	if ($stmt_get_pr_info === false)
	{
		if (($errors = sqlsrv_errors()) != null)
		{
			foreach ($errors as $error)
			{
				//file_put_contents($file_name, $now . "\r\n" . $sql . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
				insert_error_log($gs_site, 'Line 43 '.$error['message'], $audit_user, $module, $action);
			}
			sqlsrv_rollback($syn_conn);
		}
	}

	do
		{
			while ($row = sqlsrv_fetch_array($stmt_get_pr_info, SQLSRV_FETCH_ASSOC))
			{

				$ls_pr_no = $row['pur_mst_porqnnum'];
				$ldt_pr_date = $row['pur_mst_rqn_date'];
				$ls_chg_costcenter = $row['pur_mst_chg_costcenter'];
				$ls_chg_account = $row['pur_mst_chg_account'];
				$ls_crd_costcenter = $row['pur_mst_crd_costcenter'];
				$ls_crd_account = $row['pur_mst_crd_account'];
				$ls_project = $row['pur_mst_projectid'];
				$ldc_pr_cost = $row['pur_mst_sub_tot_cost'];

			}
		}
		while (sqlsrv_next_result($stmt_get_pr_info));
		sqlsrv_free_stmt($stmt_get_pr_info);
	
	//Count Supplier
	$sql_count_sup = "SELECT COUNT(DISTINCT pur_ls1_supplier) as ll_supplier_cnt, 
							MAX(pur_ls1_supplier) as ls_pr_supplier
						FROM	pur_ls1 (NOLOCK) 
						WHERE mst_rowid = ".$al_Rowid;

	$stmt_count_sup = sqlsrv_query($syn_conn, $sql_count_sup);

	if ($stmt_count_sup === false){
		if (($errors = sqlsrv_errors()) != null){
			foreach ($errors as $error)
			{
				insert_error_log($gs_site, 'Line 80 '.$error['message'], $audit_user, $module, $action);
			}
			sqlsrv_rollback($syn_conn);
		}

		$error_message = "Error selecting table (pur_ls1) - ".$now;
		return $error_message;
	}

	do
	{
		while ($row = sqlsrv_fetch_array($stmt_count_sup, SQLSRV_FETCH_ASSOC))
		{

			$ll_supplier_cnt = $row['ll_supplier_cnt'];
			$ls_pr_supplier = $row['ls_pr_supplier'];

		}
	}
	while (sqlsrv_next_result($stmt_count_sup));
	
	If ($ll_supplier_cnt <> 1) {
		//wf_budget_update("APP_PR")	
		//f_update_purchase_budget($gs_site, $ldt_pr_date, $ls_chg_costcenter, $ls_chg_account, "APP_PR", $ldc_pr_cost, $syn_conn, $audit_user);
		f_update_purchase_budget($gs_site, $ldt_pr_date, $ls_chg_costcenter, $ls_chg_account, "MINUS_AWA_PR", $ldc_pr_cost, $syn_conn, $audit_user);
		f_update_purchase_budget($gs_site, $ldt_pr_date, $ls_chg_costcenter, $ls_chg_account, "ADD_PR", $ldc_pr_cost, $syn_conn, $audit_user);
		$error_message = "Purchase Order is not generated.~r~n~r~nBecause there is no supplier assigned in the PR or more~r~nthan one supplier had assigned in the Purchase Request. - ".$now;
		sqlsrv_rollback($syn_conn);
		return $error_message;
	}
	
	sqlsrv_free_stmt($stmt_count_sup);
	////
	
	//Count Currency
	$sql_count_cur = "SELECT 'll_supplier_cur_cnt' = COUNT(DISTINCT pur_ls1_cur_code) , 
							'ls_pr_cur' = MAX(pur_ls1_cur_code)
					FROM		pur_ls1
					WHERE	mst_rowid = ".$al_Rowid;

	$stmt_count_cur = sqlsrv_query($syn_conn, $sql_count_cur);

	if ($stmt_count_cur === false)
	{
		if (($errors = sqlsrv_errors()) != null)
		{
			foreach ($errors as $error)
			{
				insert_error_log($gs_site, 'Line 126 '.$error['message'], $audit_user, $module, $action);
			}
			sqlsrv_rollback($syn_conn);
		}
		$error_message = "Error selecting table (pur_ls1) - ".$now;
		return $error_message;
	}

	do
	{
		while ($row = sqlsrv_fetch_array($stmt_count_cur, SQLSRV_FETCH_ASSOC))
		{

			$ll_supplier_cur_cnt = $row['ll_supplier_cur_cnt'];
			$ls_pr_cur = $row['ls_pr_cur'];

		}
	}
	while (sqlsrv_next_result($stmt_count_cur));
	
	If ($ll_supplier_cur_cnt <> 1) {
		//wf_budget_update("APP_PR")	
		//f_update_purchase_budget($gs_site, $ldt_pr_date, $ls_chg_costcenter, $ls_chg_account, "APP_PR", $ldc_pr_cost, $syn_conn, $audit_user);
		f_update_purchase_budget($gs_site, $ldt_pr_date, $ls_chg_costcenter, $ls_chg_account, "MINUS_AWA_PR", $ldc_pr_cost, $syn_conn, $audit_user);
		f_update_purchase_budget($gs_site, $ldt_pr_date, $ls_chg_costcenter, $ls_chg_account, "ADD_PR", $ldc_pr_cost, $syn_conn, $audit_user);
		$error_message = "Purchase Order is not generated.~r~n~r~nBecause there are more than one~r~ncurrency code exist in the Purchase Request - ".$now;
		sqlsrv_rollback($syn_conn);
		return $error_message;
	}
	sqlsrv_free_stmt($stmt_count_cur);
	///////
	
	//Count Currency Supplier
	$sql_count_cur = "SELECT 'll_supplier_cnt' = COUNT(sup_mst_supplier_cd) 
					FROM 	sup_mst
					WHERE 	sup_mst.site_cd = '".$gs_site."'
					AND		sup_mst.sup_mst_supplier_cd = '".$ls_pr_supplier."' 
					AND		sup_mst_curr_code = '".$ls_pr_cur."'";

	$stmt_count_cur_sup = sqlsrv_query($syn_conn, $sql_count_cur);

	if ($stmt_count_cur_sup === false)
	{
		if (($errors = sqlsrv_errors()) != null)
		{
			foreach ($errors as $error)
			{
				insert_error_log($gs_site, 'Line 171 '.$error['message'], $audit_user, $module, $action);
			}
			sqlsrv_rollback($syn_conn);
		}
		$error_message = "Error selecting table (pur_ls1) - ".$now;
		return $error_message;
	}

	do
	{
		while ($row = sqlsrv_fetch_array($stmt_count_cur_sup, SQLSRV_FETCH_ASSOC))
		{

			$ll_supplier_cnt = $row['ll_supplier_cnt'];

		}
	}
	while (sqlsrv_next_result($stmt_count_cur_sup));
	
	If ($ll_supplier_cnt <> 1) {
		//wf_budget_update("APP_PR")	
		//f_update_purchase_budget($gs_site, $ldt_pr_date, $ls_chg_costcenter, $ls_chg_account, "APP_PR", $ldc_pr_cost, $syn_conn, $audit_user);
		f_update_purchase_budget($gs_site, $ldt_pr_date, $ls_chg_costcenter, $ls_chg_account, "MINUS_AWA_PR", $ldc_pr_cost, $syn_conn, $audit_user);
		f_update_purchase_budget($gs_site, $ldt_pr_date, $ls_chg_costcenter, $ls_chg_account, "ADD_PR", $ldc_pr_cost, $syn_conn, $audit_user);
		$error_message = "Purchase Order is not generated.~r~n~r~nBecause the PR currency code is not~r~nsame with the supplier currency code. - ".$now;
		return $error_message;
	}
	sqlsrv_free_stmt($stmt_count_cur_sup);
	//////



	//Get Running Number
	$sql_get_pono = "Select cnt_mst_prefix + SUBSTRING(CONVERT(VARCHAR(7), cnt_mst_counter + 1000000), 2, 6)  ls_doc_no
			From 	cnt_mst WITH (NOLOCK) 
			Where 	site_cd ='" . $gs_site . "'
			And 	cnt_mst_module_cd =  'PO'";

	$stmt_get_pono = sqlsrv_query($syn_conn, $sql_get_pono);

	if ($stmt_get_pono === false)
	{
		if (($errors = sqlsrv_errors()) != null)
		{
			foreach ($errors as $error)
			{
				//file_put_contents($file_name, $now . "\r\n" . $sql . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
				insert_error_log($gs_site, 'Line 216 '.$error['message'], $audit_user, $module, $action);
			}
			sqlsrv_rollback($syn_conn);
		}
	}

	do
	{
		while ($row = sqlsrv_fetch_array($stmt_get_pono, SQLSRV_FETCH_ASSOC))
		{

			$ls_doc = $row['ls_doc_no'];

		}
	}
	while (sqlsrv_next_result($stmt_get_pono));
	sqlsrv_free_stmt($stmt_get_pono);
	
	if (empty($ls_doc) || $ls_doc == ""){
		$error_message = "Purchase Order is not generated.~r~n~r~nBecause the PR currency code is not~r~nsame with the supplier currency code. - ".$now;
		return $error_message;
		
	}else{
		
		//Get Default PO Status
		$sql_get_po_dft_status = "Select dft_mst_puo_sts
				From 	dft_mst (NOLOCK)
				Where 	site_cd ='" . $gs_site . "'";

		$stmt_get_po_dft_status = sqlsrv_query($syn_conn, $sql_get_po_dft_status);

		if ($stmt_get_po_dft_status === false)
		{
			if (($errors = sqlsrv_errors()) != null)
			{
				foreach ($errors as $error)
				{
					//file_put_contents($file_name, $now . "\r\n" . $sql . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
					insert_error_log($gs_site, 'Line 254 '.$error['message'], $audit_user, $module, $action);
				}
				sqlsrv_rollback($syn_conn);
			}
		}

		do
		{
			while ($row = sqlsrv_fetch_array($stmt_get_po_dft_status, SQLSRV_FETCH_ASSOC))
			{

				$ls_status = $row['dft_mst_puo_sts'];

			}
		}
		while (sqlsrv_next_result($stmt_get_po_dft_status));
		sqlsrv_free_stmt($stmt_get_po_dft_status);
		
		//If Default Status is not null
		if (empty($ls_status) || $ls_status == "") {
			//Get TOP 1 1st puo_sts_status
			$sql_get_po_1st_status = "Select TOP 1 puo_sts_status as 'ls_status'
					From 	puo_sts (NOLOCK)
					Where 	site_cd ='" . $gs_site . "'
					AND		puo_sts_st_cat_cd = 'PO'
					AND		puo_sts_status_type = 'FIRM-ORDER'";

			$stmt_get_po_1st_status = sqlsrv_query($syn_conn, $sql_get_po_1st_status);

			if ($stmt_get_po_1st_status === false)
			{
				if (($errors = sqlsrv_errors()) != null)
				{
					foreach ($errors as $error)
					{
						//file_put_contents($file_name, $now . "\r\n" . $sql . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
						insert_error_log($gs_site, 'Line 290 '.$error['message'], $audit_user, $module, $action);
					}
					sqlsrv_rollback($syn_conn);
				}
			}

			do
			{
				while ($row = sqlsrv_fetch_array($stmt_get_po_1st_status, SQLSRV_FETCH_ASSOC))
				{

					$ls_status = $row['ls_status'];

				}
			}
			while (sqlsrv_next_result($stmt_get_po_1st_status));
			sqlsrv_free_stmt($stmt_get_po_1st_status);
			
			if ($ls_status == "" || empty($ls_status)) {
				//Get TOP 1 2nd puo_sts_status
				$sql_get_po_2nd_status = "Select TOP 1 puo_sts_status as 'ls_status'
						From 	puo_sts (NOLOCK)
						Where 	site_cd ='" . $gs_site . "'
						AND		puo_sts_st_cat_cd = 'PO'
						AND		puo_sts_status_type = 'PO'";
						
				$stmt_get_po_2nd_status = sqlsrv_query($syn_conn, $sql_get_po_2nd_status);

				if ($stmt_get_po_2nd_status === false)
				{
					if (($errors = sqlsrv_errors()) != null)
					{
						foreach ($errors as $error)
						{
							//file_put_contents($file_name, $now . "\r\n" . $sql . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
							insert_error_log($gs_site, 'Line 325 '.$error['message'], $audit_user, $module, $action);
						}
						sqlsrv_rollback($syn_conn);
					}
				}

				do
				{
					while ($row = sqlsrv_fetch_array($stmt_get_po_2nd_status, SQLSRV_FETCH_ASSOC))
					{

						$ls_status = $row['ls_status'];

					}
				}
				while (sqlsrv_next_result($stmt_get_po_2nd_status));
				sqlsrv_free_stmt($stmt_get_po_2nd_status);
			}			
		}
		
		
		//Get PR Information
		$sql_get_pr_info = "Select pur_mst_porqnnum,
									pur_mst_rqn_date,
									pur_mst_chg_costcenter,
									pur_mst_chg_account,
									pur_mst_crd_costcenter,
									pur_mst_crd_account,
									pur_mst_projectid,
									pur_mst_sub_tot_cost
				From 	pur_mst (NOLOCK)
				Where 	site_cd ='" . $gs_site . "'
				AND		pur_mst.rowid = ".$al_Rowid;
				
		$stmt_get_pr_info = sqlsrv_query($syn_conn, $sql_get_pr_info);

		if ($stmt_get_pr_info === false)
		{
			if (($errors = sqlsrv_errors()) != null)
			{
				foreach ($errors as $error)
				{
					//file_put_contents($file_name, $now . "\r\n" . $sql . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
					insert_error_log($gs_site, 'Line 368 '.$error['message'], $audit_user, $module, $action);
				}
				sqlsrv_rollback($syn_conn);
			}
		}

		do
		{
			while ($row = sqlsrv_fetch_array($stmt_get_pr_info, SQLSRV_FETCH_ASSOC))
			{

				$ls_pr_no = $row['pur_mst_porqnnum'];
				$ldt_pr_date = $row['pur_mst_rqn_date'];
				$ls_chg_costcenter = $row['pur_mst_chg_costcenter'];
				$ls_chg_account = $row['pur_mst_chg_account'];
				$ls_crd_costcenter = $row['pur_mst_crd_costcenter'];
				$ls_crd_account = $row['pur_mst_crd_account'];
				$ls_project = $row['pur_mst_projectid'];
				$ldc_pr_cost = $row['pur_mst_sub_tot_cost'];

			}
		}
		while (sqlsrv_next_result($stmt_get_pr_info));
		sqlsrv_free_stmt($stmt_get_pr_info);

		//Get PR Line Info
		$sql_get_pr_line_info = "SELECT 	'ls_supplier' = Max(pur_ls1_supplier) ,
									'ld_sub_tot_cost' = Sum(pur_ls1_ord_qty * pur_ls1_item_cost),
									'ld_tot_retail_cost' = Sum(pur_ls1_ord_qty * pur_ls1_retail_price),
									'ls_stockno' = Max(pur_ls1_stockno)
						FROM 	pur_ls1 (NOLOCK)
				Where 	site_cd ='" . $gs_site . "'
				AND		pur_ls1.mst_rowid = ".$al_Rowid;
				
		$stmt_get_pr_line_info = sqlsrv_query($syn_conn, $sql_get_pr_line_info);

		if ($stmt_get_pr_line_info === false)
		{
			if (($errors = sqlsrv_errors()) != null)
			{
				foreach ($errors as $error)
				{
					//file_put_contents($file_name, $now . "\r\n" . $sql . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
					insert_error_log($gs_site, 'Line 411 '.$error['message'], $audit_user, $module, $action);
				}
				sqlsrv_rollback($syn_conn);
			}
		}

		do
		{
			while ($row = sqlsrv_fetch_array($stmt_get_pr_line_info, SQLSRV_FETCH_ASSOC))
			{

				$ls_supplier = $row['ls_supplier'];
				$ld_sub_tot_cost = $row['ld_sub_tot_cost'];
				$ld_tot_retail_cost = $row['ld_tot_retail_cost'];
				$ls_stockno = $row['ls_stockno'];

			}
		}
		while (sqlsrv_next_result($stmt_get_pr_line_info));
		sqlsrv_free_stmt($stmt_get_pr_line_info);
		
		// SELECT	itm_mst_type
		// INTO		:ls_type
		// FROM		itm_mst
		// WHERE	itm_mst.site_cd = :gs_site
		// AND		itm_mst.itm_mst_stockno = :ls_stockno ;
		
		//If ls_type = "C" Then ls_group = "CON"
		//If ls_type = "S" Then ls_group = "REPAIR"

		$ls_group = "PO";
		
		//Select Supplier Detail
		$sql_get_sup_info = "SELECT 	sup_det.sup_det_contact1,
											sup_mst_buyer,
											sup_mst_curr_code,
											sup_mst_tax_id,
											sup_mst_terms,
											sup_mst_shipvia,
											sup_mst_fob,					
											sup_det_bil_billto,
											sup_det_bil_address1,
											sup_det_bil_address2,
											sup_det_bil_city,
											sup_det_bil_state,
											sup_det_bil_postal_code,
											sup_det_bil_country,
											sup_det_bil_phone,
											sup_det_bil_contact,
											sup_det_bil_province,				
											sup_det_bil_note,				
											sup_det_shi_shipto,
											sup_det_shi_address1,
											sup_det_shi_address2,
											sup_det_shi_city,
											sup_det_shi_state,
											sup_det_shi_postal_code,
											sup_det_shi_country,
											sup_det_shi_phone,
											sup_det_shi_contact,
											sup_det_shi_province,				
											sup_det_shi_note			
						FROM 	sup_mst (NOLOCK), sup_det (NOLOCK)
				Where 	sup_mst.site_cd = sup_det.site_cd
				AND 	sup_mst.RowID = sup_det.mst_RowID 
				AND 	sup_mst.site_cd ='" . $gs_site . "'
				AND		sup_mst.sup_mst_supplier_cd = '".$ls_supplier."'";
				
		$stmt_get_sup_info = sqlsrv_query($syn_conn, $sql_get_sup_info);

		if ($stmt_get_sup_info === false)
		{
			if (($errors = sqlsrv_errors()) != null)
			{
				foreach ($errors as $error)
				{
					//file_put_contents($file_name, $now . "\r\n" . $sql . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
					insert_error_log($gs_site, 'Line 488 '.$error['message'], $audit_user, $module, $action);
				}
				sqlsrv_rollback($syn_conn);
			}
		}

		do
		{
			while ($row = sqlsrv_fetch_array($stmt_get_sup_info, SQLSRV_FETCH_ASSOC))
			{

				$ls_contact             = $row['sup_det_contact1'];
				$ls_buyer               = $row['sup_mst_buyer'];
				$ls_curr                = $row['sup_mst_curr_code'];
				$ls_tax                 = $row['sup_mst_tax_id'];
				$ls_term                = $row['sup_mst_terms'];
				$ls_shipvia             = $row['sup_mst_shipvia'];
				$ls_fob                 = $row['sup_mst_fob'];
				$ls_bil_billto          = $row['sup_det_bil_billto'];
				$ls_bil_address1        = $row['sup_det_bil_address1'];
				$ls_bil_address2        = $row['sup_det_bil_address2'];
				$ls_bil_city            = $row['sup_det_bil_city'];
				$ls_bil_state           = $row['sup_det_bil_state'];
				$ls_bil_postal_code     = $row['sup_det_bil_postal_code'];
				$ls_bil_country         = $row['sup_det_bil_country'];
				$ls_bil_phone           = $row['sup_det_bil_phone'];
				$ls_bil_contact         = $row['sup_det_bil_contact'];
				$ls_bil_province        = $row['sup_det_bil_province'];
				$ls_bil_note            = $row['sup_det_bil_note'];
				$ls_shi_shipto          = $row['sup_det_shi_shipto'];
				$ls_shi_address1        = $row['sup_det_shi_address1'];
				$ls_shi_address2        = $row['sup_det_shi_address2'];
				$ls_shi_city            = $row['sup_det_shi_city'];
				$ls_shi_state           = $row['sup_det_shi_state'];
				$ls_shi_postal_code     = $row['sup_det_shi_postal_code'];
				$ls_shi_country         = $row['sup_det_shi_country'];
				$ls_shi_phone           = $row['sup_det_shi_phone'];
				$ls_shi_contact         = $row['sup_det_shi_contact'];
				$ls_shi_province		= $row['sup_det_shi_province'];
				$ls_shi_note			= $row['sup_det_shi_note'];	

			}
		}
		while (sqlsrv_next_result($stmt_get_sup_info));
		sqlsrv_free_stmt($stmt_get_sup_info);
		
		$ldc_rate = 0;
		
		//Get Exchange Rate
		$sql_get_exc_rate = "SELECT 'ldc_rate' = COALESCE(cur_mst_exchange_rate , 0)
						FROM 	cur_mst (NOLOCK)
				Where 	cur_mst.site_cd ='" . $gs_site . "'
				AND		cur_mst_cur_code = '".$ls_curr."'";
				
		$stmt_get_exc_rate = sqlsrv_query($syn_conn, $sql_get_exc_rate);

		if ($stmt_get_exc_rate === false)
		{
			if (($errors = sqlsrv_errors()) != null)
			{
				foreach ($errors as $error)
				{
					//file_put_contents($file_name, $now . "\r\n" . $sql . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
					insert_error_log($gs_site, 'Line 551 '.$error['message'], $audit_user, $module, $action);
				}
				sqlsrv_rollback($syn_conn);
			}
		}

		do
		{
			while ($row = sqlsrv_fetch_array($stmt_get_exc_rate, SQLSRV_FETCH_ASSOC))
			{
				$ldc_rate             = $row['ldc_rate'];
			}
		}
		while (sqlsrv_next_result($stmt_get_exc_rate));
		sqlsrv_free_stmt($stmt_get_exc_rate);
		
		$ldc_tax_rate = 0;
		
		//Get Tax Rate
		$sql_get_tax_rate = "SELECT COALESCE(tax_mst_tax_rate , 0) as ldc_tax_rate
						FROM 	tax_mst (NOLOCK)
				Where 	tax_mst.site_cd ='" . $gs_site . "'
				AND		tax_mst_tax_cd = '".$ls_tax."'";
				
		$stmt_get_tax_info = sqlsrv_query($syn_conn, $sql_get_tax_rate);

		if ($stmt_get_exc_rate === false)
		{
			if (($errors = sqlsrv_errors()) != null)
			{
				foreach ($errors as $error)
				{
					//file_put_contents($file_name, $now . "\r\n" . $sql . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
					insert_error_log($gs_site, 'Line 584 '. $error['message'], $audit_user, $module, $action);
				}
				sqlsrv_rollback($syn_conn);
			}
		}

		do
		{
			while ($row = sqlsrv_fetch_array($stmt_get_tax_info, SQLSRV_FETCH_ASSOC))
			{
				$ldc_tax_rate             = $row['ldc_tax_rate'];
			}
		}
		while (sqlsrv_next_result($stmt_get_tax_info));
		sqlsrv_free_stmt($stmt_get_tax_info);
		
		$ld_sub_tot_cost = $ld_tot_retail_cost;
		
		
		If ($ldc_tax_rate > 0){
			$ldc_tax_amt = $ld_sub_tot_cost * ( $ldc_tax_rate / 100 );
			$ld_total_cost = $ld_sub_tot_cost + $ldc_tax_amt;
		}else{
			$ldc_tax_amt = 0;
			$ld_total_cost = $ld_sub_tot_cost	;
		}
		
		//Insert puo_mst
		$sql_insert_puo_mst = "	INSERT INTO puo_mst ( 	site_cd, 				puo_mst_po_no, 				puo_mst_po_type, 		puo_mst_supplier, 		puo_mst_status, 		puo_mst_po_grp, 
														puo_mst_po_priority, 	puo_mst_po_date, 			puo_mst_po_expire_date, puo_mst_promised_date, 	puo_mst_followup_date, 	puo_mst_clo_date, 
														puo_mst_tax_code, 		puo_mst_taxrate, 			puo_mst_discount_pct, 	puo_mst_curr_code, 		puo_mst_exchange_rate, 	puo_mst_sub_tot_cost, 
														puo_mst_tax, 			puo_mst_freight, 			puo_mst_freight_tax, 	puo_mst_tot_cost, 		puo_mst_po_ammend_ctr, 	puo_mst_print_count, 
														puo_mst_create_by,		puo_mst_create_date, 		audit_user, 			audit_date) 
									 VALUES ( 			?, 						?, 							NULL, 					?, 						?, 						?, 
														NULL, 					?, 							?, 						?, 						?, 						NULL, 
														?, 						?, 							0.00, 					?, 						?, 						?, 
														?,						0.0000, 					0.0000, 				?, 						0, 						0, 
														?, 						GetDate() ,					?, 						GetDate() )" ;

		$params_insert_puo_mst = array(					$gs_site,				$ls_doc,											$ls_supplier,			$ls_status,				$ls_group,
																				$ld_date,					$ld_date,				$ld_date,				$ld_date,	
														$ls_tax,				$ldc_tax_rate,										$ls_curr,				$ldc_rate,				$ld_sub_tot_cost,
														$ldc_tax_amt,																$ld_total_cost,	
														$audit_user,										$audit_user);
										
										
		//echo 	$params_insert_eml_log;							
		$stmt_insert_puo_mst = sqlsrv_query( $syn_conn, $sql_insert_puo_mst, $params_insert_puo_mst);	
		
		if( !$stmt_insert_puo_mst ) {
			$error_message = "Error (INSERT Table puo_mst)";
			if (($errors = sqlsrv_errors()) != null){
				foreach ($errors as $error)	{
					//echo $error['message'];
					//file_put_contents($file_name, $now . "\r\n" . $sql_wo_detail . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
					insert_error_log($gs_site, 'Line 639 '.$error['message'], $audit_user, $module, $action);
				}
				sqlsrv_rollback($syn_conn);
			}		
		}
		sqlsrv_free_stmt( $stmt_insert_puo_mst);
		
		//Get Puo_mst Rowid
		$sql_select_rowid = "SELECT RowID
						FROM 	puo_mst (NOLOCK)
				Where 	puo_mst.site_cd ='" . $gs_site . "'
				AND		puo_mst.puo_mst_po_no = '".$ls_doc."'";
				
		$stmt_select_rowid = sqlsrv_query($syn_conn, $sql_select_rowid);

		if ($stmt_select_rowid === false)
		{
			if (($errors = sqlsrv_errors()) != null)
			{
				foreach ($errors as $error)
				{
					//file_put_contents($file_name, $now . "\r\n" . $sql . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
					insert_error_log($gs_site, 'Line 661 '.$error['message'], $audit_user, $module, $action);
				}
				sqlsrv_rollback($syn_conn);
			}
		}

		do
		{
			while ($row = sqlsrv_fetch_array($stmt_select_rowid, SQLSRV_FETCH_ASSOC))
			{
				$ll_po_RowID             = $row['RowID'];
			}
		}
		while (sqlsrv_next_result($stmt_select_rowid));
		sqlsrv_free_stmt($stmt_select_rowid);
		
		
		//Insert puo_det
		$sql_insert_puo_det = "	INSERT INTO puo_det ( 	site_cd, 					mst_RowID, 					puo_det_contact, 			puo_det_chg_costcenter, 			puo_det_chg_account, 
														puo_det_crd_costcenter, 	puo_det_crd_account, 		puo_det_confirm_flag, 		puo_det_buyer, 						puo_det_fob, 
														puo_det_shipvia, 			puo_det_terms, 				puo_det_po_header, 			puo_det_po_trailer, 				puo_det_shipto, 
														puo_det_shi_address1, 		puo_det_shi_address2, 		puo_det_shi_city, 			puo_det_shi_state, 					puo_det_shi_postal_code, 
														puo_det_shi_country,		puo_det_shi_phone, 			puo_det_shi_contact,		puo_det_shi_province,				puo_det_shi_note, 									
														puo_det_billto, 			puo_det_bil_address1, 		puo_det_bil_address2, 		puo_det_bil_city, 					puo_det_bil_state, 
														puo_det_bil_postal_code,	puo_det_bil_country,		puo_det_bil_phone, 			puo_det_bil_contact, 				puo_det_bil_province,
														puo_det_bil_note, 			puo_det_projectid,			audit_user, 				audit_date) 
									 VALUES ( 			?, 							?, 							?, 							?, 									?, 
														?, 							?, 							'0', 						NULL, 								NULL, 
														NULL, 						?, 							NULL, 						NULL, 								?, 
														?, 							?, 							?, 							?, 									?, 								
														?, 							?,							?, 							?, 									?, 
														?, 							?, 							?, 							?, 									?, 									
														?, 							?, 							?, 							?, 									?, 								
														?, 							?,							?, 							GetDate() )" ;

		$params_insert_puo_det = array(					$gs_site,					$ll_po_RowID,				$ls_contact,				$ls_chg_costcenter,					$ls_chg_account,
														$ls_crd_costcenter,			$ls_crd_account,										
																					$ls_term,																					$ls_shi_shipto,
														$ls_shi_address1,			$ls_shi_address2,			$ls_shi_city,				$ls_shi_state,						$ls_shi_postal_code,
														$ls_shi_country,			$ls_shi_phone,				$ls_shi_contact,			$ls_shi_province,					$ls_shi_note,
														$ls_bil_billto,				$ls_bil_address1,			$ls_bil_address2,			$ls_bil_city,						$ls_bil_state,
														$ls_bil_postal_code,		$ls_bil_country,			$ls_bil_phone,				$ls_bil_contact,					$ls_bil_province,
														$ls_bil_note,				$ls_project,				$audit_user);
										
										
						
		$stmt_insert_puo_det = sqlsrv_query( $syn_conn, $sql_insert_puo_det, $params_insert_puo_det);	
		
		if( !$stmt_insert_puo_det ) {
			$error_message = "Error (INSERT Table puo_det)";
			if (($errors = sqlsrv_errors()) != null){
				foreach ($errors as $error)	{
					//echo $error['message'];
					//file_put_contents($file_name, $now . "\r\n" . $sql_wo_detail . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
					insert_error_log($gs_site, 'Line 715 '.$error['message'], $audit_user, $module, $action);
				}
				sqlsrv_rollback($syn_conn);
			}
		
			$insert_email = false;
			
		}
		sqlsrv_free_stmt( $stmt_insert_puo_det);
		
		//Insert puo_ls2
		$sql_insert_puo_ls2 = "	INSERT INTO puo_ls2 ( 	site_cd , 					mst_RowID , 				puo_ls2_varchar1 , 			puo_ls2_varchar2 , 					puo_ls2_varchar3 , 
														puo_ls2_datetime1 , 		puo_ls2_datetime2 , 		puo_ls2_numeric1 , 			audit_user , 						audit_date) 
									 VALUES ( 			?, 							?, 							?, 							?, 									?, 
														GetDate(),					NULL,						0,							?, 									GetDate() )" ;

		$params_insert_puo_ls2 = array(					$gs_site,					$ll_po_RowID,				$ls_doc,					$ls_status,							$audit_user,
																																			$audit_user);
								
		$stmt_insert_puo_ls2 = sqlsrv_query( $syn_conn, $sql_insert_puo_ls2, $params_insert_puo_ls2);	
		
		if( !$stmt_insert_puo_ls2 ) {
			$error_message = "Error (INSERT Table puo_ls2)";
			if (($errors = sqlsrv_errors()) != null){
				foreach ($errors as $error)	{
					//echo $error['message'];
					//file_put_contents($file_name, $now . "\r\n" . $sql_wo_detail . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
					insert_error_log($gs_site, 'Line 742 '.$error['message'], $audit_user, $module, $action);
				}
				sqlsrv_rollback($syn_conn);
			}
		
			$insert_email = false;
			
		}
		sqlsrv_free_stmt( $stmt_insert_puo_ls2);
		
		//loop pur_ls1
		
		$ld_line_cost = 0;
		$ld_line_tax = 0;
		
		$sql_get_po_1st_status = "Select pur_ls1.site_cd,			mst_RowID,					pur_ls1_pr_lineno,			pur_ls1_wo_no,			pur_ls1_mr_no,			pur_ls1_mr_lineno,  			pur_ls1_quo_no, 
										pur_ls1_contract_id, 		pur_ls1_contract_lineno, 	pur_ls1_po_no,				pur_ls1_po_lineno,		pur_ls1_op_refno,		pur_ls1_item_category,			pur_ls1_stockno,
										pur_ls1_stk_locn,			pur_ls1_desc,				pur_ls1_ord_uom,			pur_ls1_ord_qty,		pur_ls1_supplier,		pur_ls1_rec_supplier,			pur_ls1_item_cost,
										pur_ls1_last_item_cost,		pur_ls1_taxable,			pur_ls1_tax_code,			pur_ls1_chg_costcenter,	pur_ls1_chg_account,	pur_ls1_activity_code,			pur_ls1_projectid,
										pur_ls1_rcv_in_full,		pur_ls1_cur_code,			pur_ls1_cur_exchange_rate,	pur_ls1_retail_price,	pur_ls1_tax_rate,		pur_ls1_tax_value,				pur_ls1_varchar1,
										pur_ls1_varchar2,			pur_ls1_varchar3,			pur_ls1_varchar4,			pur_ls1_varchar5,		pur_ls1_numeric1,		pur_ls1_numeric2,				pur_ls1_numeric3,			
										pur_ls1_numeric4,			pur_ls1_numeric5,			pur_ls1_datetime1,			pur_ls1_datetime2,		pur_ls1_datetime3,		pur_ls1_datetime4,				pur_ls1_datetime5,
										pur_ls1.audit_user,			pur_ls1.audit_date,			pur_ls1.column1,			pur_ls1.column2,		pur_ls1.column3,		pur_ls1.column4,				pur_ls1.column5,
										pur_ls1.RowID
					From 	pur_ls1 (NOLOCK)
					Where 	site_cd ='" . $gs_site . "'
					AND		pur_ls1.mst_rowid = ".$al_Rowid." order by pur_ls1_pr_lineno";

		$stmt_get_po_1st_status = sqlsrv_query($syn_conn, $sql_get_po_1st_status);

		if ($stmt_get_po_1st_status === false)
		{
			if (($errors = sqlsrv_errors()) != null)
			{
				foreach ($errors as $error)
				{
					//file_put_contents($file_name, $now . "\r\n" . $sql . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
					insert_error_log($gs_site, 'Line 779'.$error['message'], $audit_user, $module, $action);
				}
				sqlsrv_rollback($syn_conn);
			}
		}

		$ll_cnt = 0;

		do
		{
			while ($row = sqlsrv_fetch_array($stmt_get_po_1st_status, SQLSRV_FETCH_ASSOC))
			{
				$ll_cnt				 = $ll_cnt + 1;
				
				$ll_pr_lineno		 = $row['pur_ls1_pr_lineno'];
				$ldc_ord_qty		 = $row['pur_ls1_ord_qty'];
				$ldc_item_cost		 = $row['pur_ls1_item_cost'];
				$ldc_retail_price	 = $row['pur_ls1_retail_price'];
				$ls_ord_uom			 = $row['pur_ls1_ord_uom'];
				$ls_stockno			 = $row['pur_ls1_stockno'];
				$ls_stk_locn		 = $row['pur_ls1_stk_locn'];
				$ls_desc			 = $row['pur_ls1_desc'];
				$ls_chg_costcenter	 = $row['pur_ls1_chg_costcenter'];
				$ls_chg_account		 = $row['pur_ls1_chg_account'];
				$ls_item_cat		 = $row['pur_ls1_item_category'];
				$ls_wo				 = $row['pur_ls1_wo_no'];
				$ls_project			 = $row['pur_ls1_projectid'];
				$pur_ls1_tax_code	 = $row['pur_ls1_tax_code'];
				
				$pur_ls1_tax_code = trim((string)($pur_ls1_tax_code ?? ''));
				
				If (strlen($pur_ls1_tax_code) > 0){
					$ls_tax					= $row['pur_ls1_tax_code'];
					$ldc_tax_rate			= $row['pur_ls1_tax_rate'];
					$ldc_tax_amt			= $row['pur_ls1_tax_value'];
				}
												
				If ($ldc_rate <> 0){
					$ldc_item_cost = $ldc_retail_price / $ldc_rate;
				}else{
					$ldc_item_cost =  $ldc_retail_price;
				}
				
				If ($ldc_tax_rate > 0 ){
					$ldc_tax_amt = ( $ldc_retail_price * ( $ldc_tax_rate / 100 ) ) * $ldc_ord_qty;
				}else{
					$ldc_tax_amt = 0;
					
				}
				//Insert puo_ls1
				$sql_insert_puo_ls1 = "INSERT INTO puo_ls1 ( 		site_cd , 							mst_RowID , 					puo_ls1_po_lineno, 						puo_ls1_pr_no, 							puo_ls1_pr_lineno, 
																	puo_ls1_craft, 						puo_ls1_contract_id, 			puo_ls1_contract_lineno, 				puo_ls1_wo_no, 							puo_ls1_activity_code, 
																	puo_ls1_promised_date, 				puo_ls1_dept, 					puo_ls1_markfor, 						puo_ls1_taxable, 						puo_ls1_cur_code, 
																	puo_ls1_cur_exchange_rate, 			puo_ls1_suggest_qty, 			puo_ls1_ord_qty, 						puo_ls1_item_cost, 						puo_ls1_ord_uom, 
																	puo_ls1_stockno, 					puo_ls1_description, 			puo_ls1_ext_description, 				puo_ls1_rcv_qty,						puo_ls1_bo_qty, 
																	puo_ls1_chg_costcenter, 			puo_ls1_chg_account, 			puo_ls1_crd_costcenter, 				puo_ls1_crd_account, 					puo_ls1_clo_flag, 
																	puo_ls1_item_category, 				puo_ls1_req_date, 				puo_ls1_g_s, 							puo_ls1_invoice_qty, 					puo_ls1_last_change_date, 
																	puo_ls1_retail_price, 				puo_ls1_discount_pct, 			puo_ls1_discount_amt, 					puo_ls1_supplier_partno, 				puo_ls1_mr_no, 
																	puo_ls1_mr_lineno, 					puo_ls1_priority_po_detail, 	puo_ls1_inv_total_cost, 				puo_ls1_tax_rate, 						puo_ls1_tax_value, 
																	puo_ls1_net_price, 					puo_ls1_tax_code, 				puo_ls1_projectid, 						puo_ls1_contract_ref, 					puo_ls1_com_code, 
																	puo_ls1_stk_locn, 					puo_ls1_clo_date, 				puo_ls1_match_qty,						audit_user, 							audit_date)
										VALUES ( 					?, 									?, 								?, 										?, 										?, 
																	NULL, 								NULL, 							NULL, 									?, 										NULL, 
																	NULL, 								NULL, 							NULL, 									'0', 									?, 
																	?, 									?, 								?, 										?, 										?, 
																	?, 									?, 								NULL, 									0, 										0, 
																	?, 									?, 								?, 										?, 										'0', 
																	?, 									NULL, 							NULL, 									0, 										NULL, 
																	?, 									0, 								0, 										NULL, 									NULL, 
																	NULL, 								NULL, 							0, 										?, 										?, 
																	?, 									?, 								?, 										NULL, 									NULL, 
																	?, 									NULL, 							0,										?, 										GetDate()) ";												
				$params_insert_puo_ls1 = array(						$gs_site,							$ll_po_RowID,					$ll_cnt,								$ls_pr_no,								$ll_pr_lineno,
																																												$ls_wo,						
																																																						$ls_curr,
																	$ldc_rate,							$ldc_ord_qty,					$ldc_ord_qty,							$ldc_item_cost,							$ls_ord_uom,
																	$ls_stockno,						$ls_desc,						
																	$ls_chg_costcenter,					$ls_chg_account,				$ls_crd_costcenter,						$ls_crd_account,
																	$ls_item_cat,	
																	$ldc_retail_price,
																																												$ldc_tax_rate,							$ldc_tax_amt,
																	$ldc_retail_price,					$ls_tax,						$ls_project,
																	$ls_stk_locn,																								$audit_user								);
				
				$stmt_insert_puo_ls1 = sqlsrv_query( $syn_conn, $sql_insert_puo_ls1, $params_insert_puo_ls1);	
				
				if( !$stmt_insert_puo_ls1 ) {
					$error_message = "Error (INSERT Table puo_ls1)";
					if (($errors = sqlsrv_errors()) != null){
						foreach ($errors as $error)	{
							//echo $error['message'];
							//file_put_contents($file_name, $now . "\r\n" . $sql_wo_detail . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
							insert_error_log($gs_site, 'Line 869 '.$error['message'], $audit_user, $module, $action);
						}
						sqlsrv_rollback($syn_conn);
					}		
				}
				sqlsrv_free_stmt( $stmt_insert_puo_ls1);
				$ls_stockno = trim((string)($ls_stockno ?? ''));
				If (strlen($ls_stockno) > 0 ){
					//Select UOM
					$sql_get_uom = "SELECT 'll_itm_rowid' = itm_mst.RowID,
											itm_det.itm_det_issue_uom
							FROM 	itm_mst (NOLOCK),
									itm_det (NOLOCK)
							WHERE 	itm_mst.site_cd = itm_det.site_cd
							AND		itm_mst.RowID = itm_det.mst_RowID
							AND		itm_mst.site_cd = '".$gs_site."'
							AND		itm_mst.itm_mst_stockno = '".$ls_stockno."'";

					$stmt_get_uom = sqlsrv_query($syn_conn, $sql_get_uom);

					if ($stmt_get_uom === false)
					{
						if (($errors = sqlsrv_errors()) != null)
						{
							foreach ($errors as $error)
							{
								insert_error_log($gs_site, 'Line 894'.$error['message'], $audit_user, $module, $action);
							}
							sqlsrv_rollback($syn_conn);
						}

						sqlsrv_rollback($syn_conn);
						sqlsrv_close($syn_conn);

						$error_message = "Error selecting table (itm_mst, itm_det) - ".$now;
					}

					do
					{
						while ($row = sqlsrv_fetch_array($stmt_get_uom, SQLSRV_FETCH_ASSOC))
						{

							$ll_itm_rowid = $row['ll_itm_rowid'];
							$ls_issue_uom = $row['itm_det_issue_uom'];

						}
					}
					while (sqlsrv_next_result($stmt_get_uom));
					sqlsrv_free_stmt($stmt_get_uom);
					
					// Conversion Factor
					If ($ls_ord_uom <> $ls_issue_uom){
						//Select UOM uom_con_factor
						$sql_get_uom_fac = "SELECT uom_con_factor
								FROM 	uom_con (NOLOCK)
								WHERE 	uom_con.site_cd = '".$gs_site."'
								AND		uom_con_from_uom = '".$ls_ord_uom."' 
								AND 	uom_con_to_uom = '".$ls_issue_uom."'";

						$stmt_get_uom_fac = sqlsrv_query($syn_conn, $sql_get_uom_fac);

						if ($stmt_get_uom_fac === false)
						{
							if (($errors = sqlsrv_errors()) != null)
							{
								foreach ($errors as $error)
								{
									insert_error_log($gs_site, 'Line 936 '.$error['message'], $audit_user, $module, $action);
								}
								sqlsrv_rollback($syn_conn);
							}

							$error_message = "Error selecting table (itm_mst, itm_det) - ".$now;
							
						}

						do
						{
							while ($row = sqlsrv_fetch_array($stmt_get_uom_fac, SQLSRV_FETCH_ASSOC))
							{

								$ldc_conversion_factor = $row['uom_con_factor'];

							}
						}
						while (sqlsrv_next_result($stmt_get_uom_fac));
						sqlsrv_free_stmt($stmt_get_uom_fac);
						
						
						If (empty($ldc_conversion_factor) || $ldc_conversion_factor <= 0){
							$ldc_conversion_factor = 1;
						} 
						
						$ldc_ord_qty = $ldc_ord_qty * $ldc_conversion_factor;
					}
					//Update itm_det
					$sql_update_itm_det = "UPDATE 	itm_det
											SET		itm_det_due_in = COALESCE(itm_det_due_in, 0) + ?,
														itm_det_pr_due_in = COALESCE(itm_det_pr_due_in, 0) - ?
											WHERE	site_cd = ?
											AND		mst_rowid = ?";												
					$params_update_itm_det = array($ldc_ord_qty, $ldc_ord_qty,	$gs_site, $ll_itm_rowid);
					
					$stmt_update_itm_det = sqlsrv_query( $syn_conn, $sql_update_itm_det, $params_update_itm_det);	
					
					if( !$stmt_update_itm_det ) {
						$error_message = "Error (Update Table itm_det)";
						if (($errors = sqlsrv_errors()) != null){
							foreach ($errors as $error)	{
								//echo $error['message'];
								//file_put_contents($file_name, $now . "\r\n" . $sql_wo_detail . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
								insert_error_log($gs_site, 'Line 980 '.$error['message'], $audit_user, $module, $action);
							}
							sqlsrv_rollback($syn_conn);
						}		
					}
					sqlsrv_free_stmt( $stmt_update_itm_det);
					
					//Update itm_Loc
					$sql_update_itm_loc = "UPDATE	itm_loc
											SET		itm_loc_due_in = COALESCE(itm_loc_due_in, 0) + ?,
														itm_loc_pr_due_in = COALESCE(itm_loc_pr_due_in, 0) - ?
											WHERE	site_cd = ?
											AND		mst_rowid = ? 
											AND		itm_loc_stk_loc = ?";											
					$params_update_itm_loc = array($ldc_ord_qty, $ldc_ord_qty,	$gs_site, $ll_itm_rowid, $ls_stk_locn);
					
					$stmt_update_itm_det = sqlsrv_query( $syn_conn, $sql_update_itm_loc, $params_update_itm_loc);	
					
					if( !$stmt_update_itm_det ) {
						$error_message = "Error (Update Table itm_loc)";
						if (($errors = sqlsrv_errors()) != null){
							foreach ($errors as $error)	{
								//echo $error['message'];
								//file_put_contents($file_name, $now . "\r\n" . $sql_wo_detail . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
								insert_error_log($gs_site, 'Line 1004 '.$error['message'], $audit_user, $module, $action);
							}
							sqlsrv_rollback($syn_conn);
						}		
					}
					sqlsrv_free_stmt( $stmt_update_itm_det);
						
						
					}
					
					//Update PO and line to PR Line
					$sql_update_pr_line = "UPDATE	pur_ls1 
											Set 	pur_ls1_po_no = ?,
													pur_ls1_po_lineno = ?
											Where 	pur_ls1.site_cd = ?
											And		mst_rowid = ? 
											AND		pur_ls1_pr_lineno = ?";											
					$params_update_pr_line = array($ls_doc, $ll_cnt, $gs_site, $al_Rowid, $ll_pr_lineno);
					
					$stmt_update_pr_line = sqlsrv_query( $syn_conn, $sql_update_pr_line, $params_update_pr_line);	
					
					if( !$stmt_update_pr_line ) {
						$error_message = "Error (Update Table pur_ls1)";
						if (($errors = sqlsrv_errors()) != null){
							foreach ($errors as $error)	{
								//echo $error['message'];
								//file_put_contents($file_name, $now . "\r\n" . $sql_wo_detail . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
								insert_error_log($gs_site, 'Line 1031 '. $error['message'], $audit_user, $module, $action);
							}
							sqlsrv_rollback($syn_conn);
						}		
					}
					sqlsrv_free_stmt( $stmt_update_pr_line);
					
					$ld_line_cost 	= $ld_line_cost + ($ldc_ord_qty * $ldc_retail_price);
					$ld_line_tax 	= $ld_line_tax + $ldc_tax_amt;
				

			}
			//WHILE
		}
		//DO
		while (sqlsrv_next_result($stmt_get_po_1st_status));
		sqlsrv_free_stmt($stmt_get_po_1st_status);
		
		
			
	}
	

	//f_update_purchase_budget($gs_site, $ldt_pr_date, $ls_chg_costcenter, $ls_chg_account, "PR_PO", $ldc_pr_cost, $syn_conn, $audit_user);
	f_update_purchase_budget($gs_site, $ldt_pr_date, $ls_chg_costcenter, $ls_chg_account, "MINUS_AWA_PR", $ldc_pr_cost, $syn_conn, $audit_user);
	f_update_purchase_budget($gs_site, $ldt_pr_date, $ls_chg_costcenter, $ls_chg_account, "ADD_PO", $ldc_pr_cost, $syn_conn, $audit_user);
	
	//wf_budget_update("PR_PO")
	$ld_total = $ld_line_cost + $ld_line_tax;
	
	//Update PO Master Cost
	$sql_update_po_mst = "UPDATE	puo_mst 
							Set 	puo_mst_sub_tot_cost = ?,
									puo_mst_tax = ?,
									puo_mst_tot_cost = ?
							Where 	puo_mst.site_cd = ?
							AND		RowID = ?";											
	$params_update_po_mst = array($ld_line_cost, $ld_line_tax, $ld_total, $gs_site, $ll_po_RowID);
	
	$stmt_update_po_mst = sqlsrv_query( $syn_conn, $sql_update_po_mst, $params_update_po_mst);	
	
	if( !$stmt_update_po_mst ) {
		$error_message = "Error (Update Table puo_mst)";
		if (($errors = sqlsrv_errors()) != null){
			foreach ($errors as $error)	{
				//echo $error['message'];
				//file_put_contents($file_name, $now . "\r\n" . $sql_wo_detail . "\r\n" . "SQLSTATE: " . $error['SQLSTATE'] . "\r\n" . "code: " . $error['code'] . "\r\n" . "message: " . $error['message'] . "\r\n\r\n", FILE_APPEND);
				insert_error_log($gs_site, 'Line 1078 '.$error['message'], $audit_user, $module, $action);
				
			}
			sqlsrv_rollback($syn_conn);
		}		
	}
	sqlsrv_free_stmt($stmt_update_po_mst);
	
	$sql = "UPDATE 	cnt_mst WITH (UPDLOCK)
				SET 	cnt_mst_counter = cnt_mst_counter + 1
				WHERE 	site_cd ='" . $gs_site . "' 
				AND 	cnt_mst_module_cd = 'PO'";

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

	if ($stmt === false)
	{
		if (($errors = sqlsrv_errors()) != null)
		{
			foreach ($errors as $error)
			{
				insert_error_log($gs_site, 'Line 1099 '.$error['message'], $audit_user, $module, $action);
				
			}
			sqlsrv_rollback($syn_conn);
		}
		$error_message = "(" . $now . ") Error updating table (cnt_mst)";
		
	}
	sqlsrv_free_stmt($stmt);
	
	sqlsrv_commit($syn_conn);
    sqlsrv_close($syn_conn);
	
	
	return "The assigned Purchase Order No is " . $ls_doc . ".";
	

}

?>