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

include_once APPPATH . 'core/Admin_Controller.php';

class Roles 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_roles', 'view');
    }

    public function index()
    {
        $roles = $this->rbac_m->get_roles(false);
        foreach ($roles as $role) {
            $role->user_count = $this->rbac_m->count_users_in_role($role->id);
        }
        $this->data['page_title'] = 'Roles';
        $this->data['roles'] = $roles;
        $this->data['flash_success'] = $this->session->flashdata('success');
        $this->data['flash_error'] = $this->session->flashdata('error');
        $this->render_report('admin/roles/index', $this->data);
    }

    public function create()
    {
        $this->data['page_title'] = 'Add Role';
        $this->data['role'] = null;
        $this->data['form_action'] = base_url('index.php/roles/store');
        $this->render_report('admin/roles/form', $this->data);
    }

    public function store()
    {
        $payload = $this->collect_payload();
        if ($payload === false) {
            redirect(base_url('index.php/roles/create'));
            return;
        }
        if ($this->rbac_m->get_role_by_slug($payload['slug'])) {
            $this->session->set_flashdata('error', 'Role slug already exists.');
            redirect(base_url('index.php/roles/create'));
            return;
        }
        $id = $this->rbac_m->create_role($payload);
        $this->session->set_flashdata('success', 'Role created. Assign permissions next.');
        redirect(base_url('index.php/permissions/edit/' . (int) $id));
    }

    public function edit($id = null)
    {
        $role = $this->rbac_m->get_role($id);
        if (!$role) {
            show_404();
            return;
        }
        $this->data['page_title'] = 'Edit Role';
        $this->data['role'] = $role;
        $this->data['form_action'] = base_url('index.php/roles/update/' . (int) $id);
        $this->render_report('admin/roles/form', $this->data);
    }

    public function update($id = null)
    {
        $role = $this->rbac_m->get_role($id);
        if (!$role) {
            show_404();
            return;
        }
        $payload = $this->collect_payload($role);
        if ($payload === false) {
            redirect(base_url('index.php/roles/edit/' . (int) $id));
            return;
        }
        $existing = $this->rbac_m->get_role_by_slug($payload['slug']);
        if ($existing && (int) $existing->id !== (int) $id) {
            $this->session->set_flashdata('error', 'Role slug already exists.');
            redirect(base_url('index.php/roles/edit/' . (int) $id));
            return;
        }
        // Never allow removing superadmin flag from the built-in role via form
        if (!empty($role->is_superadmin)) {
            $payload['is_superadmin'] = 1;
            $payload['status'] = 1;
        }
        $this->rbac_m->update_role($id, $payload);
        $this->session->set_flashdata('success', 'Role updated.');
        redirect(base_url('index.php/roles'));
    }

    public function delete($id = null)
    {
        $role = $this->rbac_m->get_role($id);
        if (!$role) {
            show_404();
            return;
        }
        if (!empty($role->is_superadmin)) {
            $this->session->set_flashdata('error', 'Super Admin role cannot be deleted.');
            redirect(base_url('index.php/roles'));
            return;
        }
        if ($this->rbac_m->count_users_in_role($id) > 0) {
            $this->session->set_flashdata('error', 'Reassign users before deleting this role.');
            redirect(base_url('index.php/roles'));
            return;
        }
        $this->rbac_m->delete_role($id);
        $this->session->set_flashdata('success', 'Role deleted.');
        redirect(base_url('index.php/roles'));
    }

    protected function collect_payload($existing = null)
    {
        $name = trim((string) $this->input->post('name'));
        $slug = trim((string) $this->input->post('slug'));
        $description = trim((string) $this->input->post('description'));
        $status = (int) $this->input->post('status') ? 1 : 0;

        if ($name === '') {
            $this->session->set_flashdata('error', 'Role name is required.');
            return false;
        }
        if ($slug === '') {
            $slug = strtolower(preg_replace('/[^a-zA-Z0-9]+/', '_', $name));
            $slug = trim($slug, '_');
        } else {
            $slug = strtolower(preg_replace('/[^a-z0-9_]/', '', $slug));
        }
        if ($slug === '') {
            $this->session->set_flashdata('error', 'Invalid role slug.');
            return false;
        }

        return array(
            'name' => $name,
            'slug' => $slug,
            'description' => $description,
            'status' => $status,
            'is_superadmin' => ($existing && !empty($existing->is_superadmin)) ? 1 : 0,
        );
    }
}
