<?php

namespace App\Http\Controllers\Role;

use App\Http\Controllers\Controller;
use App\Models\Log as LogModel;
use App\Utils\ArrayUtils;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use App\Http\Resources\RolesResource;

class RolesController extends Controller
{
    public function __construct(Request $request)
    {
        $this->log = new LogModel([
            'module' => 'role',
            'action' => $request->getMethod(),
            'target_type' => 'role',
        ]);
    }

    public function index(Request $request)
    {
        $roles = Role::query()->with('permissions')->where('id', '<>', 1)->get()->toArray();
        $routes = include(resource_path('lang/zh-CN/permission.php'));
        $allPermissions = Permission::query()->get()->toArray();
        $allPermissions = ArrayUtils::index($allPermissions, 'name');
        foreach ($roles as &$role) {
            $permissions = [];
            foreach ($role['permissions'] as $item) {
                $permissions[] = [
                    'id' => $allPermissions[$item['name']]['id'],
                    'name' => $routes[$item['name']]['name'],
                ];
            }
            $role['permissions'] = $permissions;
        }

        return RolesResource::collection($roles);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:191|unique:roles,name',
        ]);
        if ($validator->fails()) {
            $this->setValidatorFailResponse($validator->getMessageBag()->getMessages());

            return response($this->res, $this->res['httpCode']);
        }
        $role = new Role();
        $role->name = $request->name;
        $role->save();
        $this->setAfterUpdate($role->name);
        $this->addLog($role->id, 'add');

        return new RolesResource($role);
    }

    public function addPermissions($id, Request $request)
    {
        $role = Role::query()->findOrFail($id);
        $permissions = Permission::query()->findOrFail($request->permissionIds);
        $role->syncPermissions($permissions);
        $this->setAfterUpdate($permissions->toArray());
        $this->addLog($id, 'set', 'permission');

        return response($this->res, $this->res['httpCode']);
    }

    public function show($id)
    {
        return new RolesResource(Role::query()->find($id));
    }

    public function update($id, Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => ['required', 'string', 'max:191', Rule::unique('roles')->ignore($id),]
        ]);
        if ($validator->fails()) {
            $this->setValidatorFailResponse($validator->getMessageBag()->getMessages());

            return response($this->res, $this->res['httpCode']);
        }
        $role = Role::query()->find($id);
        $this->setBeforeUpdate($role->name);
        $role->name = $request->name;
        $role->save();
        $this->setAfterUpdate($role->name);
        $this->addLog($id, 'name');

        return new RolesResource($role);
    }
}
