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

/**
 * This class provides login capability
 *
 * @package    lnApp
 * @category   Controllers
 * @author     Deon George
 * @copyright  (c) 2009-2013 Deon George
 * @license    http://dev.leenooks.net/license.html
 * @also       [logout]
 */
class lnApp_Controller_Login extends Controller_TemplateDefault {
	protected $auth_required = FALSE;

	/**
	 * Activate an account so that it can login and use the site
	 */
	public function action_activate() {
		if ($this->request->post()) {
			$ao = ORM::factory('Account',array('id'=>$this->request->param('id'),'email'=>$this->request->post('email')));

			if ($ao->loaded()) {
				if ($ao->activated())
					HTTP::redirect('login');

				elseif ($ao->activate_code() == $this->request->post('code')) {
					$go = ORM::factory('Group',array('name'=>'Registered Users'));

					$ago = ORM::factory('Account_Group',array('account_id'=>$ao,'group_id'=>$go));

					if (! $ago->loaded()) {
						$ago->account_id=$ao;
						$ago->group_id=$go;
					}
					$ago->active = TRUE;
					$ago->save();

					SystemMessage::factory()
						->title(_('Account Activated'))
						->type('info')
						->body(_('Your account has been activated.'));
				}
			}

		} elseif (! $this->request->param('id'))
			HTTP::redirect('login/activate_resend');

		Block::factory()
			->title('Activate account')
			->title_icon('fa-wrench')
			->type('form-horizontal')
			->body(View::factory('login/activate')->set('o',Session::instance()->get_once('activate')));
	}

	/**
	 * Send the account activation code to the email address, validating the email address
	 */
	public function action_activate_resend() {
		if ($this->request->post('email')) {
			$ao = ORM::factory('Account',array('email'=>$this->request->post('email')));

			if ($ao->loaded()) {
				if ($ao->activated())
					HTTP::redirect('login');
				else {
					$co = Company::instance();

					// Send our email with the token
					$email = Email::factory('login_activate')
						->set('SITE',URL::base(TRUE,TRUE))
						->set('SITE_ADMIN',$co->admin()->name())
						->set('CODE',$ao->activate_code())
						->set('EMAIL',$ao->email)
						->set('ID',$ao->id)
						->set('USER_NAME',$ao->name());

					$email->to = array('email'=>array($ao->email=>$ao->name()));
					$email->from = array('email'=>array($co->admin()->email=>$co->admin()->name()));
					$email->subject = 'Activation Code for '.$co->name();
					$email->deliver();

					// Log the password reset
					$ao->log('Activation code sent');
					Session::instance()->set('activate',$ao);
				}
			}

			HTTP::redirect('login/activate/'.$ao->id);

		} else {
			Block::factory()
				->title('Activate account')
				->title_icon('fa-wrench')
				->type('form-horizontal')
				->body(View::factory('login/activate_resend'));
		}
	}

	/**
	 * Login to the site
	 */
	public function action_index() {
		$output = '';

		if (! array_key_exists('auth',Kohana::modules()))
			throw HTTP_Exception::factory(501,'Auth not enabled.');

		// If user already signed-in
		if (Auth::instance()->logged_in())
			HTTP::redirect(URL::link('user','welcome/index'));

		// If there is a post and $_POST is not empty
		if ($this->request->post()) {
			// If the post data validates using the rules setup in the user model
			if (Auth::instance()->login($this->request->post('username'),$this->request->post('password'))) {
				// Redirect to the user account
				if ($redir = Session::instance()->get('afterlogin')) {
					Session::instance()->delete('afterlogin');
					HTTP::redirect($redir);

				} else
					HTTP::redirect(URL::link('user','welcome/index'));

			} else {
				SystemMessage::factory()
					->title(_('Invalid username or password'))
					->type('danger')
					->body(_('The username or password was invalid.'));
			}
		}

		if (array_key_exists('oauth',Kohana::modules()))
			$oauthlogin = is_null($x=Session::instance()->get_once('login-no-oauth',NULL)) ? TRUE : ! $x;
		else
			$oauthlogin = FALSE;

		$output .= View::factory('login')
			->set('oauth',$oauthlogin);

		Style::factory()
			->type('file')
			->data('media/css/auth-buttons.css');

		if ($oauthlogin)
			foreach (ORM::factory('Oauth')->list_active() as $oo)
				$output .= $oo->plugin()->html();

		$this->template->content = $output;
		$this->template->shownavbar = FALSE;
	}

	/**
	 * Method redirect when authenticated user doesnt have access to the url
	 */
	public function action_noaccess() {
		SystemMessage::factory()
			->title(_('No access to requested resource'))
			->type('danger')
			->body(_('You do not have access to the requested resource, please contact your administrator.'));
	}

	/**
	 * Register for an account on the site
	 */
	public function action_register() {
		$ao = ORM::factory('Account',$this->request->param('id'));

		if ($this->request->post() AND $ao->values($this->request->post())->changed() AND (! $this->save($ao)))
				$ao->reload()->values($this->request->post());

		if ($ao->loaded())
			HTTP::redirect('login');

		Block::factory()
			->type('form-horizontal')
			->title('Register Account')
			->title_icon('fa-edit')
			->body(View::factory('account/user/edit')->set('o',$ao));
	}

	/**
	 * Enable user password reset
	 */
	public function action_reset() {
		// Minutes to keep our token
		$token_expire = 15;
		$co = Company::instance();

		// If user already signed-in
		if (Auth::instance()->logged_in())
			HTTP::redirect('welcome/index');

		// If the user posted their details to reset their password
		if ($this->request->post()) {
			// If the username is correct, create a method token
			if ($ao=ORM::factory('Account',array('email'=>$this->request->post('username'))) AND $ao->loaded()) {
				$mmto = ORM::factory('Module_Method_Token')
					->method(array('account','user:resetpassword'))
					->account($ao)
					->uses(2)
					->expire(time()+$token_expire*60);

				if ($mmto->generate()) {
					// Send our email with the token
					$email = Email::factory('login_reset')
						->set('SITE',URL::base(TRUE,TRUE))
						->set('SITE_ADMIN',$co->admin()->name())
						->set('TOKEN',$mmto->token)
						->set('TOKEN_EXPIRE_MIN',$token_expire)
						->set('USER_NAME',$mmto->account->name());

					$email->to = array('email'=>array($mmto->account->email=>$mmto->account->name()));
					$email->from = array('email'=>array($co->admin()->email=>$co->admin()->name()));
					$email->subject = 'Login Reset Token for '.$co->name();
					$email->deliver();

					// Log the password reset
					$ao->log('Password reset token sent');
				}

			// Redirect to our password reset, the Auth will validate the token.
			} elseif ($this->request->post('token')) {
				HTTP::redirect(URL::link('user','account/resetpassword?token='.$this->request->post('token')));
			}

			// Show our token screen even if the email was invalid.
			if ($this->request->post('username'))
				$output = View::factory('login/reset_sent');
			else
				HTTP::redirect('login');

		} else {
			$output = View::factory('login/reset');
		}

		$this->template->content = $output;
		$this->template->shownavbar = FALSE;
	}
}
?>