<?php
defined('BASEPATH') or exit('No direct script access allowed');

include_once APPPATH . 'core/Admin_Controller.php';

class Permissions extends Admin_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('rbac_m');
        $this->load->database();
        if (!$this->rbac_m->tables_ready()) {
            redirect(base_url('index.php/install/rbac'));
            return;
        }
        $this->require_permission('manage_permissions', 'view');
    }

    public function index()
    {
        $this->data['page_title'] = 'Role Permissions';
        $this->data['roles'] = $this->rbac_m->get_roles(false);
        $this->data['flash_success'] = $this->session->flashdata('success');
        $this->data['flash_error'] = $this->session->flashdata('error');
        $this->render_report('admin/permissions/index', $this->data);
    }

    public function edit($role_id = null)
    {
        $role = $this->rbac_m->get_role($role_id);
        if (!$role) {
            show_404();
            return;
        }

        $this->data['page_title'] = 'Permissions — ' . $role->name;
        $this->data['role'] = $role;
        $this->data['modules_grouped'] = $this->rbac_m->get_modules(true);
        $this->data['perm_map'] = $this->rbac_m->get_role_permissions_map($role->id);
        $this->data['flash_success'] = $this->session->flashdata('success');
        $this->data['flash_error'] = $this->session->flashdata('error');
        $this->render_report('admin/permissions/edit', $this->data);
    }

    public function save($role_id = null)
    {
        $role = $this->rbac_m->get_role($role_id);
        if (!$role) {
            show_404();
            return;
        }

        if (!empty($role->is_superadmin)) {
            // Super admin always has everything; refresh grant and exit
            $this->rbac_m->grant_all_permissions($role->id, true);
            $this->session->set_flashdata('success', 'Super Admin always has full access. Permissions refreshed.');
            redirect(base_url('index.php/permissions/edit/' . (int) $role_id));
            return;
        }

        $posted = $this->input->post('perm');
        if (!is_array($posted)) {
            $posted = array();
        }

        $this->rbac_m->save_role_permissions($role->id, $posted);
        $this->session->set_flashdata('success', 'Permissions saved for role: ' . $role->name);
        redirect(base_url('index.php/permissions/edit/' . (int) $role_id));
    }
}
