<?php

namespace Sargilla\FlatLab\Controllers;

use Auth;
use Session;
use App\User;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use Artdarek\Toastr\Facades\Toastr;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Controller;
use Spatie\Permission\Models\Permission;
use Yajra\Datatables\Facades\Datatables;

class UserController extends Controller {

    public function __construct() {

        $this->middleware(['auth', 'isAdmin']); 

    }

    public function index() {

        return view('flatlab::users.index');

    }

    public function create() {

        $roles = Role::get();

        return view('flatlab::users.create', ['roles'=>$roles]);

    }

    public function store() {

        $this->validate(request(), [
            'name'=>'required|max:120',
            'email'=>'required|email|unique:users',
            'password'=>'required|min:6|confirmed'
        ]);

        $user = User::create(request()->except('roles', 'password_confirmation')); 

        $user->roles()->sync(request()->roles);

        Toastr::success('Usuario Creado!');

        return redirect()->route('users.index');

    }

    public function show($id) {

        return redirect('flatlab::users'); 

    }

    public function edit(User $user) {
        
        $roles = Role::get();

        return view('flatlab::users.edit', compact('user', 'roles')); 

    }

    public function update(User $user) {
      
        $this->validate(request(), [
            'name'=>'required|max:120',
            'email'=>'required|email|unique:users,email,'.$user->id,
        ]);
        if(request('password')){
            $this->validate(request(), [
               'password'=>'required|min:6|confirmed'
            ]);
            $user->fill([
                'password' => Hash::make(request()->password)
            ])->save();
        } 

        $user->fill([
                'name' => request()->name,
                'email' => request()->email
            ])->save();

        if (request()->has('roles')) {        
            $user->roles()->sync(request()->roles);  //If one or more role is selected associate user to roles          
        } else {
            $user->roles()->detach(); //If no role is selected remove exisiting role associated to a user
        }

        Toastr::success('Usuario editado!');

        return redirect()->route('users.index');

    }

    public function destroy(User $user) {
        
        if ($user->id == 1 ) {
            return response()->json('No puedes borrar este rol!', 401);
        } 
   
        $user->delete();

        return response()->json('Usuario Borrado!');

    }

    public function getUsers()
    {
        if (!request()->ajax()) {
            return redirect()->route('permisos.index');
        }
        return Datatables::of(User::all())       
            ->editColumn('created_at',  function($query){
                return $query->created_at->format('d/m/Y');
            })
            ->addColumn('roles', function($query){
                return $query->roles()->pluck('name')->implode(' / ');
            })
            ->addColumn('acciones', function($query){
                return "<div class='acciones' data-id='$query->id' >                  
                    <button class='btn btn-xs btn-primary' 
                        data-action='editar' title='Editar'><i class='fa fa-pencil'></i></button>
                    <button class='btn btn-xs btn-danger btn-xs'
                        data-action='borrar' title='Borrar'><i class='fa fa-times'></i></button>
                </div>";
            })
            ->rawColumns(['acciones'])
            ->make(true);    
    }

}
