<?php

class UsersController extends AppController{
	
	var $name = 'users';
	var $components = array('Uploader.Uploader');
	
	function beforeFilter(){
		parent::beforeFilter();
		
		$this->Auth->allow('register', 'getTopUser');
	}
	
	function index() {
		$this->User->id = $this->Session->read('Auth.User.id');
		$user = $this->User->read();
		
		if (!empty($this->data)) {
			$this->data['User']['id'] = $user['User']['id'];
			$this->User->set($this->data);
			
    		//Si el fichero es correcto.
 			if ($this->User->validates(array('fieldList' => array('avatar')))) {
				//Sube el fichero.
 				$this->Uploader->uploadDir = 'files/uploads/avatares/';
           		if ($data = $this->Uploader->upload('avatar', array('overwrite' => true, 'name' => $this->User->id))){
											
					//Actualizar datos del registro.
					$this->User->saveField('avatar', $data['name']);
					$this->Session->write('Auth.User.avatar', $data['name']);
					
					$this->Session->setFlash('La imagen se guardó correctamente.');
					$this->redirect(array('controller' => 'users', 'action' => 'index'));
				} else {
					//No se pudo subir el fichero.
					$this->Session->setFlash('Lo sentimos, no se pudo guardar la imagen.');
				}	
			}
        }
        
        $this->set('user', $user);
	}
	
	/**
	 * Registra una nuevo usuario.
	 */
	function register() {
		if (!empty($this->data)) {
			$this->User->create();
			if ($this->User->save($this->data)) {
				$this->Session->setFlash('You have successfully registered your account.');
				$this->redirect(array('controller' => 'users', 'action' => 'login'));
			} else {
				$this->Session->setFlash('Lo siento, no se pudo registar.');
			}
		}
	}
	
	/**
	 * Abre sesión de usuario.
	 */
	function login() {
		if ($this->Session->read('Auth.User')) {
			$this->Session->setFlash('Ya está loguado!');
			$this->redirect(array('controller' => 'users', 'action' => 'index'));
		}
	}       
	
	
	/**
	 * Cierra sesión de usuario.
	 */
	function logout() {
		$this->Session->setFlash('Hasta la próxima!');
		$this->redirect($this->Auth->logout());
	}
	
	function getTopUser(){
		$this->autoRender = false;
		return $this->User->find('all', array('fields'=> array('username', 'avatar', 'points'), 'order' => 'points DESC', 'limit' => 5));
	}
}

?>