<?php

use Modules\Settings\Models\UserPermissionsModel;
use Modules\Settings\Models\UserGroupPermissionsModel;

if (!function_exists('has_permission')) {
    /**
     * Check if current user has a permission
     * 
     * @param string $permission The permission string in 'ControllerName.methodName' format
     * @return bool
     */
    function has_permission(string $permission): bool
    {
        // Get user group / User
        $authloginModel = new \App\Models\AuthLoginModel();
        $userData = $authloginModel->getUserDetails(session('logged_user'));
        $userId = $userData->user_id;
        $groupId = $userData->group_id;
        
        if (!$userId || !$groupId) {
            return false;
        }

        // Convert permission to lowercase to match database format
        $permission = strtolower($permission);

        // First check user-specific permissions
        $userPermModel = new UserPermissionsModel();
        $hasUserPerm = $userPermModel->where('user_id', $userId)
            ->join('permissions', 'permissions.id = user_permissions.permission_id')
            ->where('permissions.module', $permission)
            ->where('user_permissions.is_allowed', 1)
            ->countAllResults() > 0;

        if ($hasUserPerm) {
            return true;
        }

        // Fall back to group permissions
        $groupPermModel = new UserGroupPermissionsModel();
        return $groupPermModel->where('group_id', $groupId)
            ->join('permissions', 'permissions.id = user_group_permissions.permission_id')
            ->where('permissions.module', $permission)
            ->countAllResults() > 0;
    }

    //On Button functions with jquery
    function permission_attrs(
        string $permission, 
        string $action, 
        ...$params
        ): string {
            if (!has_permission($permission)) {  // Removed extra parenthesis
                return 'hidden title="Requires permission"';
            }
            
            $jsParams = array_map(function($param) {
                if (is_numeric($param)) {
                    return $param; // Numbers without quotes
                }
                return "'" . addslashes($param) . "'"; // Strings with escaped quotes
            }, $params);
            
            return 'onclick="' . $action . '(' . implode(', ', $jsParams) . ')"';
        }

        //Link Buttons
        function permission_link(string $permission, string $url, string $text, array $attrs = []): string {
        if (!has_permission($permission)) {
            $attrs['class'] = ($attrs['class'] ?? '') . ' hidden';
            $attrs['title'] = 'Requires permission';
            $url = 'javascript:void(0)';
        }
        
        $attrString = '';
        foreach ($attrs as $key => $value) {
            $attrString .= " $key=\"" . htmlspecialchars($value) . "\"";
        }
        
        return "<a href=\"$url\"$attrString>$text</a>";
    }
}