<?php

namespace App\Http\Controllers\Permission;

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

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

    public function index(Request $request)
    {
        $permissions = $request->user()->getPermissionsViaRoles()->toArray();
        $permissions = ArrayUtils::index($permissions, 'name');
        $routes = include(resource_path('lang/zh-CN/permission.php'));
        $allowedPermissions = [];
        foreach ($routes as $route => $conf) {
            if (isset($permissions[$route])) {
                $conf['id'] = $permissions[$route]['id'];
                $allowedPermissions[] = $conf;
            }
        }
        $allowedPermissions = FormatUtils::formatTreeData($allowedPermissions, 0);

        return PermissionsResource::collection($allowedPermissions);
    }

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

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

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

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

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

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

        return new PermissionsResource($permission);
    }
}
