<?php

namespace App\Http\Controllers\Admins\Users;

use App\Http\Controllers\Admins\Users\UserAccessController;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class RoleController extends Controller
{

    private $uac;
    function __construct(UserAccessController $uac)
    {
        $this->uac = $uac;
    }
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        // call table user with pagination
        $datas = Role::latest()->paginate(10);

        return view('pages.admins.roles.index', compact('datas'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $permissions = Permission::all()->groupBy('group_name');
        return view('pages.admins.roles.create', compact('permissions'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        // validation
        $rules = array(
            'name'  => 'required',
            'email' => 'required|email',
            'password'  => 'required|min:8'
        );
        $validator = Validator::make($request->all(), $rules);

        // check validation
        if ($validator->fails()) {
            return Redirect::to('admin/roles/create')
                ->withErrors($validator)
                ->withInput($request->except('password'));
        } else {
            // create new account
            $user = Role::create([
                'name' => $request->name,
                'email' => $request->email,
                'password' => bcrypt($request->password),
            ]);

            // Create role for user
            $role = Role::findOrFail($request->role); // Pengunjung
            $user->assignRole($role);

            // Create Session message
            Session::flash('roles-message', [
                'type' => 'success',
                'msg' => 'Anda berhasil menambahkan data!'
            ]);

            return Redirect::to('admin/roles');
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        // get data from user
        $user = User::findOrFail($id);
        $roles = Role::latest()->get();

        // call view pages
        return view('pages.admins.roles.edit', compact('user', 'roles'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        // validation
        $rules = array(
            'name'     => 'required|min:5',
            'password'   => 'required|min:8',
        );
        $validator = Validator::make($request->all(), $rules);

        // process the login
        if ($validator->fails()) {
            return Redirect::to('admin/roles/edit/' . $id)
                ->withErrors($validator)
                ->withInput($request->except('password'));
        } else {
            // create new account
            $user = User::findOrFail($id);
            if (!$user) {
                // Create Session message
                Session::flash('roles-message', [
                    'type' => 'warning',
                    'msg' => 'Data pengguna tidak ditemukan!'
                ]);

                return Redirect::to('admin/roles');
            }
            $user->update([
                'name' => $request->name,
                'password' => bcrypt($request->password),
            ]);

            // Update role for user
            $user->removeRole($user->roles[0]->name);
            $user->assignRole($request->role);

            // Create Session message
            Session::flash('roles-message', [
                'type' => 'success',
                'msg' => 'Anda berhasil mengubah data!'
            ]);

            return Redirect::to('admin/roles');
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }

    public function refreshRoutes()
    {
        try {
            $result = $this->uac->generate();

            if ($result['status' == 'success']) {
                return redirect()->back()->with('success', $result['message']);
            } else {
                return redirect()->back()->with('error', $result['message']);
            }
        } catch (\Throwable $th) {
            //throw $th;
        }
        return redirect()->back();
    }
}
