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


class Admin_model extends MY_Model
{
	protected $table_name = 'tbladmin';
	protected $id_name = 'admin_id';
	
	function __construct()
	{
		parent::__construct();
	}
	
	function check_login($login_name, $password)
	{
		$hash_password = md5($password);
		$query = "SELECT * FROM tbladmin WHERE  login_name = ? AND  passwd = ?";
		$result = $this->db->query($query, array($login_name, $hash_password));
		if($result->num_rows() == 1){
			return $result->row(0);
		}else
		{
			return null;
		}
	}
	
	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_admins($data)
	{
		$sql="SELECT * FROM ".$this->table_name;
		if ($data['keyword'])
		{
			$sql.=" WHERE (phone LIKE '%".$data['keyword']."%' OR login_name LIKE '%".$data['keyword']."%' OR full_name LIKE '%".$data['keyword']."%') ";
		}
		
		$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_admins($data)
	{
		$sql="SELECT COUNT(".$this->id_name.") AS total FROM ".$this->table_name;
		if (isset($data['keyword']))
		{
			$sql.=" WHERE (login_name LIKE '%".$data['keyword']."%' OR full_name LIKE '%".$data['keyword']."%') ";
		}
		$query = $this->db->query($sql);
		$result = $query->row_array();
		return $result['total'];
	}
	
	function check_password($admin_id, $passwd)
	{
		$hash_passwd = md5($passwd);
		$sql = "SELECT * FROM ".$this->table_name." WHERE admin_id = ? AND  passwd = ?";
		$result = $this->db->query($sql, array($admin_id, $hash_passwd));
		if($result->num_rows() == 1){
			return true;
		}else
		{
			return false;
		}
		
	}
	
	function get_roles()
	{
		$sql = "SELECT * FROM tbladminrole";
		$query = $this->db->query($sql);
		$result = $query->result_array();
		return $result;
	}
}