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

class Auth {

	public $CI;

    public function __construct ()
    {
        $this->CI = & get_instance();
    }

    public function is_valid_user($username='',$password='')
    {
    	$query = $this->CI->db->get_where('user',array('username'=>$username,'password'=>$password));
    	
    	if($query->num_rows()==1)
    	{
    		return TRUE;
    	}
    	return FALSE;
    }

    public function authorize_user($username)
    {
    	$query = $this->CI->db->get_where('user',array('username'=>$username));

    	$this->CI->session->set_userdata('user',$query->row());
    }

    public function unauthorize_user()
    {
    	$this->CI->session->unset_userdata('user');
    	$this->CI->session->sess_destroy();
    	redirect(base_url(''));
    }


    public function user()
    {
    	return ($this->CI->session->userdata('user')!==NULL)?$this->CI->session->userdata('user'):FALSE;
    }

    public function allowed_page_access($page,$user_role=NULL)
    {
        if($this->user()) {
            $user_role = ($user_role!=NULL)? $user_role : $this->user()->role_ID;
        }

        if($user_role=='1') { return TRUE; }

        if($this->CI->input->is_ajax_request()) { return TRUE; }

        if(isset($page) && is_string($page)){
            $page = $this->CI->db->select('*')
                                ->where('page_url',$page)
                                ->get('page')->row();
        }

    	if(isset($page) && in_array( $user_role, explode(',',$page->allowed_roles) ) ){
    		return TRUE;
    	}
    	return FALSE;
    }

    public function userFullName()
    {
        return $this->user()->f_name." ".$this->user()->l_name;
    }
}