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

/**
 * This class provides User with a TSM node functions
 *
 * @package    TSM Access Management
 * @category   Controllers/User
 * @author     Deon George
 * @copyright  (c) 2009-2013 Deon George
 * @license    http://dev.leenooks.net/license.html
 */
class Controller_User_Admin extends Controller_Admin {
	protected $secure_actions = array(
		'add'=>0,
		'view'=>0,
	);

	private function admin_name($i) {
		return sprintf('%s%02dA',$this->ao->id(),$i);
	}

	public function action_add() {
		$n = ORM::factory('ADMIN')->where('EMAIL_ADDRESS','=',$this->ao->email)->find_all();

		if ($n->count() >= $this->ao->max_admin) {
			SystemMessage::add(array(
				'title'=>_('Maximum admins created'),
				'type'=>'info',
				'body'=>_('Additional admins cannot be created for your account, you have already reached your maximum. If you really need more, please contact us.'),
			));

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

		if ($this->request->post()) {
			// Find a free name.
			for ($i=1;$i<=$n->count();$i++)
				if (! Object::in_array('ADMIN_NAME',$this->admin_name($i),$n->as_array()))	
					break;

			$ao = ORM::factory('ADMIN');
			$ao->ADMIN_NAME=$this->admin_name($i);
			$ao->CONTACT=$this->ao->name();
			$ao->EMAILADDRESS=$this->ao->email;
			$ao->values($x=Arr::merge(Kohana::$config->load('tsm')->admin_create,$this->request->post()));

			$this->save($ao);

			if ($ao->saved())
				#HTTP::redirect(URL::link('user','admin/view/'.$ao->ADMIN_NAME));
				HTTP::redirect(URL::link('user','welcome'));
		}

		Block::factory()
			->type('form-horizontal')
			->title('Register ADMIN')
			->title_icon('fa-graduation-cap')
			->body(View::factory('admin/user/add')->set('o',$this->ao));
	}
}
?>