fix: Fixes in get_balance_on function (#18324)

diff --git a/erpnext/accounts/utils.py b/erpnext/accounts/utils.py
index e75dd95..e41c74c 100644
--- a/erpnext/accounts/utils.py
+++ b/erpnext/accounts/utils.py
@@ -104,6 +104,9 @@
 		# get balance of all entries that exist
 		date = nowdate()
 
+	if account:
+		acc = frappe.get_doc("Account", account)
+
 	try:
 		year_start_date = get_fiscal_year(date, verbose=0)[1]
 	except FiscalYearError:
@@ -118,7 +121,7 @@
 
 	allow_cost_center_in_entry_of_bs_account = get_allow_cost_center_in_entry_of_bs_account()
 
-	if cost_center and allow_cost_center_in_entry_of_bs_account:
+	if cost_center and (allow_cost_center_in_entry_of_bs_account or acc.report_type =='Profit and Loss'):
 		cc = frappe.get_doc("Cost Center", cost_center)
 		if cc.is_group:
 			cond.append(""" exists (
@@ -132,20 +135,13 @@
 
 	if account:
 
-		acc = frappe.get_doc("Account", account)
-
 		if not frappe.flags.ignore_account_permission:
 			acc.check_permission("read")
 
-
-		if not allow_cost_center_in_entry_of_bs_account and acc.report_type == 'Profit and Loss':
+		if acc.report_type == 'Profit and Loss':
 			# for pl accounts, get balance within a fiscal year
 			cond.append("posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" \
 				% year_start_date)
-		elif allow_cost_center_in_entry_of_bs_account:
-			# for all accounts, get balance within a fiscal year if maintain cost center in balance account is checked
-			cond.append("posting_date >= '%s' and voucher_type != 'Period Closing Voucher'" \
-				% year_start_date)
 		# different filter for group and ledger - improved performance
 		if acc.is_group:
 			cond.append("""exists (