<?php

if (!function_exists('setting')) {
    /**
     * Get a setting value from the database
     *
     * @param string $key
     * @param mixed $default
     * @return mixed
     */
    function setting($key, $default = null)
    {
        static $settings = null;

        // Cache settings in memory for the request
        if ($settings === null) {
            $settings = \App\Models\Setting::pluck('value', 'key')->toArray();
        }

        return $settings[$key] ?? $default;
    }
}

if (!function_exists('can_access')) {
    /**
     * Check if the authenticated user has permission to access a module
     *
     * @param string $module
     * @param string $action
     * @return bool
     */
    function can_access($module, $action = 'read')
    {
        $user = auth()->user();

        if (!$user) {
            return false;
        }

        // FinanceUser (and other auth models) may not implement permission API.
        if (!method_exists($user, 'hasPermission')) {
            return false;
        }

        // Super admin (user ID 1) always has full access
        if ((int) $user->id === 1) {
            return true;
        }

        return (bool) $user->hasPermission($module, $action);
    }
}
