<?php
/**
 * Script para debug do registro de token FCM
 */

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

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

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

echo "<h1>🐛 Debug do Registro de Token FCM</h1>";
echo "<hr>";

try {
    // 1. Verificar dados recebidos
    echo "<h2>1. Dados Recebidos</h2>";
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if ($input) {
        echo "<p style='color: green;'>✅ JSON recebido:</p>";
        echo "<pre>" . json_encode($input, JSON_PRETTY_PRINT) . "</pre>";
        
        $userId = $input['user_id'] ?? null;
        $token = $input['token'] ?? null;
        $deviceId = $input['device_id'] ?? null;
        $deviceName = $input['device_name'] ?? null;
        $appVersion = $input['app_version'] ?? null;
        $platform = $input['platform'] ?? 'android';
        
        echo "<ul>";
        echo "<li><strong>User ID:</strong> " . ($userId ?: 'NULL') . "</li>";
        echo "<li><strong>Token:</strong> " . ($token ? substr($token, 0, 30) . '...' : 'NULL') . "</li>";
        echo "<li><strong>Device ID:</strong> " . ($deviceId ?: 'NULL') . "</li>";
        echo "<li><strong>Device Name:</strong> " . ($deviceName ?: 'NULL') . "</li>";
        echo "<li><strong>App Version:</strong> " . ($appVersion ?: 'NULL') . "</li>";
        echo "<li><strong>Platform:</strong> " . ($platform ?: 'NULL') . "</li>";
        echo "</ul>";
    } else {
        echo "<p style='color: red;'>❌ Nenhum JSON recebido</p>";
        echo "<p>Raw input: " . file_get_contents('php://input') . "</p>";
    }
    
    // 2. Verificar estrutura da tabela
    echo "<h2>2. Estrutura da 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>";
        
        // Verificar estrutura
        $colunas = Database::query(
            "DESCRIBE fcm_tokens"
        );
        
        echo "<table border='1' style='border-collapse: collapse; width: 100%;'>";
        echo "<tr><th>Campo</th><th>Tipo</th><th>Null</th><th>Key</th><th>Default</th><th>Extra</th></tr>";
        
        foreach ($colunas as $coluna) {
            echo "<tr>";
            echo "<td>{$coluna['Field']}</td>";
            echo "<td>{$coluna['Type']}</td>";
            echo "<td>{$coluna['Null']}</td>";
            echo "<td>{$coluna['Key']}</td>";
            echo "<td>{$coluna['Default']}</td>";
            echo "<td>{$coluna['Extra']}</td>";
            echo "</tr>";
        }
        echo "</table>";
    }
    
    // 3. Tentar inserir token
    if ($userId && $token) {
        echo "<h2>3. Tentando Inserir Token</h2>";
        
        try {
            // Desativar tokens antigos do mesmo dispositivo
            if ($deviceId) {
                $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
            $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, 30) . "...</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>";
            }
            
        } catch (Exception $e) {
            echo "<p style='color: red;'>❌ Erro ao inserir token: " . $e->getMessage() . "</p>";
            echo "<pre>" . $e->getTraceAsString() . "</pre>";
        }
    }
    
    // 4. Estatísticas
    echo "<h2>4. 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>";
    
    echo "<hr>";
    echo "<h2>🎉 DEBUG CONCLUÍDO!</h2>";
    
} catch (Exception $e) {
    echo "<p style='color: red;'>❌ ERRO GERAL: " . $e->getMessage() . "</p>";
    echo "<pre>" . $e->getTraceAsString() . "</pre>";
    Logger::error('Erro no debug de token', [
        'error' => $e->getMessage(),
        'trace' => $e->getTraceAsString()
    ]);
}
?> 
