<?php


class Paging
{
    private $conn;

    function __construct()
    {
        require_once dirname(__FILE__) . '/db_connect.php';

        // opening db connection
        $db = new DbConnect();
        $this->conn = $db->connect();
    }

    public function populateView()
    {

    }


    //returns the query to perform paging
    public function getQuery($query, $records_per_page)
    {
        $starting_position = 0;
        if (isset($_GET["page_no"])) {
            $starting_position = ($_GET["page_no"] - 1) * $records_per_page;
        }
        $query2 = $query . " limit $starting_position,$records_per_page";
        return $query2;
    }


    public function pagingLink($query, $records_per_page)
    {

        $self = $_SERVER['PHP_SELF'];

        $stmt = $this->conn->prepare($query);
        $stmt->execute();
        $stmt->store_result();
        $num_rows = $stmt->num_rows;
        $stmt->close();

        $total_no_of_records = $num_rows;

        if ($total_no_of_records > 0 && $total_no_of_records > $records_per_page) { ?>
            <ul class="pagination">
                <?php
                $total_no_of_pages = ceil($total_no_of_records / $records_per_page);
                $current_page = 1;
                if (isset($_GET["page_no"])) {
                    $current_page = $_GET["page_no"];
                }

                for ($i = 1; $i <= $total_no_of_pages; $i++) {
                    if ($i == $current_page) {
                        echo "<li><a href='" . $self . "?page_no=" . $i . "' style='color:green;text-decoration:none'>" . $i . "</a></li>";
                    } else {
                        echo "<li><a href='" . $self . "?page_no=" . $i . "'>" . $i . "</a></li>";
                    }
                }
                ?>
            </ul>
            <?php
        }
    }

}