<?php
/**
 * Script para inicializar a API Key no banco de dados
 * Execute este script uma vez para configurar o token inicial
 */

$token = '4ddbee538bd0c96b4db4fd1384d7bebd2db6f79461357997ed156c32d58844b664fbc525be339d693fbac3600926a30fe408811e40c153bd7ef8943bfae0866f';

$dbPath = __DIR__ . '/admin/admin.db';

try {
    $pdo = new PDO('sqlite:' . $dbPath);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->exec('PRAGMA journal_mode = WAL');
    
    // Criar tabela se não existir
    $pdo->exec("CREATE TABLE IF NOT EXISTS settings (
        key TEXT PRIMARY KEY,
        value TEXT NOT NULL,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");
    
    // Criar tabela de histórico
    $pdo->exec("CREATE TABLE IF NOT EXISTS api_token_history (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        token_old_masked TEXT,
        token_new_masked TEXT,
        description_old TEXT,
        description_new TEXT,
        changed_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        changed_by_ip TEXT,
        change_type TEXT DEFAULT 'update'
    )");
    
    // Config inicial
    $config = [
        'apiToken' => $token,
        'description' => 'Token inicial configurado via script',
        'lastUpdated' => date('Y-m-d H:i:s')
    ];
    
    // Verificar se já existe
    $stmt = $pdo->prepare('SELECT value FROM settings WHERE key = :key LIMIT 1');
    $stmt->execute([':key' => 'api_config']);
    $existing = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($existing) {
        echo "API Key já está configurada no banco de dados.\n";
        echo "Use o painel admin para atualizar se necessário.\n";
    } else {
        // Inserir config
        $stmt = $pdo->prepare('INSERT INTO settings (key, value, updated_at) VALUES (:key, :value, datetime(\'now\', \'localtime\'))');
        $stmt->execute([
            ':key' => 'api_config',
            ':value' => json_encode($config, JSON_UNESCAPED_UNICODE)
        ]);
        
        // Registrar no histórico
        $maskToken = function($t) {
            $len = strlen($t);
            if ($len > 8) return substr($t, 0, 4) . '...' . substr($t, -4);
            return '****';
        };
        
        $histStmt = $pdo->prepare("INSERT INTO api_token_history 
            (token_old_masked, token_new_masked, description_old, description_new, changed_by_ip, change_type, changed_at)
            VALUES (NULL, :token_new, NULL, :desc_new, :ip, 'create', datetime('now', 'localtime'))");
        
        $histStmt->execute([
            ':token_new' => $maskToken($token),
            ':desc_new' => 'Token inicial configurado via script',
            ':ip' => 'localhost'
        ]);
        
        echo "✅ API Key configurada com sucesso!\n";
        echo "Token (mascarado): " . $maskToken($token) . "\n";
    }
    
} catch (Exception $e) {
    echo "❌ Erro: " . $e->getMessage() . "\n";
}
