<?php

class Pagination {

    public function menu($table, $url, $pager, $where = "", $per_page = PAGES, $offset = 2, $type = NULL){

        if ($type != 'search') {
            $sql = "SELECT COUNT(*) FROM `$table` $where";
            $query = Flight::db()->query($sql);
            $rows = $query->fetchColumn();
        } else {
            $v = Flight::db()->prepare("SELECT * FROM video WHERE {$_SESSION['s_type']} LIKE CONCAT('%', :search, '%')");
            $v->execute(array(':search' => $_SESSION['s_query']));
            
            
            $rows = count($v->fetchAll());         
        }
        
        if (!empty($per_page))
            $per_page = (int)$per_page;
        else
            $per_page = 10;

        $last = ceil($rows / $per_page );

        if ($last < 1)
            $last = 1;

        $pagenum = 1;

        if (isset($pager))
            $pagenum = (int)$pager;

        if ($pagenum < 1)
            $pagenum = 1;
        elseif ($pagenum > $last)
            $pagenum = $last;

        $limit = 'LIMIT '.($pagenum - 1) * $per_page.','.$per_page;
        $this->limit = $limit;

        $paginationCtrls = '<div class="pagination"><center>';

        if ($last != 1){

            if ($pagenum == 1){
                $paginationCtrls .= '<span class="active"> <<</span> ';
            }

            if ($pagenum > 1){
                $previous = $pagenum - 1;
                $paginationCtrls .= '<a href="'.$url.'/page/1"> <<</a> ';
                for ($i = $pagenum-$offset; $i< $pagenum; $i++){
                    if ($i>0){
                        $paginationCtrls .= '<a href="'.$url.'/page/'.$i.'"> '.$i.'</a> ';
                    }
                }
            }

            $paginationCtrls .= '<span class="active"> '.$pagenum.'</span> ';

            for ($i = $pagenum+1; $i<=$last; $i++){
                $paginationCtrls .= '<a href="'.$url.'/page/'.$i.'"> '.$i.'</a> ';
                if ($i >= $pagenum+$offset){
                    break;
                }
            }

            if ($pagenum != $last) {
                $next = $pagenum + 1;
                $paginationCtrls .= '<a href="' . $url . '/page/' . $last . '"> >></a> ';
            }

            if ($pagenum == $last){
                $paginationCtrls .= '<span class="active"> >></div> ';
            }
        }

        $paginationCtrls .= "</center></div>";
        return $paginationCtrls;

    }
    public function limit(){
        return $this->limit;
    }
}
