<?php

declare(strict_types=1);

namespace App\Http\Controllers\Backend;

use App\User;
use App\Http\Controllers\Controller;
use App\Http\Requests\RoleRequest;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\RedirectResponse;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use App\Helpers\AuditTrailHelper;

class RolesController extends Controller
{
    public function index(): Renderable
    {
        $this->checkAuthorization(auth()->user(), ['role.view']);
        session()->put('redirect_url', route('admin.roles.index'));

        $pageInfo = [
            'title' => 'List Roles',
            'sub_title' => 'List All User Roles',
            'path' => url()->current()
        ];
        return view('backend.pages.roles.index', [
            'roles' => Role::all(), 'pageInfo' => $pageInfo
        ]);
    }

    public function create(): Renderable
    {
        $this->checkAuthorization(auth()->user(), ['role.create']);
        
        $pageInfo = [
            'title' => 'Create Roles',
            'sub_title' => 'Create User Roles',
            'path' => url()->current()
        ];
        
        return view('backend.pages.roles.create', [
            'all_permissions' => Permission::all(),
            'permission_groups' => User::getpermissionGroups(),
            'pageInfo' => $pageInfo
        ]);
    }

    public function store(RoleRequest $request): RedirectResponse
    {
        $this->checkAuthorization(auth()->user(), ['role.create']);

        // Process Data.
        $role = Role::create(['name' => $request->name, 'guard_name' => 'admin']);

        // $role = DB::table('roles')->where('name', $request->name)->first();
        $permissions = $request->input('permissions');

        if (!empty($permissions)) {
            $role->syncPermissions($permissions);
        }

        AuditTrailHelper::AddAuditTrail('Insert', 'Created New Role (' . $request->name . ') in the Role Table');
        session()->flash('success', 'Role has been created.');
        return redirect()->back();
    }

    public function edit(int $id): Renderable|RedirectResponse
    {
        $this->checkAuthorization(auth()->user(), ['role.edit']);

        $role = Role::findById($id, 'admin');
        if (!$role) {
            session()->flash('error', 'Role not found.');
            return back();
        }

        $pageInfo = [
            'title' => 'Create Roles',
            'sub_title' => 'Create User Roles',
            'path' => url()->current()
        ];

        return view('backend.pages.roles.edit', [
            'role' => $role,
            'all_permissions' => Permission::all(),
            'permission_groups' => User::getpermissionGroups(),
            'pageInfo' => $pageInfo
        ]);
    }

    public function update(RoleRequest $request, int $id): RedirectResponse
    {
        $this->checkAuthorization(auth()->user(), ['role.edit']);

        $role = Role::findById($id, 'admin');
        if (!$role) {
            session()->flash('error', 'Role not found.');
            return back();
        }

        $permissions = $request->input('permissions');
        if (!empty($permissions)) {
            $role->name = $request->name;
            $role->save();
            $role->syncPermissions($permissions);
        }

        AuditTrailHelper::AddAuditTrail('Update', 'Updated Role Data (' . $request->name . ') in the Role Table');
        session()->flash('success', 'Role has been updated.');
        return redirect()->back();
    }

    public function destroy(int $id): RedirectResponse
    {
        $this->checkAuthorization(auth()->user(), ['role.delete']);

        $role = Role::findById($id, 'admin');
        if (!$role) {
            session()->flash('error', 'Role not found.');
            return back();
        }
        AuditTrailHelper::AddAuditTrail('Delete', 'Deleted Role (' . $role->name . ')');

        $role->delete();
        session()->flash('success', 'Role has been deleted.');
        return redirect()->back();
    }
}