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

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

	public function action_index() {
		// If user already signed-in
		if (Auth::instance()->logged_in()!= 0) {
			// Redirect to the user account
			Request::current()->redirect('user/welcome');
		}

		// If there is a post and $_POST is not empty
		if ($_POST) {
			// Store our details in a session key
			Session::instance()->set(Kohana::config('auth.session_key'),$_POST['username']);
			Session::instance()->set('password',$_POST['password']);

			// If the post data validates using the rules setup in the user model
			if (Auth::instance()->login($_POST['username'],$_POST['password'])) {
				// Redirect to the user account
				if ($redir = Session::instance()->get('afterlogin')) {
					Session::instance()->delete('afterlogin');
					Request::current()->redirect($redir);
					
				} else
					Request::current()->redirect('user/welcome');

			} else {
				SystemMessage::add(array(
					'title'=>_('Invalid username or password'), 
					'type'=>'error',
					'body'=>_('The username or password was invalid.')
				));
			}
		}

		Block::add(array(
			'title'=>_('Login to server'),
			'body'=>View::factory('login'),
			'style'=>array('css/login.css'=>'screen'),
		));

		Script::add(array('type'=>'stdin','data'=>'
			$(document).ready(function() {
				$("#ajxbody").click(function() {$("#ajBODY").load("'.$this->request->uri().'/"); return false;});
			});'
		));
	}

	public function action_register() {
		// If user already signed-in
		if (Auth::instance()->logged_in()!= 0) {
			// Redirect to the user account
			Request::current()->redirect('welcome/index');
		}

		// Instantiate a new user
		$account = ORM::factory('account');

		// If there is a post and $_POST is not empty
		if ($_POST) {
			// Check Auth
			$status = $account->values($_POST)->check();

			if (! $status) {
				foreach ($account->validation()->errors('form/register') as $f => $r) {
					// $r[0] has our reason for validation failure
					switch ($r[0]) {
						// Generic validation reason
						default:
							SystemMessage::add(array(
								'title'=>_('Validation failed'), 
								'type'=>'error',
								'body'=>sprintf(_('The defaults on your submission were not valid for field %s (%s).'),$f,$r)
							));
					}
				}
			}

			$ido = ORM::factory('module')
				->where('name','=','account')
				->find();

			$account->id = $ido->record_id->next_id($ido->id);
			// Save the user details
			if ($account->save()) {}

		}

		SystemMessage::add(array(
			'title'=>_('Already have an account?'), 
			'type'=>'info',
			'body'=>_('If you already have an account, please login..')
		));

		Block::add(array(
			'title'=>_('Register'),
			'body'=>View::factory('register')
				->set('account',$account)
				->set('errors',$account->validation()->errors('form/register')),
		));

		$this->template->left = HTML::anchor('login','Login').'...';
	}

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

		// If user already signed-in
		if (Auth::instance()->logged_in()!= 0) {
			// Redirect to the user account
			Request::current()->redirect('welcome/index');
		}

		// If the user posted their details to reset their password
		if ($_POST) {
			// If the email address is correct, create a method token
			if (! empty($_POST['email']) AND ($ao=ORM::factory('account',array('email'=>$_POST['email']))) AND $ao->loaded()) {
				$mt = ORM::factory('module_method_token');

				// Find out our password reset method id
				// @todo move this to a more generic method, so that it can be called by other methods
				$mo = ORM::factory('module',array('name'=>'account'));
				$mmo = ORM::factory('module_method',array('name'=>'user_resetpassword','module_id'=>$mo->id));

				// Check to see if there is already a token, if so, do nothing.
				if ($mt->where('account_id','=',$ao->id)->and_where('method_id','=',$mmo->id)->find()) {
					if ($mt->loaded() AND ($mt->date_expire < time())) {
						$mt->delete();
						$mt->clear();
					}
				}

				if (! $mt->loaded()) {
					$mt->account_id = $ao->id;
					$mt->method_id = $mmo->id;
					$mt->date_expire = time() + $token_expire*60;
					$mt->token = md5(sprintf('%s:%s:%s',$mt->account_id,$mt->method_id,$mt->date_expire));
					$mt->save();

					// Send our email with the token
					// @todo Need to provide an option if Email_Template is not installed/activited.
					// @todo Need to provide an option if account_reset_password template doesnt exist.
					$et = Email_Template::instance('account_reset_password');
					$et->to = array('account'=>array($mt->account_id));
					$et->variables = array(
						'SITE'=>URL::base(TRUE,TRUE),
						'SITE_ADMIN'=>Config::sitename(),
						'SITE_NAME'=>Config::sitename(),
						'TOKEN'=>$mt->token,
						'TOKEN_EXPIRE_MIN'=>$token_expire,
						'USER_NAME'=>sprintf('%s %s',$mt->account->first_name,$mt->account->last_name),
					);
					$et->send();
				}

			// Redirect to our password reset, the Auth will validate the token.
			} elseif (! empty($_REQUEST['token'])) {
				Request::current()->redirect(sprintf('user/account/resetpassword?token=%s',$_REQUEST['token']));
			}

			// Show our token screen even if the email was invalid.
			if (isset($_POST['email']))
				Block::add(array(
					'title'=>_('Reset your password'),
					'body'=>View::factory('login_reset_sent'),
					'style'=>array('css/login.css'=>'screen'),
				));
			else
				Request::current()->redirect('login');

		} else {
			Block::add(array(
				'title'=>_('Reset your password'),
				'body'=>View::factory('login_reset'),
				'style'=>array('css/login.css'=>'screen'),
			));
		}
	}

	public function action_noaccess() {
		SystemMessage::add(array(
			'title'=>_('No access to requested resource'), 
			'type'=>'error',
			'body'=>_('You do not have access to the requested resource, please contact your administrator.')
		));
	}
}
?>