It may not be a good use of your time to try to work out exactly how the malicious stuff on your site works. It's hard to be confident you've found it all.
Instead, the standard advice is to reformat and re-install from trusted backups that date back before the intrusion. There is a lot more to be said about this. Rather than repeating what others have written, I will direct you to the question "what to do after suspected intrusion on hobby webserver""what to do after suspected intrusion on hobby webserver", which covers this topic pretty well.