<?php

class Rbac extends Cf_Controller
{
    private $roles;

    public function __construct()
    {
        parent::__construct();

        setCurrentApplication('rbac');

        $this->load->library('ion_auth');
        $this->load->model('rbac_model');
        $this->roles = $this->ion_auth->get_roles();
        array_walk($this->roles, function (&$item) {
            $item = $item['id'];
        });
    }

    /**
     * @rbacName View settings page
     * @rbacGroup Role base access control
     * @rbacAlias rbac.index
     */
    public function index()
    {
        $data = [
            'title' => $this->lang->line('mission_portal_title') . ' - ' . 'Role based access control',
            'roles' => $this->roles,
        ];
        $this->template->load('template', 'rbac/index', $data);
    }

    /**
     * @rbacName Edit role permissions
     * @rbacGroup Role base access control
     * @rbacAlias rbac.edit
     */
    public function edit($role)
    {
        $role = rawurldecode($role);
        if (!in_array($role, $this->roles)) {
            show_404();
        }

        if ($this->input->method(true) == 'POST') {
            $data = $this->input->post('permissions');
            $this->rbac_model->assignPermissions($role, $data);
            redirect('settings/rbac/edit/' . $role, 'refresh');
            exit();
        }

        $permissionList = $this->rbac_model->getPermissionList('application');
        $rolePermissions = $this->rbac_model->getRolePermissions($role);

        $this->template->load('template', 'rbac/edit', [
            'roles' => $this->roles,
            'permissions' => $permissionList,
            'rolePermissions' => $rolePermissions,
            'role' => $role,
            'title' => $this->lang->line('mission_portal_title') . ' - ' . 'Edit ' . $role . ' role permissions',
        ]);
    }
}
