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

/**
 * @package    PTA
 * @subpackage Auth
 * @category   Models
 * @author     Deon George
 * @copyright  (c) 2010 Deon George
 * @license    http://dev.leenooks.net/license.html
 */
class Model_Auth_UserDefault extends Model_Auth_User {
	protected $_table_names_plural = false;

	// Validation rules
	protected $_rules = array(
		'admin_name' => array(
			'not_empty'  => NULL,
			'min_length' => array(4),
			'max_length' => array(8),
		),
		'password' => array(
			'not_empty'  => NULL,
			'min_length' => array(5),
			'max_length' => array(16),
		),
		'password_confirm' => array(
			'matches_ifset'    => array('password'),
		),
	);

	// Columns to ignore
	protected $_ignored_columns = array('password_confirm');

	// Field labels
	protected $_labels = array(
		'admin_name'         => 'username',
		'email'            => 'email address',
		'password'         => 'password',
		'password_confirm' => 'password confirmation',
	);

	/**
	 * Validates login information from an array, and optionally redirects
	 * after a successful login.
	 *
	 * @param   array    values to check
	 * @param   string   URI or URL to redirect to
	 * @return  boolean
	 */
	public function login(array & $array, $redirect = FALSE) {
		$fieldname = 'admin_name';
		$array = Validate::factory($array)
			->label('admin_name', $this->_labels[$fieldname])
			->label('password', $this->_labels['password'])
			->filter(TRUE, 'trim')
			->filter('admin_name','strtoupper')
			->rules('admin_name', $this->_rules[$fieldname])
			->rules('password', $this->_rules['password']);

		// Get the remember login option
		$remember = isset($array['remember']);

		// Login starts out invalid
		$status = FALSE;

		if ($array->check())
		{
			// Attempt to load the user
			$this->where($fieldname, '=', $array['admin_name'])->find();

			if ($this->loaded() AND Auth::instance()->login($this, $array['password'], $remember))
			{
				if (is_string($redirect))
				{
					// Redirect after a successful login
					Request::instance()->redirect($redirect);
				}

				// Login is successful
				$status = TRUE;
			}
			else
			{
				$array->error('admin_name', 'invalid');
			}
		}

		return $status;
	}
}
?>
