<?php

class Rbac extends Cf_Controller
{
    private $roles;

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

        setCurrentApplication('rbac');

        $this->load->helper('form');
        $this->load->library('ion_auth');
        $this->load->model('rbac_model');
        $this->load->model('settings_rest_model');
        $this->settings_rest_model->setRestClient($this->getRestClient());
        $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()
    {
        if ($this->input->method(true) == 'POST') {
            $this->saveHostFiltering();
            redirect('settings/rbac', 'refresh');
            exit();
        }

        try {
            $rbacEnabled = (bool) $this->settings_rest_model->app_settings_get_item('rbacEnabled');
        } catch (Exception $e) {
            show_error($e->getMessage());
        }

        $data = [
            'title' => $this->lang->line('mission_portal_title') . ' - ' . 'Role based access control',
            'roles' => $this->roles,
            'rbacEnabled' => $rbacEnabled,
            'canEditHostFiltering' => isActionAllowed('settings.manage'),
            'message' => $this->session->flashdata('message'),
        ];
        $this->template->load('template', 'rbac/index', $data);
    }

    /**
     * Host filtering (database level RBAC) used to live on the preferences page,
     * so it keeps being guarded by the preferences permission.
     */
    private function saveHostFiltering()
    {
        if (!isActionAllowed('settings.manage')) {
            redirect('auth/permission_deny', 'refresh');
            exit();
        }

        try {
            $response = $this->settings_rest_model->updateData(['rbacEnabled' => (bool) $this->input->post('rbac')]);
            $message = empty($response['success'])
                ? [
                    'content' => 'Could not save your settings.',
                    'type' => 'alert-error',
                ]
                : [
                    'content' => 'Data saved successfully.',
                    'type' => 'alert-success',
                ];
        } catch (Exception $e) {
            log_message(log_level_for_exception($e), 'Could not save RBAC setting:: ' . $e->getMessage());
            $message = [
                'content' => 'Could not save your settings. ' . $e->getMessage(),
                'type' => 'alert-error',
            ];
        }

        $this->session->set_flashdata('message', $message);
    }

    /**
     * @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',
        ]);
    }
}
