<?php
// app/Helpers/permission_helper.php

if (!function_exists('has_permission')) {
    function has_permission(string $permissionName): bool
    {
        $session = session();
        if (!$session->get('isLoggedIn') || $session->get('user_type') !== 'admin') {
            return false;
        }

        $roleId = $session->get('role_id');
        if (!$roleId) return false;
        
        // Asumsi Role ID 1 adalah Super Admin yang selalu punya semua akses
        if ($roleId == 1) return true;

        $cacheKey = 'role_permissions_' . $roleId;
        if (!$permissions = cache($cacheKey)) {
            $db = \Config\Database::connect();
            $result = $db->table('role_permissions as rp')
                         ->select('p.name')
                         ->join('permissions as p', 'p.id = rp.permission_id')
                         ->where('rp.role_id', $roleId)
                         ->get()->getResultArray();
            
            $permissions = array_column($result, 'name');
            cache()->save($cacheKey, $permissions, 3600); // Cache selama 1 jam
        }
        return in_array($permissionName, (array) $permissions);
    }
}