<?php
// app/ai_settings.php
// Helper que consulta a config global de IA (admin_ai_settings) e decide
// se deve mostrar o campo OpenAI pro cliente na Minha Conta.

if (!function_exists('ai_get_config')) {

    /**
     * Retorna a config global de IA, cacheada por request.
     * @return array ['payer' => 'admin'|'client']
     */
    function ai_get_config(): array {
        static $cached = null;
        if ($cached !== null) return $cached;

        $defaults = ['payer' => 'admin'];

        try {
            $pdo = db();
            $stmt = $pdo->query("SELECT payer FROM public.admin_ai_settings WHERE id = 1 LIMIT 1");
            $row = $stmt->fetch();
            if ($row && isset($row['payer'])) {
                $defaults['payer'] = $row['payer'];
            }
        } catch (Throwable $e) {
            // Se a tabela ainda não existe, assume default
            error_log('ai_get_config: ' . $e->getMessage());
        }

        return $cached = $defaults;
    }

    /**
     * Retorna true se o cliente precisa cadastrar a própria chave OpenAI.
     */
    function ai_client_must_provide_key(): bool {
        $cfg = ai_get_config();
        return ($cfg['payer'] ?? 'admin') === 'client';
    }

    /**
     * Busca a chave OpenAI do cliente logado.
     */
    function ai_get_client_key(string $userId): ?string {
        try {
            $pdo = db();
            $stmt = $pdo->prepare("SELECT openai_api_key FROM public.auth_users WHERE id = :id LIMIT 1");
            $stmt->execute([':id' => $userId]);
            $key = $stmt->fetchColumn();
            return ($key && trim($key) !== '') ? trim($key) : null;
        } catch (Throwable $e) {
            error_log('ai_get_client_key: ' . $e->getMessage());
            return null;
        }
    }
}
