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


function get_user_permissions() {
    $CI =& get_instance();
    $session = $CI->session->userdata('user_info');

    if (isset($session['login_type']) && $session['login_type'] === 'sub_admin') {
        $sub_admin_id = $session['user_id'];
        $CI->load->database();

        $CI->db->select('role_id');
        $CI->db->from('permissions');
        $CI->db->where(['sub_admin_id' => $sub_admin_id]);
        $query = $CI->db->get();
        $result = $query->result_array();

        return !empty($result) ? array_column($result, 'role_id') : [];
    }

    return []; // For admins or others
}

function has_access($role_id) {
    $CI =& get_instance();
    $session = $CI->session->userdata('user_info');

    if (isset($session['login_type']) && $session['login_type'] === 'admin') {
        return true;
    }

    $permissions = get_user_permissions();
    return in_array($role_id, $permissions);
}

function check_permission($role_id) {
    $CI =& get_instance();

    if (!has_access($role_id)) {
        // Output a styled unauthorized access message directly
        echo '
        <!DOCTYPE html>
        <html>
        <head>
            <title>Unauthorized Access</title>
            <style>
                body {
                    background-color: #f8d7da;
                    font-family: Arial, sans-serif;
                    margin: 0;
                    padding: 0;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    height: 100vh;
                    color: #721c24;
                }
                .unauthorized-box {
                    background-color: #f8d7da;
                    border: 1px solid #f5c6cb;
                    padding: 40px;
                    border-radius: 10px;
                    box-shadow: 0 0 10px rgba(0,0,0,0.1);
                    text-align: center;
                }
                h1 {
                    font-size: 28px;
                    margin-bottom: 15px;
                }
                p {
                    font-size: 18px;
                    margin-bottom: 20px;
                }
                a {
                    background-color: #c82333;
                    color: white;
                    padding: 10px 20px;
                    text-decoration: none;
                    border-radius: 5px;
                }
                a:hover {
                    background-color: #a71d2a;
                }
            </style>
        </head>
        <body>
            <div class="unauthorized-box">
                <h1>⚠ Unauthorized Access</h1>
                <p>You do not have permission to access this module.</p>
                <a href="' . base_url('admin/register') . '">Back to Dashboard</a>
            </div>
        </body>
        </html>';
        exit;
    }
}




