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

class Admin_Controller extends CI_Controller
{
    public $data = array();

    public function __construct()
    {
        parent::__construct();
        $this->load->library('session');
        $this->load->helper('rbac');

        $loggedin = $this->session->userdata('loggedin');
        if (!$loggedin) {
            redirect(base_url('index.php/login/index'));
        }

        $this->load->model('rbac_m');
    }

    /**
     * Render a report / admin page with shared header, sidebar, and footer.
     *
     * @param string $view
     * @param array  $data
     */
    protected function render_report($view, $data = array())
    {
        if (!is_array($data)) {
            $data = array();
        }
        $this->load->view('header', $data);
        $this->load->view('sidebar', $data);
        $this->load->view($view, $data);
        $this->load->view('footer', $data);
    }

    /**
     * @deprecated Use require_permission() — kept for backward compatibility.
     */
    protected function require_admin()
    {
        if (!rbac_is_superadmin()) {
            $this->access_denied('Super Admin access required.');
        }
    }

    /**
     * Require view (or export) permission for a module key.
     *
     * @param string $module_key
     * @param string $action view|export
     */
    protected function require_permission($module_key, $action = 'view')
    {
        if (!rbac_can($module_key, $action)) {
            $this->access_denied('You do not have permission to ' . $action . ' this module.');
        }
    }

    protected function access_denied($message = 'Access denied.')
    {
        if ($this->input->method(true) === 'POST' || $this->input->is_ajax_request()) {
            show_error($message, 403);
            return;
        }
        $this->session->set_flashdata('error', $message);
        $dest = rbac_first_allowed_report();
        if ($dest) {
            redirect(base_url('index.php/' . $dest));
        }
        redirect(base_url('index.php/login/logout'));
    }
}
