<?php

class Gateway extends CI_Controller {

    private $response;
    private $table;
    private $column_order;
    private $column_search;
    private $request;

    public function __construct(){
        parent::__construct();
        $this->load->database();
        $this->response = array(
            'draw' => 0,
            'recordsTotal' => 0,
            'recordsFiltered' => 0,
            'data' => array()
        );
        $this->table = $this->db->dbprefix."gateways";
        $this->request = $this->input->post(null, true);
        $this->column_order = array(
            0 => "name",
            1 => "slug",
            2 => "charge",
            3 => "resellbizkey",
        );
        $this->column_search = array(
            "name",
            "slug",
            "instruction"
        );
    }

    public function index() {
        if($this->input->is_ajax_request() && $this->session->has_userdata('logged')) {
            $bindings = array();
            $where = $this->filter($bindings);
            $limit = $this->limit();
            $order = $this->order();
            $select = " SELECT * ";
            $count = " SELECT COUNT(*) as count ";
            $from = " FROM `".$this->table."` ";

            $data_sql = $this->aclClean($select.$from.$where.$order.$limit);
            $total_sql = $this->aclClean($count.$from);
            $filter_sql = $this->aclClean($count.$from.$where);

            $data_result = !empty($bindings) ? $this->db->query($data_sql, $bindings) : $this->db->query($data_sql);
            $data_result = $data_result ? $data_result->result() : array();
            $total_result = $this->db->query($total_sql);
            $total_result = $total_result ? $total_result->row(0) : array();
            $filter_result = !empty($bindings) ? $this->db->query($filter_sql, $bindings) : $this->db->query($filter_sql);
            $filter_result = $filter_result ? $filter_result->row(0) : array();

            if(!empty($data_result) && !empty($total_result) && !empty($filter_result) ) {

                $rows = array();
                foreach ($data_result as $gateway) {
                    $row = array();
                    $actions = array();

                    $actions[] = '<a href="'.base_url('lbadmin/gateway/edit/'.$gateway->slug).'" data-toggle="tooltip" data-placement="bottom" title="Edit '.$gateway->name.'" class="btn btn-acl-table btn-primary"><i class="acl-icon acl-icon-zoom acl-icon-edit-alt"></i></a>';
                    $actions[] = '<a href="'.base_url('lbadmin/gateway/delete/'.$gateway->slug).'" data-toggle="tooltip" data-placement="bottom" title="Remove '.$gateway->name.'" acl-name="'.$gateway->name.'" class="btn btn-acl-table btn-danger acl-remove-gateway"><i class="acl-icon acl-icon-zoom acl-icon-trash-5"></i></a>';

                    $row[] = xss_clean($gateway->name);
                    $row[] = base_url('/payment/'.$gateway->slug);
                    $row[] = xss_clean($gateway->charge);
                    $row[] = xss_clean($gateway->resellbizkey);
                    $row[] = implode(' ', $actions);
                    $rows[] = $row;
                }

                $this->response['data'] = $rows;
                $this->response['draw'] = intval($this->request['draw']);
                $this->response['recordsTotal'] = intval($total_result->count);
                $this->response['recordsFiltered'] = intval($filter_result->count);
            }
        }

        $this->sendResponse();
    }

    private function limit ( )
    {
        $limit = '';
        if ( isset($this->request['start']) && $this->request['length'] != -1 ) {
            $limit = " LIMIT ".intval($this->request['start']).", ".intval($this->request['length']);
        }

        return $limit;
    }

    private function order ()
    {
        $order = '';

        if ( isset($this->request['order']) && count($this->request['order']) ) {
            $orderBy = array();
            for ( $i=0, $ien=count($this->request['order']) ; $i<$ien ; $i++ ) {

                $columnIdx = intval($this->request['order'][$i]['column']);
                $requestColumn = $this->request['columns'][$columnIdx];

                if(array_key_exists($requestColumn['data'], $this->column_order)){
                    if ( $requestColumn['orderable'] == 'true' ) {
                        $dir = $this->request['order'][$i]['dir'] === 'asc' ?
                            'ASC' :
                            'DESC';

                        $orderBy[] = ' `'.$this->column_order[$requestColumn['data']].'` '.$dir;
                    }
                }
            }

            $order = count($orderBy)>0?' ORDER BY '.implode(', ', $orderBy).' ':'';
        }

        return $order;
    }

    private function filter ( &$bindings )
    {
        $where = array();

        if(isset($this->request['search']['value'])) {
            foreach ( $this->column_search as $search) {
                array_push($where, ' `'.$search.'` LIKE ? ');
                $bindings[] = '%'.$this->request['search']['value'].'%';
            }
        }

        return count($where)>0?(
            ' WHERE ' . implode(' OR ', $where) . ' '
        ):'';
    }
    private function aclClean($query) {
        return preg_replace('/\s+/', ' ', $query);
    }

    private function sendResponse(){
        header('Content-Type: application/json');
        echo json_encode($this->response);
        exit;
    }
}