<?php

namespace Sigma\Flatlab\Controllers;

use App\Models\User;
use Illuminate\Support\Arr;
use Yajra\Datatables\Datatables;
use Spatie\Permission\Models\Role;
use Sargilla\Toastr\Facades\Toastr;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;

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() {
        request()->validate( [
            'name'=>'required|max:120',
            'email'=>'required|email|unique:users',
            'password'=>'required|min:6|confirmed'
        ]);
        request()->merge(['password' => bcrypt(request()->password)]);
        $user = User::create(request()->except('roles', 'password_confirmation'));
        $user->roles()->sync(Arr::pluck(request()->roles, 'id'));
        return response("Se creó el usuario $user->name correctamente!");
    }

    public function show($id) {
        return redirect('flatlab::users');
    }

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

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

        if (request()->has('roles')) {
            $user->roles()->sync(Arr::pluck(request()->roles, 'id'));  //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
        }
        return response("Se editó el usuario $user->name correctamente!");

    }

    public function destroy(User $user) {
        if ($user->id == 1 ) {
            return response()->json('No puedes borrar este usuario!', 401);
        }
        $user->delete();
        return response("Se borró el usuario $user->name correctamente!");
    }

    public function getUsers()
    {
        if (!request()->ajax()) {
            return redirect()->route('usuarios.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){
                $query = $query->load('roles');
                return view('flatlab::users.acciones', compact('query'))->render();
            })
            ->rawColumns(['link','acciones'])
            ->make(true);
    }

}
