<?php

namespace App\Http\Controllers\Assets\Settings;

use App\Events\BulkUpdates;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Role;
use Spatie\Permission\Models\Permission;
use App\Models\AssetHistory;
use App\Models\PermissionCategory;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use Exception;

class AccessLevelsController extends Controller
{


    public function index()
    {
        $roles = Role::where('name', '!=', 'Super Admin')->where('name', '!=', 'Super User')->where('name', '!=', 'Research User')->get();
        $permissions = Permission::where('name', '!=', 'Purge Assets')->orderBy('name')->get();
        $permissionCategories = PermissionCategory::with('permissions')->orderBY('order')->get();


        return view('settings.manage-userrole', compact('roles', 'permissions', 'permissionCategories'));
    }

    public function store()
    {
        $roles = Role::where('name', '!=', 'Administrator')->where('name', '!=', 'Super Admin')->where('name', '!=', 'Super User')->where('name', '!=', 'Research User')->get();
        $permissions = Permission::where('name', '!=', 'Purge Assets')->get();

        foreach ($roles as $role) {
            foreach ($permissions as $permission) {
                $role->revokePermissionTo($permission);

                if (request(str_replace(' ', '_', $role->name) . '-' . str_replace(' ', '_', $permission->name))) {
                    $role->givePermissionTo($permission);
                }
            }
        }

        return redirect('manage-userrole')->with('message', __('message.access_level_updated'));
    }

    public function create()
    {
        $this->validate(request(), ['access_role' => 'required | unique:user_types,name']);

        Role::create(['name' => request('access_role'), 'is_admin' => 1]);

        $description = __('history.RoleCreated', [
            'roleName' => request('access_role'),
        ]);

        $assetHistory = [
            'user_id' => Auth::id(),
            'action' => 'role_created',
            'description' => $description,
            'created_at'  => Carbon::now()->format('Y-m-d H:i:s'),
            'updated_at'  => Carbon::now()->format('Y-m-d H:i:s'),
        ];

        event(new BulkUpdates($assetHistory));

        return redirect('manage-userrole')->with('message', __('message.access_role_created'));
    }

    public function add()
    {
        $this->validate(request(), ['access_level' => 'required | unique:permissions,name']);
        Permission::create(['name' => request('access_level'), 'guard_name' => 'web', 'permission_category_id' => request('group'), 'order' => request('order')]);
        $role = Role::where('name', 'Administrator')->first();
        $superAdminRole = Role::where('name', 'Super Admin')->first();
        $superUserRole = Role::where('name', 'Super User')->first();
        $role->givePermissionTo(request('access_level'));
        $superAdminRole->givePermissionTo(request('access_level'));
        $superUserRole->givePermissionTo(request('access_level'));

        $description = __('history.AccessLevelCreated', [
            'accessLevelName' => request('access_level'),
        ]);

        $assetHistory = [
            'user_id' => Auth::id(),
            'action' => 'accesslevel_created',
            'description' => $description,
            'created_at'  => Carbon::now()->format('Y-m-d H:i:s'),
            'updated_at'  => Carbon::now()->format('Y-m-d H:i:s'),
        ];

        event(new BulkUpdates($assetHistory));

        return redirect('manage-userrole')->with('message', 'Access Level created successfully');
    }

    public function delete()
    {
        $role = Role::find(request('role'));
        if (count($role->users)) {
            return response()->json('error');
        }
        $role->delete();
        return response()->json("Deactivated Successfully");
    }

    /**
     * Create new permission group
     */
    public function permissionGroupStore()
    {
        $this->validate(request(), ['group_name' => 'required | unique:permission_categories,name', 'group_order' => 'required']);
        PermissionCategory::create([
            'name'  => request('group_name'),
            'description'  => request('group_desc'),
            'order'  => request('group_order'),
        ]);

        return redirect('manage-userrole')->with('message', 'Permission Group created successfully');
    }
}
