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

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

class UserGroupsController extends \BaseController {

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

        View::share('active_module', 'users');
    }

    /**
     * Muestra una tabla con todos los grupos de usuarios
     * @return View 
     */
    public function getIndex()
    {
        Acl::canOrFail('usergroups', 'view');
    	return View::make('usergroups::index');
    }

    /**
     * Genera el Json con todos los grupos de usuarios.
     * @return string Json con datos para datatables
     */
    public function getTablaAjax()
    {
        Acl::canOrFail('usergroups', 'view');
        $datas      = UserGroup::select('name', 'id');
        $options    = '{{ $name }} <input type="hidden" class="id" value="{{ $id }}" >';
        return Datatables::of($datas)
                ->edit_column('name', $options)
                ->make();
    }

    /**
     * Muestra el formulario para crear un nuevo grupo de usuarios
     * @return string Vista
     */
    public function getAdd()
    {
        Acl::canOrFail('usergroups', 'create');
        $group = new UserGroup();
        $modules = Dashboard::getModules();
        return View::make('usergroups::group')
                ->with('title', trans('usergroups::label.add_group'))
                ->with('group', $group)
                ->with('modules', $modules)
                ->with("formOptions", array("role"  => "form", 
                    "id"        => "frmPrincipal", 
                    "class"     => "form-horizontal",
                    "method"    => "POST",
                    "url"       => url("admin/usergroups/add")));
    }

    /**
     * Valida y crea un nuevo grupo de usuarios
     * @return string Vista
     */
    public function postAdd()
    {
        Acl::canOrFail('usergroups', 'create');
        $data = Input::all();
        $rules = array(
            'name'      => 'required|unique:user_groups'
        );

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

        // Validamos los datos recibidos.
        if($validator->passes())
        {
            $permissions = array();
            foreach ($data as $key => $value) {
                if(starts_with($key, 'action_'))
                {
                    $name   = substr($key, 7);
                    $aux    = explode('@', $name);
                    $permissions[] = array(
                                        'module' => $aux[0],
                                        'action' => $aux[1]
                                        );
                }
            }

            $group                  = new Usergroup($data);
            $group->permissions     = json_encode($permissions);


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

    }

     /**
     * Muestra el formulario para editar un grupo de usuarios
     * @return string Vista
     */
    public function getEdit($id)
    {
        Acl::canOrFail('usergroups', 'view');
        $group = UserGroup::find($id);
        if(!$group)
        {
            Alert::message(trans('dashboard::message.element_not_found'), 'danger');
            return Redirect::to('admin/usergroups');
        }
        $permissions = json_decode($group->permissions);
        foreach ($permissions as $permission) {
            Session::flash('action_'.$permission->module.'@'.$permission->action, true);
        }
        $modules = Dashboard::getModules();
        return View::make('usergroups::group')
                ->with('title', trans('usergroups::label.edit_group'))
                ->with('group', $group)
                ->with('modules', $modules)
                ->with("formOptions", array("role"  => "form", 
                    "id"        => "frmPrincipal", 
                    "class"     => "form-horizontal",
                    "method"    => "PUT",
                    "url"       => url("admin/usergroups/edit/".$group->id)));
    }

     /**
     * Valida y edita un grupo de usuarios
     * @return string Vista
     */
    public function putEdit($id)
    {
        Acl::canOrFail('usergroups', 'update');
        $group = UserGroup::find($id);
        if(!$group)
        {
            Alert::message(trans('dashboard::message.element_not_found'), 'danger');
            return Redirect::to('admin/usergroups');
        }
        $data = Input::all();
        $rules = array(
            'name'      => 'required|unique:user_groups,name,'.$group->id
        );

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

        // Validamos los datos recibidos.
        if($validator->passes())
        {
            $permissions = array();
            foreach ($data as $key => $value) {
                if(starts_with($key, 'action_'))
                {
                    $name   = substr($key, 7);
                    $aux    = explode('@', $name);
                    $permissions[] = array(
                                        'module' => $aux[0],
                                        'action' => $aux[1]
                                        );
                }
            }

            $group->fill($data);
            $group->permissions     = json_encode($permissions);


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

    }

    /**
     * Elimina a un grupo de usuario.
     * @return  View vista
     */
    public function deleteEdit($id)
    {
        Acl::canOrFail('usergroups', 'delete');
        $group = Usergroup::find($id);
        if(!$group)
        {
            Alert::message(trans('dashboard::message.element_not_found'), 'danger');
            return Redirect::to('admin/usergroups');
        }

        if($group->users()->count()>0)
        {
            Alert::message(trans('usergroups::message.usergroup_using'), 'danger');
            return Redirect::to('admin/usergroups/edit/'.$group->id);
        }

        $group->delete();
        Alert::message(trans('usergroups::message.deleted'));
        return Redirect::to('admin/usergroups');
    }
}