<?php

/*
 * *************************************************
 * Copyright (C) 2021 Earworks.                    *
 * Codeigniter Project Template Modification       *
 * Please contact our email for more information : *
 * contact@earworks.co.id                          *
 * *************************************************
 */

defined('BASEPATH') OR exit('No direct script access allowed');
if (!function_exists('create_pagination')) {

    /**
     * Custom Pagination
     * @param array $query_pagination from query_pagination()
     * @param array $config antoher config
     * @return Object $CI->pagination
     */
    function create_pagination($query_pagination) {

        $CI = ancillary_object();
        $default_config = [
            'per_page' => isset($query_pagination['per_page']) ? $query_pagination['per_page'] : 20,
            'uri_segment' => isset($query_pagination['uri_segment']) ? $query_pagination['uri_segment'] : 3,
            'attributes' => [
                'rel' => false
            ],
            'display_pages' => true,
            'full_tag_open' => '<ul class="pagination">',
            'full_tag_close' => '</ul>',
            'next_link' => '>',
            'next_tag_open' => '<li class="next">',
            'next_tag_close' => '</li>',
            'next_tag_open_disabled' => '<li class="next disabled">',
            'next_tag_close_disabled' => '</li>',
            'prev_link' => '<',
            'prev_tag_open' => '<li class="previous">',
            'prev_tag_close' => '</li>',
            'prev_tag_open_disabled' => '<li class="previous disabled">',
            'prev_tag_close_disabled' => '</li>',
            'first_link' => '<<',
            'first_tag_open' => '<li class="first">',
            'first_tag_close' => '</li>',
            'first_tag_open_disabled' => '<li class="first disabled">',
            'first_tag_close_disabled' => '</li>',
            'last_link' => '>>',
            'last_tag_open' => '<li class="last">',
            'last_tag_close' => '</li>',
            'last_tag_open_disabled' => '<li class="last disabled">',
            'last_tag_close_disabled' => '</li>',
            'num_tag_open' => '<li>',
            'num_tag_close' => '</li>',
            'cur_tag_open' => '<li class="disabled"><a href="javascript:void(0)">',
            'cur_tag_close' => '</a></li>',
            'total_rows' => isset($query_pagination['total_row']) ? $query_pagination['total_row'] : null,
            'per_page' => isset($query_pagination['per_page']) ? $query_pagination['per_page'] : null,
            'base_url' => isset($query_pagination['base_url']) ? $query_pagination['base_url'] : null,
            'data_page_attr' => 'data-pager',
            'use_page_numbers' => true,
            'num_links' => 2,
            'reuse_query_string' => true
        ];
//        if (!$new_config['per_page']) {
//            $new_config['per_page'] = 20;
//        }
        $CI->load->library('pagination');
        $CI->pagination->initialize($default_config);
        return $CI->pagination;
    }

}
if (!function_exists('query_pagination')) {

    /**
     * Pagination Data
     * @param Object $query from Model::get_dbo()
     * @param type $config for pagination config, required: per_page', 'pages', 'order', 'keyword', 'search_field
     * @return array
     */
    function query_pagination($query, $config = []) {
        check_config_data($config);
        if ($config['keyword'] && !is_array($config['keyword'])) {
            $query->where(function($sub_query) use ($config) {
                foreach ($config['search_field'] as $field) {
                    $words = explode(' ', trim($config['keyword']));
                    foreach ($words as $word) {
                        $sub_query->orWhere($field, 'like', "%{$word}%");
                    }
                }
            });
        } elseif (is_array($config['keyword']) && !empty($config['keyword'])) {
            $query->where(function($sub_query) use ($config) {
                foreach ($config['keyword'] as $field => $keyword) {
                    $words = explode(' ', trim($keyword));
                    foreach ($words as $word) {
                        $sub_query->where($field, 'like', "%{$word}%");
                    }
                }
            });
        }
        $order_func = 'oldest';
        $order = $config['order'];
        if (strpos($config['order'], '-') !== false) {
            $order = substr($config['order'], 1, strlen($config['order']));
            $order_func = 'latest';
        }
        $query->$order_func($order);
        $total_row = $query->count();
        $pages = ( $config['pages'] * $config['per_page']) - $config['per_page'];
        if ($config['pages'] > ceil($total_row / $config['per_page']) && $total_row > 0) {
            $url_parts = explode('/', uri_string());
            if (isset($url_parts[$config['uri_segment'] - 1])) {
                unset($url_parts[$config['uri_segment'] - 1]);
            }
            $url_new = implode('/', $url_parts);
            redirect(base_url($url_new) . url_query());
        }
        $data = $query->skip($pages)->take($config['per_page'])->get();


//        echo $pages;
//        exit;
        $no = $config['pages'] > 1 ? $pages + 1 : 1;

        return array_merge($config, [
            'data' => $data,
            'total_row' => $total_row,
            'no' => $no
        ]);
    }

}
if (!function_exists('check_config_data')) {

    function check_config_data($config) {
        foreach (['per_page', 'pages', 'order', 'keyword', 'search_field'] as $required) {
            if (!array_key_exists($required, $config)) {
                show_error('required config (' . $required . ') for running query_pagination function', 500);
            }
        }
    }

}