<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Cardlog extends MX_Controller
{
	const TOKENPW = 'violet';
	
	public function __construct() 
	{
		parent::__construct();
		$this->load->helper('cookie');
	}
	
	public function index ()
	{
            
		$admin_info = $this->session->userdata('adminInfo');
		if ($admin_info)
		{
			$data['content'] = $this->get_cardlogs();
			$this->load->view('cardlog/index', $data);
		}else
		{
			$this->load->view ( 'login');
		}
	}
	
	public function get_cardlogs()
	{
		$this->load->helper('pagging');
		$this->load->model('cardlog_model');
		$data['current_page'] = $this->uri->segment(4, 1);
		$data['itemsoptions'] = array(10, 25, 50, 100);
		$data['perpage'] = 10;
		$data['keyword'] = "";
		$data['sorting_order'] = "sorting_desc";
        $data['sorting_field'] = "created_time";
		if ($this->input->post('sorting_order')) {
			if ($this->input->post('sorting_order') != "sorting")
			{
				$data['sorting_order'] = $this->input->post('sorting_order');
				$data['sorting_field'] = $this->input->post('sorting_field'); 
			}
		}
		if ($this->input->post('items')) 
		{
			$data['perpage'] = $this->input->post('items');
		}
		if ($this->input->post('keyword')) {
            $data['keyword'] = $this->input->post('keyword');
        }
		$data['start'] = ($data['current_page'] - 1) * $data['perpage'];
		$data['total'] = $this->cardlog_model->get_total_cardlogs($data);
		$cls = $this->cardlog_model->get_cardlogs($data);
		$cardlogs = array();
		foreach($cls as $cl):
			$id = $cl['us_id'];
			$username = $this->get_username($id);
			$servicename = $this->get_servicename($cl['service_id']);
			$cl['username'] = $username;
			$cl['servicename'] = $servicename;
			array_push($cardlogs, $cl);
		endforeach;
		$data['cardlogs'] = $cardlogs;
		$data['paging_url'] = base_url() . "admin/card_log/trang/";
		$data['num_links'] = 2;
		$data['paging'] = pagging($data);
		if ($this->input->is_ajax_request())
		{
			return $this->load->view('cardlog/listview', $data);
		}
		return $this->load->view('cardlog/listview', $data, true);
	}
	
	private function get_username($us_id)
	{
		$src = 'violet';
		$token = md5($us_id.self::TOKENPW);
		$this->load->model('user_model');
		$data = $this->user_model->get_user_info($src, $us_id, $token);
		if (strlen($data) > 0){
			$arr_users = explode("&", $data);
			$str_username = $arr_users[1];
			$arr_username = explode("=", $str_username);
			return $arr_username[1];
		}else
		{
			return "";
		}

	}
	
	private function get_servicename($service_id)
	{
		$this->load->model('webservice_model');
		$service = $this->webservice_model->search_by_id($service_id);
		return $service['service_name'];
	}
	
}