<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

echo "<h1>📱 Callback RD Station</h1>";

if (isset($_GET['code'])) {
    $code = $_GET['code'];
    
    echo "<div style='background: #d4edda; padding: 20px; margin: 20px 0;'>";
    echo "<h2>✅ Código recebido com sucesso!</h2>";
    echo "<p><strong>Código:</strong> <code style='background: #f8f9fa; padding: 5px;'>" . htmlspecialchars($code) . "</code></p>";
    echo "</div>";
    
    // ✅✅✅ VALORES CORRETOS JÁ CONFIGURADOS ✅✅✅
    $client_id = 'c80b7737-1279-4fd6-91bc-3c8098785a31'; // ✅ CORRETO
    $client_secret = '129cf4f7c93d4d24b0438891237faa70'; // ✅ CORRETO
    $redirect_uri = 'https://teste.tvitecnologia.com.br/callback.php';
    
    echo "<div style='background: #e8f4f8; padding: 20px; border-radius: 5px; margin: 20px 0;'>";
    echo "<h2>✅ Configuração do App:</h2>";
    echo "<table border='1' cellpadding='10' style='border-collapse: collapse; width: 100%;'>";
    echo "<tr style='background: #f8f9fa;'><th>Parâmetro</th><th>Valor</th><th>Status</th></tr>";
    echo "<tr>";
    echo "<td><strong>Client ID</strong></td>";
    echo "<td><code style='background: #f1f1f1; padding: 5px;'>" . substr($client_id, 0, 20) . "...</code></td>";
    echo "<td style='color: green; font-weight: bold;'>✅ OK</td>";
    echo "</tr>";
    echo "<tr>";
    echo "<td><strong>Client Secret</strong></td>";
    echo "<td><code style='background: #f1f1f1; padding: 5px;'>***" . substr($client_secret, -4) . "</code></td>";
    echo "<td style='color: green; font-weight: bold;'>✅ OK</td>";
    echo "</tr>";
    echo "<tr>";
    echo "<td><strong>Redirect URI</strong></td>";
    echo "<td><code style='background: #f1f1f1; padding: 5px;'>$redirect_uri</code></td>";
    echo "<td style='color: green; font-weight: bold;'>✅ OK</td>";
    echo "</tr>";
    echo "</table>";
    echo "</div>";
    
    // REMOVA O BLOCO DE VERIFICAÇÃO DE PLACEHOLDER (linhas 33-39)
    // Ou comente/delete essas linhas
    
    // Obter Access Token
    echo "<h3>🔄 Obtendo Access Token...</h3>";
    
    $url = "https://api.rd.services/auth/token";
    $data = [
        'client_id' => $client_id,
        'client_secret' => $client_secret,
        'code' => $code,
        'grant_type' => 'authorization_code',
        'redirect_uri' => $redirect_uri
    ];
    
    echo "<p><strong>Enviando para:</strong> $url</p>";
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query($data),
        CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
        CURLOPT_TIMEOUT => 10,
        CURLOPT_SSL_VERIFYPEER => true
    ]);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($http_code == 200) {
        $tokens = json_decode($response, true);
        
        echo "<div style='background: #d4edda; padding: 30px; border: 3px solid #28a745; margin: 20px 0;'>";
        echo "<h2>🎉 TOKEN OBTIDO COM SUCESSO!</h2>";
        
        // Access Token (para campo ID 7)
        echo "<h3>🔑 Access Token (use no campo ID 7):</h3>";
        echo "<textarea style='width: 100%; height: 100px; font-family: monospace; padding: 10px; background: #f8f9fa; border: 2px solid #28a745;' readonly>" . $tokens['access_token'] . "</textarea>";
        
        // Salvar em arquivo
        $token_file = __DIR__ . '/integracao_legada/rd_tokens.txt';
        file_put_contents($token_file, json_encode($tokens, JSON_PRETTY_PRINT));
        
        echo "<p><strong>✅ Token salvo em:</strong> $token_file</p>";
        
        echo "<h3>🚀 Próximos passos:</h3>";
        echo "<ol>";
        echo "<li><strong>Teste a API:</strong> <a href='/integracao_legada/test_api.php' style='color: blue; font-weight: bold;'>Clique aqui para testar</a></li>";
        echo "<li><strong>Configure no sistema:</strong> Cole o Access Token acima no campo ID 7</li>";
        echo "<li><strong>URL da API:</strong> https://api.rd.services/platform/conversions</li>";
        echo "<li><strong>Método:</strong> POST com JSON</li>";
        echo "</ol>";
        echo "</div>";
        
    } else {
        echo "<div style='background: #f8d7da; padding: 20px;'>";
        echo "<h3>❌ Erro ao obter token</h3>";
        echo "<p>HTTP Code: <strong>$http_code</strong></p>";
        if ($error) {
            echo "<p>Erro cURL: $error</p>";
        }
        echo "<p>Resposta: " . htmlspecialchars($response) . "</p>";
        echo "</div>";
    }
    
} elseif (isset($_GET['error'])) {
    echo "<h2 style='color: red;'>❌ Erro na autenticação</h2>";
    echo "<p>" . htmlspecialchars($_GET['error']) . "</p>";
    if (isset($_GET['error_description'])) {
        echo "<p>Descrição: " . htmlspecialchars($_GET['error_description']) . "</p>";
    }
} else {
    echo "<h2>📭 Aguardando autorização</h2>";
    echo "<p>Esta página receberá a resposta do RD Station após autorização.</p>";
    echo "<p><a href='/integracao_legada/auth.php' style='padding: 10px 20px; background: #007bff; color: white; text-decoration: none;'>👉 Ir para Autenticação</a></p>";
}
?>