Clearly I should just do it in php. This is messy but works, now to refactor