<?php defined('SYSPATH') or die('No direct script access.');

class Member_Group_Model extends Model {

	function __construct(){ 
		
			$this->db = new Database();  

	}
	
	public function grouplist(){
		return $this->db->get('member_group');

	}
	public function selectGroup($fieldName="",$selected_id=false){
		$groupList	=	$this->grouplist()->result_array();
		$html		=	"<select name='$fieldName'>";
		foreach ($groupList as $group){
			$html	.=	"<option value='$group->group_id' ".($group->group_id==$selected_id?"selected":":").">".$group->group_name;
		}
		return $html.=	"</select>";
	}
	public function checklist($name){
		$this->db->orwhere(array('group_name' => $name));
		return $this->db->get('member_group');

	}
	
	public function getone($id){
		$this->db->where('group_id', $id);
		return $this->db->get('member_group');

	}
	
	function add($data){
		return $this->db->insert('member_group',$data);

	}
	
	function delete($id_list){
		$this->db->in('group_id',$id_list);
		$this->db->delete('menu_group');
		$this->db->in('group_id',$id_list);
		return $this->db->delete('member_group');
	}
	
	function edit($data){
		$this->db->where('group_id', $data['group_id']);
		return $this->db->update('member_group', $data);

	}
	//新建关系
	function insert_acl_group($data){
		return $this->db->insert("membergroup_acl",$data);
	}
	//取得用户组的资源
	function getGroupAcl($group_Id){
		return $this->db->where("group_id",$group_Id)
		->get("membergroup_acl")
		->result_array();
	}
	function getAcl($group_id){
		$this->db->select("a.acl_value,a.acl_children")
		->from("acl as a")
		->join("membergroup_acl as m_c","m_c.acl_id","a.acl_id")
		->join("member_group as m_g","m_g.group_id","m_c.group_id")
		->where("m_g.group_id",$group_id);
		$result	=	$this->db->get();
		$acl	=	$result->result_array();
		if(count($acl)>0){
			foreach ($acl as $tmp){
				$aclArray[]	=	$tmp->acl_value;
				if($tmp->acl_children!=""){
					list($control)	=	explode("+",$tmp->acl_value);
					$arrAcl		=	explode("|",$tmp->acl_children);
					if(count($arrAcl)>=1){
						foreach ($arrAcl as $cil){
							$aclArray[]	=	$control."+".$cil;
						}
					}
				}
			}
		}
		else{
			$aclArray	=	array();
		}
		return $aclArray;
	}
	function cache(){
		//取得用户组
		$groups	=	$this->db->get("member_group")->result_array();
		foreach ($groups	as $tmp){
			$acls	=	$this->getAcl($tmp->group_id);
			$cacheAcl[$tmp->group_id]	=	$acls;
			$cacheAcl[$tmp->group_name]	=	$acls;
		}
		if(file_put_contents(DATADIR."cache/membergroupacl.php","<?php \r\n return ".var_export($cacheAcl,true)."?>")){
			return true;
		}
		else{
			return false;
		}
	}
	//删除以前的关系表
	function delete_acl_group($group_id=false){
		$this->db->in("group_id",$group_id);
		return $this->db->delete("membergroup_acl");
	}
	
} // End Auth Role Model 