frappe.ui.form.on("Payment Order", {
	refresh(frm) {
		if (frm.doc.docstatus !== 1 || frm.doc.payment_order_type !== "Payment Entry") return;

		// Send to Kapital Bank
		frm.add_custom_button(__("Send to Kapital Bank"), () => {
			frappe.confirm(__("Send all Payment Entries to Kapital Bank?"), () => {
				frappe.show_alert({ message: __("Sending..."), indicator: "blue" });
				frappe.call({
					method: "kapital_bank.payment_api.send_payment_order",
					args: { name: frm.doc.name },
					callback(r) {
						const res = r.message;
						if (!res) return;
						if (res.success) {
							const ind = res.failed > 0 ? "orange" : "green";
							frappe.show_alert(
								{ message: __("Sent: {0}, Failed: {1}", [res.sent, res.failed]), indicator: ind },
								6
							);
							frm.reload_doc();
						} else {
							const msg =
								res.errors && res.errors.length
									? "<ul>" + res.errors.map(e => `<li>${e}</li>`).join("") + "</ul>"
									: res.message || __("Unknown error");
							frappe.msgprint({ title: __("Send Failed"), indicator: "red", message: msg });
						}
					},
				});
			});
		}, __("Kapital Bank"));

		// Check Status
		frm.add_custom_button(__("Check Status"), () => {
			frappe.show_alert({ message: __("Checking..."), indicator: "blue" });
			frappe.call({
				method: "kapital_bank.payment_api.check_payment_status",
				args: { name: frm.doc.name },
				callback(r) {
					const res = r.message;
					if (!res) return;
					const msg = res.message || __("Updated: {0}", [res.updated || 0]);
					frappe.show_alert({ message: msg, indicator: res.success ? "green" : "orange" }, 5);
					frm.reload_doc();
				},
			});
		}, __("Kapital Bank"));

		// Cancel Bank Transfer
		frm.add_custom_button(__("Cancel Bank Transfer"), () => {
			frappe.confirm(__("Cancel all pending bank transfers for this Payment Order?"), () => {
				frappe.call({
					method: "kapital_bank.payment_api.cancel_payment_order",
					args: { name: frm.doc.name },
					callback(r) {
						const res = r.message;
						if (!res) return;
						if (res.success && res.cancelled > 0) {
							frappe.show_alert(
								{ message: __("Cancelled: {0}", [res.cancelled]), indicator: "green" },
								5
							);
							frm.reload_doc();
						} else if (res.errors && res.errors.length) {
							frappe.msgprint({
								title: __("Cancel Failed"),
								indicator: "red",
								message: "<ul>" + res.errors.map(e => `<li>${e}</li>`).join("") + "</ul>",
							});
						} else if (res.success) {
							frappe.show_alert(
								{ message: res.message || __("Nothing to cancel"), indicator: "grey" },
								5
							);
							frm.reload_doc();
						} else {
							frappe.msgprint({
								title: __("Cancel Failed"),
								indicator: "red",
								message: res.message || __("Unknown error"),
							});
						}
					},
				});
			});
		}, __("Kapital Bank"));
	},
});
