Custom SQL report from WHMCS

Job ID: 37032567

Budget: $30 – $250 USD

I have a SQL PHP report running from WHMCS that is pulling a bunch of custom records and putting them all together. The issue that I am having is the report runs through a list of products and does some joins and pulls the data. What I need to have happen is when a record is pulled and the product is not = 151 look to see if the clientID has a product 151 and pull a custom value from that product if the Primary flag is set to true.

Im attaching the code that I have been using for a review and you can get a starting point and help clean it up.
Related categories: PHP SQL MySQL WHMCS