<?php
function getApiKey() {
    $dbPath = "./api/.db.db";
    $defaultApiKey = '484354'; // Default value
    
    try {
        // Conecta diretamente ao banco
        $db = new SQLite3($dbPath);
        
        // Verifica se a tabela tsdbapi existe
        $tableCheck = $db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='tsdbapi'");
        if (!$tableCheck->fetchArray()) {
            return $defaultApiKey; // Tabela não existe, retorna default
        }
        
        // Busca os dados
        $stmt = $db->prepare("SELECT methord, key FROM tsdbapi WHERE id = :id");
        $stmt->bindValue(':id', 1, SQLITE3_INTEGER);
        $result = $stmt->execute();
        
        if ($result) {
            $row = $result->fetchArray(SQLITE3_ASSOC);
            if ($row) {
                $methord = $row['methord'] ?? 'def';
                $key = $row['key'] ?? '0';
                
                return ($methord === 'def') ? $defaultApiKey : $key;
            }
        }
        
        return $defaultApiKey;
    } catch (Exception $e) {
        error_log("Erro ao buscar API key: " . $e->getMessage());
        return $defaultApiKey;
    }
}
?>