// Copyright (c) 2025, Frappe and contributors
// For license information, please see license.txt

frappe.ui.form.on('Mpesa Setup', {
	onload_post_render: function (frm) {
		frm.events.setup_account_balance_html(frm);
	},

	refresh: function (frm) {
		frappe.realtime.on('refresh_mpesa_dashboard', function () {
			frm.reload_pg();
			frm.events.setup_account_balance_html(frm);
		});
	},

	get_account_balance: function (frm) {
		if (!frm.pg.initiator_name && !frm.pg.security_credential) {
			frappe.throw(
				__('Please set the initiator name and the security credential'),
			);
		}
		frappe.call({
			method: 'get_account_balance_info',
			pg: frm.pg,
		});
	},

	setup_account_balance_html: function (frm) {
		if (!frm.pg.account_balance) return;
		$('div').remove('.form-dashboard-section.custom');
		frm.dashboard.add_section(
			frappe.render_template('account_balance', {
				data: JSON.parse(frm.pg.account_balance),
			}),
		);
		frm.dashboard.show();
	},
});
