*/ private array $cache = []; public function enabled(): bool { $platformFlag = $this->setting('ai_enabled'); if ($platformFlag !== null && ! filter_var($platformFlag, FILTER_VALIDATE_BOOLEAN)) { return false; } if (! (bool) config('afia.enabled', true)) { return false; } return $this->apiKey() !== ''; } public function provider(): string { $provider = strtolower(trim((string) ($this->setting('ai_provider') ?? config('afia.provider', 'openai')))); return in_array($provider, ['openai', 'anthropic'], true) ? $provider : 'openai'; } public function model(): string { $configured = trim((string) ($this->setting('ai_model') ?? config('afia.model', ''))); if ($configured !== '') { return $configured; } return $this->provider() === 'anthropic' ? 'claude-3-5-haiku-latest' : 'gpt-4o-mini'; } public function apiKey(): string { $provider = $this->provider(); $providerKey = match ($provider) { 'anthropic' => trim((string) ($this->setting('ai_anthropic_api_key') ?? '')), default => trim((string) ($this->setting('ai_openai_api_key') ?? '')), }; if ($providerKey !== '') { return $providerKey; } $shared = trim((string) ($this->setting('ai_api_key') ?? '')); if ($shared !== '') { return $shared; } return trim((string) config('afia.api_key', '')); } private function setting(string $key): mixed { if (array_key_exists($key, $this->cache)) { return $this->cache[$key]; } try { if (! Schema::connection('platform')->hasTable('platform_settings')) { return $this->cache[$key] = null; } $setting = PlatformSetting::query() ->where('key', $key) ->where('is_active', true) ->first(); return $this->cache[$key] = $setting ? ($setting->value['value'] ?? null) : null; } catch (\Throwable) { return $this->cache[$key] = null; } } }