<?php
// CONFIGURAÇÕES
$capSolverKey = 'CAP-5029767E4FD6E5A15CE7A01EE50A1D57B3F588860ED447515581B5864104FD0C';
$renavam = '00997594799';
$proxy = 'gate.nodemaven.com:8080';
$proxyAuth = 'porto2k3_gmail_com-country-any-ipv4-true:chezc140hy';

echo "1. Solicitando Token ao CapSolver...\n";

$ch = curl_init('https://api.capsolver.com/createTask');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode([
        'clientKey' => $capSolverKey,
        'task' => [
            'type' => 'AntiTurnstileTaskProxyLess',
            'websiteURL' => 'https://veiculosmg.fazenda.mg.gov.br/buscar-renavam/',
            'websiteKey' => '0x4AAAAAAAWV7kjZLnydRbx6',
        ]
    ]),
    CURLOPT_HTTPHEADER => ['Content-Type: application/json']
]);
$res = json_decode(curl_exec($ch), true);
curl_close($ch);

if (!isset($res['taskId'])) {
    die("Erro ao criar tarefa: " . json_encode($res));
}

$taskId = $res['taskId'];
$token = null;
while (true) {
    sleep(3);
    echo " Aguardando resolução...\n";
    $ch = curl_init('https://api.capsolver.com/getTaskResult');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode(['clientKey' => $capSolverKey, 'taskId' => $taskId]),
        CURLOPT_HTTPHEADER => ['Content-Type: application/json']
    ]);
    $res = json_decode(curl_exec($ch), true);
    curl_close($ch);

    if ($res['status'] === 'ready') {
        $token = $res['solution']['token'];
        break;
    }
    if ($res['status'] === 'failed') die("Erro no CapSolver: " . json_encode($res));
}

echo "2. Token obtido! Consultando Fazenda MG...\n";

$ch = curl_init("https://veiculosmg.fazenda.mg.gov.br/api/extrato-debito/renavam/$renavam/");
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_VERBOSE => false,
    CURLOPT_PROXY => $proxy,
    CURLOPT_PROXYUSERPWD => $proxyAuth,
    CURLOPT_HTTPPROXYTUNNEL => true,
    CURLOPT_ENCODING => "", // Crucial: aceita todos os encodings (gzip, br)
    CURLOPT_HTTPHEADER => [
        "Token: $token",
        "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
        "Referer: https://veiculosmg.fazenda.mg.gov.br/buscar-renavam/",
        "Accept: application/json, text/plain, */*",
        "Accept-Language: pt-BR,pt;q=0.9"
    ],
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => false
]);

$finalRes = curl_exec($ch);
$info = curl_getinfo($ch);
$error = curl_error($ch);
curl_close($ch);

echo "\n--- DEBUG DA CONEXÃO ---\n";
echo "HTTP Code: " . $info['http_code'] . "\n";
if ($error) echo "Erro cURL: " . $error . "\n";

echo "\n--- RESULTADO DA FAZENDA ---\n";
echo $finalRes ? $finalRes : "Resposta vazia do servidor.";
echo "\n---------------------------\n";
