How can I create auto Credit note through Custom code?

I want create auto credit note against AR invoice entry through custom code and auto knock off with the parent invoice.

Any idea on it ,

Auto Credit Note and Au knocking off…