<?php namespace App\Modules\Backend\Users\Controllers;

use Auth, Input, Redirect, View, DB, Datatables, Validator, Innfile, Hash, Alert, Acl;
use \App\Modules\Backend\Users\Models\User;
use \App\Modules\Backend\Usergroups\Models\UserGroup;


class UserController extends \BaseController {

	/**
	 * Constructor
	 */
	public function __construct() {

        View::share('active_module', 'users');
        View::share('userGroupsOptions', UserGroup::allOptions());
    }

	/**
	 * Ejecutado cuando acceden a /admin/users
	 * @return string Muestra la pantalla con todos los usuarios registrados en el sistema.
	 */
	public function getIndex()
	{
		Acl::canOrFail('users', 'view');
		return View::make('users::index');
	}

	/**
	 * Genera el Json con todos los usuarios.
	 * @return string Json con datos para datatables
	 */
	public function getTablaAjax()
	{
		Acl::canOrFail('users', 'view');
		$datas 		= User::select('username', 'name', 'email', 'id', 'active');
		//$options 	= ;
		return Datatables::of($datas)
				->edit_column('username', '{{ $username }} <input type="hidden" class="id" value="{{ $id }}" >')
				->edit_column('name', '<span class="text_val">{{ $name }}</span>')
				->edit_column('id',   '@if($active==1)<span class="label label-success">'.trans('users::label.active').'</span> @else <span class="label label-danger">'.trans('users::label.inactive').'</span>@endif')
				->make();
	}



	/**
	 * Elimina a un usuario.
	 * @return  View vista
	 */
	public function deleteEdit($id)
	{
		Acl::canOrFail('users', 'delete');
		$user = User::find($id);
		if(!$user)
		{
			Alert::message(trans('dashboard::message.element_not_found'), 'danger');
			return Redirect::to('admin/users');
		}
		if($user->id == Auth::user()->id)
		{
			Alert::message(trans('users::message.cant_delete_yourself'), 'danger');
			return Redirect::to('admin/users');
		}

		$user->delete();
		Alert::message(trans('users::message.deleted_user'));
		return Redirect::to('admin/users');
	}

	/**
	 * Muestra el formulario para cambiar la contraseña del usuario actual
	 * @return string Vista
	 */
	public function getChangeMyPassword()
	{
		Acl::canOrFail('users', 'change-my-password');
		$user = Auth::user();
		return View::make('users::change-password')
				->with('user', $user)
				->with('myPassword', true)
				->with("formOptions", array("role" 	=> "form", 
					"id" 		=> "frmPrincipal", 
					"class" 	=> "form-horizontal",
					"method" 	=> "PUT",
					"url" 		=> url("admin/users/change-my-password/")));
	}


	/**
	 * Valida y cambia el password del usuario actual
	 * @return string Vista
	 */
	public function putChangeMyPassword()
	{
		Acl::canOrFail('users', 'change-my-password');
		$user = Auth::user();
		$data = Input::all();
		$rules = array(
            'password'  => 'required|min:6|confirmed',
        );

        $validator = Validator::make($data, $rules);

        if($validator->passes())
        {
        	$user->password = Hash::make($data['password']);
        	

        	if($user->save())
        	{
        		Alert::message(trans('users::message.password_changed'), 'success');
        		return Redirect::to('admin/users/change-my-password/');
        	}
        	else {
        		Alert::message(trans('dashboard::message.error'), 'danger');
        		return Redirect::to('admin/users/change-my-password/')
        			->withInput();
        	}
        }
        else
        {
        	Alert::message($validator, 'danger');
        	return Redirect::to('admin/users/change-my-password/')
        			->withInput();
        }

	}

	/**
	 * Muestra el formulario para cambiar la contraseña
	 * @return string Vista
	 */
	public function getChangePassword($id)
	{
		Acl::canOrFail('users', 'change-password');
		$user = User::find($id);
		if(!$user)
		{
			Alert::message(trans('dashboard::message.element_not_found'), 'danger');
			return Redirect::to('admin/users');
		}
		return View::make('users::change-password')
				->with('user', $user)
				->with("formOptions", array("role" 	=> "form", 
					"id" 		=> "frmPrincipal", 
					"class" 	=> "form-horizontal",
					"method" 	=> "PUT",
					"url" 		=> url("admin/users/change-password/".$user->id)));
	}

	/**
	 * Valida y crea un nuevo usuario
	 * @return string Vista
	 */
	public function putChangePassword($id)
	{
		Acl::canOrFail('users', 'change-password');
		$user = User::find($id);
		if(!$user)
		{
			Alert::message(trans('dashboard::message.element_not_found'), 'danger');
			return Redirect::to('admin/users');
		}
		$data = Input::all();
		$rules = array(
            'password'  => 'required|min:6|confirmed',
        );

        $validator = Validator::make($data, $rules);

        if($validator->passes())
        {
        	$user->password = Hash::make($data['password']);
        	

        	if($user->save())
        	{
        		Alert::message(trans('users::message.password_changed'), 'success');
        		return Redirect::to('admin/users/edit/'.$user->id);
        	}
        	else {
        		Alert::message(trans('dashboard::message.error'), 'danger');
        		return Redirect::to('admin/users/change-password/'.$user->id)
        			->withInput();
        	}
        }
        else
        {
        	Alert::message($validator, 'danger');
        	return Redirect::to('admin/users/change-password/'.$user->id)
        			->withInput();
        }

	}


	/**
	 * Muestra el formulario para editar el perfil del usuario en curso
	 * @return string Vista
	 */
	public function getMyProfile()
	{
		Acl::canOrFail('users', 'view-my-profile');
		$user = Auth::user();
		return View::make('users::user')
				->with('title', $user->name)
				->with('user', $user)
				->with('myProfile', true)
				->with("formOptions", array("role" 	=> "form", 
					"id" 		=> "frmPrincipal", 
					"class" 	=> "form-horizontal",
					"method" 	=> "PUT",
					"files"		=> true,
					"url" 		=> url("admin/users/my-profile/")));
	}

	/**
	 * Valida y edita el perfil del usuario actual
	 * @return string Vista
	 */
	public function putMyProfile()
	{
		Acl::canOrFail('users', 'update-my-profile');
		$user = Auth::user();
		$data = Input::all();
		$rules = array(
            'email'     => 'required|email|unique:users,email,'.$user->id,
            'avatar'  	=> 'mimes:jpeg,gif,png'
        );

        $validator = Validator::make($data, $rules);

        // Checamos si se envío un archivo y si este marco un error por el tamaño.
        if(Input::hasFile('avatar') && !Input::file("avatar")->isValid())
        {
        	Alert::message(trans('dashboard::message.file_overflow', array('file' => Input::file("avatar")->getClientOriginalName())), 'danger');
        	return Redirect::to('admin/users/my-profile')
        			->withInput();
        }
        else if($validator->passes())
        {
        	$user->fill($data);
        	if(Input::hasFile('avatar')) {
	    		$file 	= Input::file("avatar");
	    		$dir 	= "users-avatar/";
	    		$name 	= Innfile::getUniqueFileName($dir, $file->getClientOriginalName());

	    		if($file->move($dir, $name)) {
	    			$user->avatar = $dir.$name;
	    		}
	    		else {
	    			Alert::message(trans('dashboard::message.error'), 'danger');
	    			return Redirect::to('admin/users/my-profile')
	        			->withInput();
	    		}
        	}

        	if($user->save())
        	{
        		Alert::message(trans('users::message.edited_user'), 'success');
        		return Redirect::to('admin/users/my-profile');
        	}
        	else {
        		Alert::message(trans('dashboard::message.error'), 'danger');
        		return Redirect::to('admin/users/my-profile')
        			->withInput();
        	}
        }
        else
        {
        	Alert::message($validator, 'danger');
        	return Redirect::to('admin/users/my-profile')
        			->withInput();
        }

	}

	/**
	 * Muestra el formulario para editar un usuario
	 * @return string Vista
	 */
	public function getEdit($id)
	{
		Acl::canOrFail('users', 'view');
		$user = User::find($id);
		if(!$user)
		{
			Alert::message(trans('dashboard::message.element_not_found'), 'danger');
			return Redirect::to('admin/users');
		}
		return View::make('users::user')
				->with('title', $user->name)
				->with('user', $user)
				->with("formOptions", array("role" 	=> "form", 
					"id" 		=> "frmPrincipal", 
					"class" 	=> "form-horizontal",
					"method" 	=> "PUT",
					"files"		=> true,
					"url" 		=> "admin/users/edit/".$user->id));
	}

	/**
	 * Valida y edita un usuario
	 * @return string Vista
	 */
	public function putEdit($id)
	{
		Acl::canOrFail('users', 'update');
		$user = User::find($id);
		if(!$user)
		{
			Alert::message(trans('dashboard::message.element_not_found'), 'danger');
			return Redirect::to('admin/users');
		}
		$data = Input::all();
		$rules = array(
            'email'     => 'required|email|unique:users,email,'.$user->id,
            'avatar'  	=> 'mimes:jpeg,gif,png'
        );

        $validator = Validator::make($data, $rules);

        // Checamos si se envío un archivo y si este marco un error por el tamaño.
        if(!Input::has('non-photo') && Input::hasFile('avatar') && !Input::file("avatar")->isValid())
        {
        	Alert::message(trans('dashboard::message.file_overflow', array('file' => Input::file("avatar")->getClientOriginalName())), 'danger');
        	return Redirect::to('admin/users/edit/'.$user->id)
        			->withInput();
        }
        else if($validator->passes())
        {
        	$user->fill($data);
        	if(!Input::has('non-photo') && Input::hasFile('avatar')) {
	    		$file 	= Input::file("avatar");
	    		$dir 	= "users-avatar/";
	    		$name 	= Innfile::getUniqueFileName($dir, $file->getClientOriginalName());

	    		if($file->move($dir, $name)) {
	    			$user->avatar = $dir.$name;
	    		}
	    		else {
	    			Alert::message(trans('dashboard::message.error'), 'danger');
	    			return Redirect::to('admin/users/edit/'.$user->id)
	        			->withInput();
	    		}
        	}
        	else if(Input::has('non-photo'))
        		$user->avatar = '';

        	if($user->save())
        	{
        		Alert::message(trans('users::message.edited_user'), 'success');
        		return Redirect::to('admin/users/edit/'.$user->id);
        	}
        	else {
        		Alert::message(trans('dashboard::message.error'), 'danger');
        		return Redirect::to('admin/users/edit/'.$user->id)
        			->withInput();
        	}
        }
        else
        {
        	Alert::message($validator, 'danger');
        	return Redirect::to('admin/users/edit/'.$user->id)
        			->withInput();
        }

	}



	/**
	 * Muestra el formulario para crear un nuevo usuario
	 * @return string Vista
	 */
	public function getAdd()
	{
		Acl::canOrFail('users', 'create');
		$user = new User();
		return View::make('users::user')
				->with('title', trans('users::label.add_user'))
				->with('user', $user)
				->with("formOptions", array("role" 	=> "form", 
					"id" 		=> "frmPrincipal", 
					"class" 	=> "form-horizontal",
					"method" 	=> "POST",
					"files"		=> true,
					"url" 		=> url("admin/users/add/")));
	}

	/**
	 * Valida y crea un nuevo usuario
	 * @return string Vista
	 */
	public function postAdd()
	{
		Acl::canOrFail('users', 'create');
		$data = Input::all();
		$rules = array(
            'username'  => 'required|unique:users',
            'email'     => 'required|email|unique:users',
            'password'  => 'required|min:6|confirmed',
            'avatar'  	=> 'mimes:jpeg,gif,png'
        );

        $validator = Validator::make($data, $rules);

        // Checamos si se envío un archivo y si este marco un error por el tamaño.
        if(Input::hasFile('avatar') && !Input::file("avatar")->isValid())
        {
        	Alert::message(trans('dashboard::message.file_overflow', array('file' => Input::file("avatar")->getClientOriginalName())), 'danger');
        	return Redirect::to('admin/users/add')
        			->withInput();
        }
        else if($validator->passes())
        {
        	$user = new User($data);
        	$user->password = Hash::make($data['password']);
        	$user->avatar = '';
        	if(Input::hasFile('avatar')) {
	    		$file 	= Input::file("avatar");
	    		$dir 	= "users-avatar/";
	    		$name 	= Innfile::getUniqueFileName($dir, $file->getClientOriginalName());

	    		if($file->move($dir, $name)) {
	    			$user->avatar = $dir.$name;
	    		}
	    		else {
	    			Alert::message(trans('dashboard::message.error'), 'danger');
	    			return Redirect::to('admin/users/add')
	        			->withInput();
	    		}
        	}

        	if($user->save())
        	{
        		Alert::message(trans('users::message.added_user'), 'success');
        		return Redirect::to('admin/users/edit/'.$user->id);
        	}
        	else {
        		Alert::message(trans('dashboard::message.error'), 'danger');
        		return Redirect::to('admin/users/add')
        			->withInput();
        	}
        }
        else
        {
        	Alert::message($validator, 'danger');
        	return Redirect::to('admin/users/add')
        			->withInput();
        }

	}
}