<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User_model extends MY_Model
{
	
	protected $table_name = 'tbluser';
	protected $id_name = 'us_id';

	function __construct()
	{
		parent::__construct();
		$this->vservices->setApiUrl($this->config->item('api_url'));
		$this->vservices->setConnection($this->curl);
	}
	
	function check_data($login_name)
	{
		$this->db->where('login_name', $login_name);
		$query = $this->db->get($this->table_name);
		return $query->num_rows();
	}
	
	function get_list_users($data)
	{
		$sql="SELECT * FROM ".$this->table_name;
		if ($data['keyword'])
		{
			$sql.=" WHERE (cellphone LIKE '%".$data['keyword']."%' OR collaborator LIKE '%".$data['keyword']."%' OR acc_balanced LIKE '%".$data['keyword']."%') ";
		}
		if ($data['status'] == 1){
			$sql.=" WHERE expire_date > NOW()";
		}
		if ($data['status'] == 2){
			$sql.=" WHERE expire_date < NOW()";
		}
		$order = "";
		if ($data['sorting_order'] != "sorting") {
			if($data['sorting_field'] != "status"){
				$sort = "DESC";
				if ($data['sorting_order'] == "sorting_asc")
					$sort = "ASC";
				$order = "ORDER BY " . $data['sorting_field'] . " " . $sort;
			}
		}
		return $this->db->query($sql." ".$order." LIMIT ".$data['start'].", ".$data['perpage']." ")->result_array();
	}

	function get_total_users($data)
	{
		$sql="SELECT COUNT(".$this->id_name.") AS total FROM ".$this->table_name;
		
		if ($data['status'] == 1){
			$sql.=" WHERE expire_date > NOW()";
		}
		if ($data['status'] == 2){
			$sql.=" WHERE expire_date < NOW()";
		}
		
		if (isset($data['keyword']))
		{
			if (strlen($data['keyword'])>0)
				$sql.=" WHERE (cellphone LIKE '%".$data['keyword']."%' OR collaborator LIKE '%".$data['keyword']."%' OR acc_balanced LIKE '%".$data['keyword']."%') ";
		}
		return $this->db->query($sql)->row_array()['total'];
	}
	
	function get_user_info($src, $us_id, $token)
	{
		$data = $this->vservices->actionExecute('getinfo', array('src' => $src, 'us_id' => $us_id, 'token'=>$token), 'user');
                return $data;
	}
}