import frappe

def on_submit(doc, method):
    print("DEBUG: On Submit Triggered for Payment Entry")
    is_advance_payment = any(ref.reference_doctype == "Sales Order" for ref in doc.references)
    if is_advance_payment:
        print("DEBUG: Payment Entry is for an advance payment, checking Sales Order if half down requirement is met.")
        so_ref = next((ref for ref in doc.references if ref.reference_doctype == "Sales Order"), None)
        if so_ref:
            so_doc = frappe.get_doc("Sales Order", so_ref.reference_name)
            if so_doc.requires_half_payment:
                is_paid = so_doc.custom_halfdown_amount <= so_doc.advance_paid or so_doc.advance_paid >= so_doc.grand_total / 2
                if is_paid and not so_doc.custom_halfdown_is_paid:
                    print("DEBUG: Sales Order requires half payment and it has not been marked as paid, marking it as paid now.")
                    so_doc.custom_halfdown_is_paid = 1
                    so_doc.save()