<?php
/**
 * Script para inserir token de teste diretamente no banco
 */

require_once __DIR__ . '/config/bootstrap.php';

use ControleFrotas\Config\Database;
use ControleFrotas\Utils\Logger;

header('Content-Type: text/html; charset=utf-8');

echo "<h1>➕ Inserir Token de Teste Manualmente</h1>";
echo "<hr>";

try {
    // Dados do token de teste
    $userId = "admin";
    $token = "manual_test_token_" . time() . "_" . rand(1000, 9999);
    $deviceId = "manual_test_device_" . rand(100000, 999999);
    $deviceName = "Manual Test Device";
    $appVersion = "1.0.0";
    $platform = "android";
    
    echo "<h2>1. Dados do Token</h2>";
    echo "<ul>";
    echo "<li><strong>User ID:</strong> $userId</li>";
    echo "<li><strong>Token:</strong> $token</li>";
    echo "<li><strong>Device ID:</strong> $deviceId</li>";
    echo "<li><strong>Device Name:</strong> $deviceName</li>";
    echo "<li><strong>App Version:</strong> $appVersion</li>";
    echo "<li><strong>Platform:</strong> $platform</li>";
    echo "</ul>";
    
    // Verificar se a tabela existe
    echo "<h2>2. Verificando tabela fcm_tokens</h2>";
    
    $tabelaExiste = Database::queryOne(
        "SELECT COUNT(*) as total FROM information_schema.tables 
         WHERE table_schema = DATABASE() AND table_name = 'fcm_tokens'"
    );
    
    if ($tabelaExiste['total'] == 0) {
        echo "<p style='color: red;'>❌ Tabela fcm_tokens não existe!</p>";
        echo "<p>Criando tabela...</p>";
        
        $sql = "CREATE TABLE fcm_tokens (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id VARCHAR(100) NOT NULL,
            token TEXT NOT NULL,
            device_id VARCHAR(255),
            device_name VARCHAR(255),
            app_version VARCHAR(50),
            platform VARCHAR(50) DEFAULT 'android',
            ativo BOOLEAN DEFAULT TRUE,
            ultimo_uso TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            UNIQUE KEY unique_user_device (user_id, device_id),
            INDEX idx_user_id (user_id),
            INDEX idx_ativo (ativo)
        )";
        
        Database::execute($sql);
        echo "<p style='color: green;'>✅ Tabela fcm_tokens criada com sucesso!</p>";
    } else {
        echo "<p style='color: green;'>✅ Tabela fcm_tokens existe</p>";
    }
    
    // Inserir token
    echo "<h2>3. Inserindo token</h2>";
    
    // Desativar tokens antigos do mesmo dispositivo
    $tokensDesativados = Database::execute(
        "UPDATE fcm_tokens SET ativo = FALSE 
         WHERE user_id = ? AND device_id = ?",
        [$userId, $deviceId]
    );
    
    echo "<p>✅ Tokens antigos desativados: $tokensDesativados</p>";
    
    // Inserir novo token
    $sql = "INSERT INTO fcm_tokens 
            (user_id, token, device_id, device_name, app_version, platform, ativo, ultimo_uso)
            VALUES (?, ?, ?, ?, ?, ?, TRUE, NOW())";
    
    Database::execute($sql, [
        $userId, $token, $deviceId, $deviceName, $appVersion, $platform
    ]);
    
    $tokenId = Database::lastInsertId();
    echo "<p style='color: green;'>✅ Token inserido com sucesso! (ID: $tokenId)</p>";
    
    // Verificar se foi inserido
    echo "<h2>4. Verificando inserção</h2>";
    
    $tokenInserido = Database::queryOne(
        "SELECT * FROM fcm_tokens WHERE id = ?",
        [$tokenId]
    );
    
    if ($tokenInserido) {
        echo "<p style='color: green;'>✅ Token encontrado no banco:</p>";
        echo "<ul>";
        echo "<li><strong>ID:</strong> {$tokenInserido['id']}</li>";
        echo "<li><strong>User ID:</strong> {$tokenInserido['user_id']}</li>";
        echo "<li><strong>Token:</strong> " . substr($tokenInserido['token'], 0, 20) . "...</li>";
        echo "<li><strong>Device ID:</strong> {$tokenInserido['device_id']}</li>";
        echo "<li><strong>Device Name:</strong> {$tokenInserido['device_name']}</li>";
        echo "<li><strong>Platform:</strong> {$tokenInserido['platform']}</li>";
        echo "<li><strong>Ativo:</strong> " . ($tokenInserido['ativo'] ? "Sim" : "Não") . "</li>";
        echo "<li><strong>Último Uso:</strong> {$tokenInserido['ultimo_uso']}</li>";
        echo "</ul>";
    } else {
        echo "<p style='color: red;'>❌ Token não encontrado no banco!</p>";
    }
    
    // Contar tokens ativos
    echo "<h2>5. Estatísticas</h2>";
    
    $totalTokens = Database::queryOne("SELECT COUNT(*) as total FROM fcm_tokens")['total'];
    $tokensAtivos = Database::queryOne("SELECT COUNT(*) as total FROM fcm_tokens WHERE ativo = TRUE")['total'];
    
    echo "<ul>";
    echo "<li><strong>Total de tokens:</strong> $totalTokens</li>";
    echo "<li><strong>Tokens ativos:</strong> $tokensAtivos</li>";
    echo "</ul>";
    
    // Listar todos os tokens
    echo "<h2>6. Todos os Tokens</h2>";
    
    $todosTokens = Database::query(
        "SELECT id, user_id, device_id, device_name, platform, ativo, ultimo_uso 
         FROM fcm_tokens ORDER BY created_at DESC"
    );
    
    if (count($todosTokens) > 0) {
        echo "<table border='1' style='border-collapse: collapse; width: 100%;'>";
        echo "<tr>";
        echo "<th>ID</th>";
        echo "<th>User ID</th>";
        echo "<th>Device ID</th>";
        echo "<th>Device Name</th>";
        echo "<th>Platform</th>";
        echo "<th>Ativo</th>";
        echo "<th>Último Uso</th>";
        echo "</tr>";
        
        foreach ($todosTokens as $token) {
            $status = $token['ativo'] ? "✅ Sim" : "❌ Não";
            $rowColor = $token['ativo'] ? "background-color: #e8f5e8;" : "background-color: #ffe8e8;";
            
            echo "<tr style='$rowColor'>";
            echo "<td>{$token['id']}</td>";
            echo "<td>{$token['user_id']}</td>";
            echo "<td>{$token['device_id']}</td>";
            echo "<td>{$token['device_name']}</td>";
            echo "<td>{$token['platform']}</td>";
            echo "<td>$status</td>";
            echo "<td>{$token['ultimo_uso']}</td>";
            echo "</tr>";
        }
        echo "</table>";
    } else {
        echo "<p style='color: orange;'>⚠️ Nenhum token encontrado</p>";
    }
    
    echo "<hr>";
    echo "<h2>🎉 TOKEN INSERIDO COM SUCESSO!</h2>";
    echo "<p>✅ Token de teste inserido no banco</p>";
    echo "<p>✅ Sistema pronto para testar notificações</p>";
    
    echo "<h3>📱 PRÓXIMOS PASSOS:</h3>";
    echo "<ol>";
    echo "<li>Reinstale o app Android</li>";
    echo "<li>Configure como 'Gestor' na instalação</li>";
    echo "<li>Verifique os logs no Android Studio</li>";
    echo "<li>Use o botão 'Registrar Token FCM' nas configurações</li>";
    echo "</ol>";
    
    echo "<p><a href='verificar-tokens.php' style='background: #007bff; color: white; padding: 10px; text-decoration: none; border-radius: 5px;'>🔍 Verificar Tokens</a></p>";
    
} catch (Exception $e) {
    echo "<p style='color: red;'>❌ ERRO: " . $e->getMessage() . "</p>";
    Logger::error('Erro ao inserir token manual', [
        'error' => $e->getMessage(),
        'trace' => $e->getTraceAsString()
    ]);
}
?> 
