Then it should work like this:
where tt.fkbranchid = @branchid
and TT.DateCreated >= '{$begdate}'
and TT.DateCreated < '{$enddate}'
and (P.code not in ('089998', '089997'))
AND (Left(d.instorecode,3)='502' or d.id='312')
That seems to be exactly what you started with. Does the query work if you use only one of the where-statements? Start with "where tt.fkbranchid = @branchid" and if that works go to the next row. The last row should be divided into 3, one for each statement ("Left(d.instorecode,3)='502'" and "d.id='312'") and one for both of them. This way you will get to know exactly what it is that is a problem.
Another way to see problems is to echo the query, then it is often possible to spot problems you get with all the PHP logic and variables already submitted.
It could be the @branchid, I just guess that it should be $branchid instead. But I don't know for sure.