<?php

namespace App\Controllers\Security;

use App\Controllers\BaseController;
use App\Models\RoleModel;
use App\Models\PermissionModel;

class Role extends BaseController
{
    public function index()
    {
        $roleModel = new RoleModel();
        $permModel = new PermissionModel();

        // Ambil semua role
        $roles = $roleModel->findAll();

        // Attach permission ke tiap role
        foreach ($roles as &$r) {
            $r['permissions'] = $permModel->getByRole($r['id']);
        }

        // Group permission untuk form
        $permissions = $permModel->grouped();

        return view('security/role/index', [
            'roles' => $roles,
            'permissions' => $permissions
        ]);
    }

    public function store()
    {
        $roleModel = new RoleModel();

        $roleId = $roleModel->insert([
            'name' => $this->request->getPost('name'),
            'description' => $this->request->getPost('description'),
            'is_system' => 0
        ], true);

        $permissions = $this->request->getPost('permissions') ?? [];
        $roleModel->syncPermissions($roleId, $permissions);

        return redirect()->back()->with('success', 'Role berhasil dibuat');
    }

}
