<?php

    function getPagination($db,$query, $debug = false)
    {
        $result = setPaginationData($_GET);
        $total = $db->query('select count(*) as count ' . $query['query'], $query['queryParams'])->row_array();
        $response['recordsTotal'] = (isset($total['count'])) ? (int)$total['count'] : 0;
        if ($result['orderByField'] != '' && $result['orderBy'] != '') {
            //$query['queryParams'][] = $result['orderByField'];
            //$query['query'] .= ' order by ? '.$result['orderBy'].' ';
            $query['query'] .= ' order by ' . $result['orderByField'] . ' ' . $result['orderBy'] . ' ';
        }
        $query['query'] .= ' limit ? offset ? ';
        $query['queryParams'][] = (int)$result['limit'];
        $query['queryParams'][] = (int)$result['offset'];
//        /p($query);
      //  DB::enableQueryLog();
        $response['data'] = $db->query('select ' . $query['select'] . ' ' . $query['query'], $query['queryParams'])->result_array();
       // p(DB::getQueryLog());
        $response['recordsFiltered'] = $response['recordsTotal'];//count($response['data']);
        $response['draw'] = $result['draw'];
        if ($debug) {
            p([$db->last_query(), $result, $response]);
        }
        return $response;
    }

    function setPaginationData($data)
    {
        $array['draw'] = isset($data['draw']) ? $data['draw'] : 0;
        $array['limit'] = isset($data['length']) ? $data['length'] : 10;
        $array['offset'] = isset($data['start']) ? $data['start'] : 0;
        $array['orderByField'] = '';
        $array['orderBy'] = '';
        if (isset($data['order'])) {
            for ($i = 0, $ien = count($data['order']); $i < $ien; $i++) {
                // Convert the column index into the column data property
                $columnIdx = intval($data['order'][$i]['column']);
                $requestColumn = $data['columns'][$columnIdx];
                $array['orderByField'] = isset($requestColumn['data']) ? $requestColumn['data'] : '';
                $array['orderBy'] = '';
                if ($requestColumn['orderable'] == 'true') {
                    $array['orderBy'] = $data['order'][$i]['dir'] === 'asc' ? 'ASC' : 'DESC';
                }
            }
        }
        return $array;
    }
