<?php
namespace app\controllers;

use app\models\User;
use lithium\security\Auth;
use lithium\util\String;
use li3_access\security\Access;
use li3_flash_message\extensions\storage\FlashMessage;
use lithium\action\Dispatcher;

class AdminController extends \lithium\action\Controller {
	public function index()
	{
		$limit = 5;
		$page = $this->request->page ?: 1;
		//$order = array('created' => 'DESC');
		$total = User::count();
		$users = User::all(compact('limit','page'));
		$this->render(array('layout' => 'admin', 'data' =>  compact('users', 'total', 'page', 'limit')));	
	}

	public function users()
	{
		$users = User::all();
		$this->render(array('layout' => 'admin', 'data' => compact('users')));
		//Should have paginate for when there is more users.
	}

	
	//This is basically admins version of signup
	public function addUser()
	{
		$sucsess = false;

		//If the request isn't empty
		if($this->request->data) {
			//Does admins data need to be validated?
			$user = User::Create($this->request->data);
			$sucsess = $user->save();
		}
		if ($sucsess) {
			return $this->redirect('Users');
		}
	
		FlashMessage::set($user->name . "was added sucessfully.");
	}

	public function editUser($username = NULL)
	{
		if ($username != NULL)
		{
			$user = User::find('first', array('conditions' => compact('username')));
		
			if($this->request->data)
			{
				$user->set($this->request->data);
				if ($user->save(null, array('validate' => false)))
				{
					FlashMessage::write('User updated sucsessfully');
					$this->redirect('Admin::index');
				}
				else
				{
					FlashMessage::set('There was an error');
					$this->redirect('Admin::index');

				}
			}
			else
			{
				//unset($user->password);
				return compact('user');
			}
		}
	}

	public function removeUser($username)
	{
		/*
		//Form data needs to have $username and $confirm = true to do the delete.
		if($this->request->data)
		{
			//If the user has confirmed the deletion of the user.
			if($this->request->data->confirm)
			{ */
				$user = User::find('first', array('conditions' => compact('username')));
				$user->delete();
				FlashMessage::set("User was deleted sucsessfully.");
				$this->redirect('Admin');	
			//}
		}
		/*else
		{
			//Render the form
			$this->render(array('layout' => 'form', 'data' => compact('users')));

		}*/
	//}
}
?>