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

class User_auth
{
	public function __construct()
	{
		$this->ci =& get_instance();
		if (!session_id()) {
	      session_start();
	    }
	}

	public function is_logged_in()
	{
		return ($this->ci->session->userdata('user_id'))? TRUE : FALSE;
	}

	public function login($email,$password)
	{
		$user = $this->ci->users_model->get_user_by_login($email,md5($password));
		if($user)
		{
			$this->ci->users_model->update_last_login($user['user_id']);
			$this->ci->session->set_userdata(array(
				'user_id'	        => $user['user_id']
				,'user_role_id'	    => $user['user_role_id']
				,'user_facebook_id'	=> $user['user_facebook_id']
				,'user_email'	    => $user['user_email']
				,'user_fullname'    => $user['user_fullname']
			));
			$result['success']      = TRUE;
			$result['redirect_url'] = site_url('home');
			$result['message']      = lang('login_success');
		}
		else
		{
			$result['success']   = FALSE;
			$result['message']   = lang('wrong_credentials');
		}
		return $result;
	}

	public function email_login($email)
	{
		$user = $this->ci->users_model->get_user_by_email($email);
		if($user)
		{
			$this->ci->users_model->update_last_login($user['user_id']);
			$this->ci->session->set_userdata(array(
				'user_id'	        => $user['user_id']
				,'user_role_id'	    => $user['user_role_id']
				,'user_facebook_id'	=> $user['user_facebook_id']
				,'user_email'	    => $user['user_email']
				,'user_fullname'    => $user['user_fullname']
			));
		}
	}

	public function facebook_login($facebook_id)
	{
		$user = $this->ci->users_model->get_user_by_facebook_id($facebook_id);
		if($user)
		{
			$this->ci->users_model->update_last_login($user['user_id']);
			$this->ci->session->set_userdata(array(
				'user_id'	        => $user['user_id']
				,'user_role_id'	    => $user['user_role_id']
				,'user_facebook_id'	=> $user['user_facebook_id']
				,'user_email'	    => $user['user_email']
				,'user_fullname'    => $user['user_fullname']
			));
		}
	}

	public function logout()
	{
		$this->ci->session->unset_userdata(array(
			'user_id'	        => ''
			,'user_role_id'	    => ''
			,'user_facebook_id'	=> ''
			,'user_email'	    => ''
			,'user_fullname'    => ''
		));
		$this->ci->facebook->destroySession();
		// $this->ci->session->sess_destroy();
		return TRUE;
	}

	public function register($data)
	{
	    $this->ci->db->query($this->ci->db->insert_string('users', $data));
	    $result['success']   = TRUE;
		$result['message']   = lang('confirmation_mail_sent');
	    return $result;
	}
}

/* End of file User_auth.php */
/* Location: ./application/libraries/User_auth.php */