<?php

namespace Sargilla\Flatlab4\Controllers;

use Illuminate\Support\Arr;
use Yajra\DataTables\DataTables;
use Spatie\Permission\Models\Role;
use Artdarek\Toastr\Facades\Toastr;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;

class UserController extends Controller {

    protected string $userModel;

    public function __construct() {

        $this->middleware(['auth', 'isAdmin']);
        $this->userModel = config('auth.providers.users.model');

    }

    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 = ($this->userModel)::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($id) {
        $user = ($this->userModel)::findOrFail($id);
        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($id) {
        $user = ($this->userModel)::findOrFail($id);
        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(($this->userModel)::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);
    }

}
