import frappe


def execute():
	if frappe.db.exists("DocType", "Kapital Bank Purpose Mapping"):
		frappe.rename_doc("DocType", "Kapital Bank Purpose Mapping", "Kapital Bank Transaction Mapping", force=True)
		frappe.db.commit()

	# Rename the child table field in Settings
	if frappe.db.exists("DocType", "Kapital Bank Settings"):
		old_field = "purpose_mappings"
		new_field = "transaction_mappings"
		meta = frappe.get_meta("Kapital Bank Settings")
		if meta.has_field(old_field) and not meta.has_field(new_field):
			frappe.db.sql("""
				UPDATE `tabDocField`
				SET fieldname = %s
				WHERE fieldname = %s AND parent = 'Kapital Bank Settings'
			""", (new_field, old_field))

			# Rename the tab and section fields too
			for old, new in [
				("purpose_mappings_tab", "transaction_mappings_tab"),
				("purpose_mappings_section", "transaction_mappings_section"),
			]:
				frappe.db.sql("""
					UPDATE `tabDocField`
					SET fieldname = %s
					WHERE fieldname = %s AND parent = 'Kapital Bank Settings'
				""", (new, old))

			frappe.db.commit()
			frappe.clear_cache(doctype="Kapital Bank Settings")
