I haven't examined the whole page but I notice one particular problem that would be a good place to start.
$page-- doesn't mean "one less than $page". It means make $page one less.
Likewise, $page++ doesn't mean one higher. It means make $page one higher.
So when you say $prevpage = $page--;
you are actually changing the value of $page. Then later when you say,
$nextpage = $page++;
you are adding one back to $page... so you are setting it's value back to what it was before. So $nextpage actually equals the current page!! (and that's not what you want).
Therefore, you should really say:
$prevpage = $page-1;
and
$nextpage = $page+1;
That's a good place to start anyway.