<?php
class Dashboard extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->model('Permission_model');
        if (!$this->session->userdata('user_id')) redirect('auth/login');
    }
    
    public function index() {
        $role_id = $this->session->userdata('role_id');
        $data['sections'] = [];

        if ($role_id == 1) {
            // Superadmin: show all sections and admin tools
            $data['sections'] = [
                'clients', 'accounts', 'balance', 'tickets', 'users',
                'admin/manage_users', 'admin/manage_roles', 'admin/manage_permissions', 'admin/create_role', 'admin/create_user',
            ];
        } else {
            // Convert permission objects to string section names
            $permissions = $this->Permission_model->get_permissions_by_role($role_id);
            $data['sections'] = array_map(function($p) {
                return is_object($p) ? $p->section : $p;
            }, $permissions);
        }

        $data['content'] = 'dashboard/home';
        $this->load->view('dashboard/layout', $data);
    }



    public function clients() {
    $this->_check_access('clients');
    $this->load->view('dashboard/clients');
}


    public function accounts() {
        $this->_check_access('accounts');
        $this->load->view('dashboard/accounts');
    }

    public function balance() {
        $this->_check_access('balance');
        $this->load->view('dashboard/balance');
    }

    public function tickets() {
        $this->_check_access('tickets');
        $this->load->view('dashboard/tickets');
    }

    public function users() {
        $this->_check_access('users');
        $this->load->view('dashboard/users');
    }

    private function _check_access($section) {
        $role_id = $this->session->userdata('role_id');
        if ($role_id == 1) return;  // Superadmin can access everything
        if (!$this->Permission_model->has_access($role_id, $section)) {
            show_error('Access denied', 403);
        }
    }
}
