<?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->active) {
					SystemMessage::factory()
						->title(_('Account NOT Activated'))
						->type('warning')
						->body(_('Your account cannot been activated, please contact us.'));

				} elseif ($ao->activate_code() == $this->request->post('code')) {
					$ao->verified = TRUE;
					$ao->save();

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

				HTTP::redirect('welcome');
			}

		} 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'))->set('email',$this->request->query('email')));
	}

	/**
	 * 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()) {
			$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 = 'Please activate your account for '.$co->name();
			$email->deliver();

			SystemMessage::factory()
				->title(_('Account Registered'))
				->type('info')
				->body(_('Please check your email for more instructions!'));

			Session::instance()->set('activate',$ao);
			HTTP::redirect('login/activate/'.$ao->id);
		}

		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*60;

		// 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()) {
				$token = $ao->token($token_expire,'account','user:resetpassword',2);

				if ($token) {
					$co = Company::instance();

					// 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',$token)
						->set('TOKEN_EXPIRE_MIN',$token_expire)
						->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 = '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;
	}
}
?>
