<?php
$prev = $pagina - 1;
$next = $pagina + 1;
$lastpage = ceil($total_pages / $limit);
$LastPagem1 = $lastpage - 1;
$paginate = '';
if ($lastpage > 1) {
    $paginate .= "";
 echo "";
    if ($pagina > 1) {
        $paginate .= "<a href=\"" . $targetpage . "?pagina=$prev\" class=\"w3-button w3-bluepm w3-hover-seagreen\"><i class=\"fa fa-arrow-left\"></i></a>";
    } else {
        $paginate .= "<a class=\"w3-button w3-bluepm w3-hide\"><i class=\"fa fa-arrow-left\"></i></a>";
    }
    if ($lastpage < 3 + ($stages * 2))
        {
        for ($counter = 1; $counter <= $lastpage; $counter++) {
            if ($counter == $pagina) {
                $paginate .= "<a class=\"w3-button w3-red w3-hover-seagreen\" title=\"Pagina curentă\">$counter</a>";
            } else {
                $paginate .= "<a class=\"w3-button w3-bluepm w3-hover-seagreen\" href='$targetpage?pagina=$counter'>$counter</a>";
            }
        }
    } elseif ($lastpage > 3 + ($stages * 2))
    {
        
        if ($pagina < 1 + ($stages * 2)) {
            for ($counter = 1; $counter < 2 + ($stages * 2); $counter++) {
                if ($counter == $pagina) {
                    $paginate .= "<a class=\"w3-button w3-red w3-hover-seagreen\" title=\"Pagina curentă\">$counter</a>";
                } else {
                    $paginate .= "<a class=\"w3-button w3-blue\" href='$targetpage?pagina=$counter'>$counter</a>";
                }
            }
        }
        
        elseif ($lastpage - ($stages * 2) > $pagina && $pagina > ($stages * 2)) {            
            for ($counter = $pagina - $stages; $counter <= $pagina + $stages; $counter++) {
                if ($counter == $pagina) {
                    $paginate .= "<a class=\"w3-button w3-red w3-hover-seagreen\" title=\"Pagina curentă\">$counter</a>";
                } else {
                    $paginate .= "<a class=\"w3-button w3-bluepm w3-hover-seagreen\" href='$targetpage?pagina=$counter'>$counter</a>";
                }
            }            
        }        
        else {           
            for ($counter = $lastpage - (3 + ($stages * 2)); $counter <= $lastpage; $counter++) {
                if ($counter == $pagina) {
                    $paginate .= "<a class=\"w3-button w3-red w3-hover-seagreen\" title=\"Pagina curentă\">$counter</a>";
                } else {
                    $paginate .= "<a class=\"w3-button w3-bluepm w3-hover-seagreen\" href='$targetpage?pagina=$counter'>$counter</a>";
                }
            }
        }
    }
    if ($pagina < $counter - 1) {
        $paginate .= "<a class=\"w3-button w3-bluepm w3-hover-seagreen\" href='$targetpage?pagina=$next'><i class=\"fa fa-arrow-right\"></i></a>";
    } else {
        $paginate .= "<a class='w3-button w3-bluepm w3-hide'><i class=\"fa fa-arrow-right\"></i></a>";
    }
    $paginate .= "";
}
?>