<?php

namespace App\Http\Controllers\SM;

use App\Http\Controllers\Controller;
use App\Models\SM\Application;
use App\Models\SM\Fnction;
use App\Models\SM\Permission;
use App\Models\SM\Role;
use Illuminate\Http\Request;
use stdClass;

class SecurityController extends Controller
{
    public function apps()
    {
        return Application::select('name', 'code')->get();
    }

    public function permissions()
    {
        return Permission::select('name', 'id as code')->get();
    }

    public function fnctions()
    {
        return Fnction::select('name as label', 'code', 'id')
            ->whereAppCode(config('canteen.app_code'))->with('permissions')->get()
            ->map(function ($item) {
                $fn = new stdClass;
                $fn->children = $item->permissions->map(function ($per) {
                    $permission = new stdClass;
                    $permission->label = $per->name;
                    $permission->data = $per->pivot->id;
                    $permission->key = $per->pivot->id;
                    return $permission;
                });
                $fn->label = $item->label;
                $fn->key = $item->code;
                $fn->data = $item->code;
                return $fn;
            });
    }
    public function index()
    {
        $apps           = $this->apps();
        $permissions    = $this->permissions();
        $fnctions       = $this->fnctions();
        return [
            'apps'          => $apps,
            'permissions'   => $permissions,
            'fnctions'      => $fnctions
        ];
    }

    public function roles(){
        return Role::whereAppCode(config('canteen.app_code'))->select('name','id AS code')->get();
    }

    public function userModule(){
        return [
            'roles' => $this->roles()
        ];
    }

    public function fncModule(){
        return [
            'permissions' => $this->permissions()
        ];
    }

    public function roleModule(){
        return [
            'fnctions'  => $this->fnctions()
        ];
    }
}
