<?php
declare(strict_types=1);

namespace App\Controllers;

require_once BASE_PATH . '/app/helpers/permissions.php';

use App\Core\Controller;
use App\Models\RbacModel;

final class RbacController extends Controller
{
    public function index(): void
    {
        require_permission('rbac.view');

        $model = new RbacModel();

        $roles = $model->roles();
        $permissions = $model->permissions();
        $rolePermissionMap = [];

        foreach ($roles as $role) {
            $rolePermissionMap[(int) $role['id']] = $model->permissionsForRole((int) $role['id']);
        }

        $this->view('admin/rbac/index', [
            'roles' => $roles,
            'permissions' => $permissions,
            'rolePermissionMap' => $rolePermissionMap,
        ]);
    }

    public function editRolePermissions(): void
    {
        require_permission('rbac.manage');

        $roleId = (int) ($_GET['role_id'] ?? ($_POST['role_id'] ?? 0));
        if ($roleId <= 0) {
            redirect('admin/rbac');
        }

        $model = new RbacModel();
        $roles = $model->roles();
        $permissions = $model->permissions();

        $role = null;
        foreach ($roles as $r) {
            if ((int) $r['id'] === $roleId) {
                $role = $r;
                break;
            }
        }

        if (!$role) {
            redirect('admin/rbac');
        }

        if ($this->isPost()) {
            csrf_check();

            $permissionIds = array_map('intval', $_POST['permission_ids'] ?? []);
            $model->replaceRolePermissions($roleId, $permissionIds);

            audit_log('update_role_permissions', 'roles', $roleId, ['permission_ids' => $permissionIds]);
            flash('success', trans('permissions_updated_success'));
            redirect('admin/rbac');
        }

        $this->view('admin/rbac/edit_role', [
            'role' => $role,
            'permissions' => $permissions,
            'assigned' => $model->permissionsForRole($roleId),
        ]);
    }
}
