<?php
/**
 * API de Consulta de Débitos de Veículos - MG (Minas Gerais)
 * Versão sem Proxy
 */

// Remover headers que expõem informações
header_remove('X-Powered-By');
ini_set('expose_php', 'off');

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// ============================================
// CONFIGURAÇÕES
// ============================================

define('FAZENDA_MG_BASE_URL', 'https://veiculosmg.fazenda.mg.gov.br');
define('FAZENDA_MG_API_URL', FAZENDA_MG_BASE_URL . '/api/extrato-debito/renavam/');
define('CF_TURNSTILE_SITEKEY', '0x4AAAAAAAWV7kjZLnydRbx6');
define('CF_TOKEN_CACHE_FILE', __DIR__ . '/cache/cf_token.json');
define('COOKIES_CACHE_FILE', __DIR__ . '/cache/cookies.json');

// CAPSOLVER
define('CAPSOLVER_API_KEY', 'CAP-5029767E4FD6E5A15CE7A01EE50A1D57B3F588860ED447515581B5864104FD0C'); 
define('CAPSOLVER_API_URL', 'https://api.capsolver.com');

// PROXY DESATIVADO
define('PROXY_ENABLED', false);

// ============================================
// FUNÇÕES DO CAPSOLVER
// ============================================

function solveTurnstileWithCapSolver(): ?array {
    $createTaskPayload = [
        'clientKey' => CAPSOLVER_API_KEY,
        'task' => [
            'type' => 'AntiTurnstileTaskProxyLess',
            'websiteURL' => FAZENDA_MG_BASE_URL . '/buscar-renavam/',
            'websiteKey' => CF_TURNSTILE_SITEKEY,
            'metadata' => [
                'action' => 'consulta-buscar-renavam'
            ]
        ]
    ];
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => CAPSOLVER_API_URL . '/createTask',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($createTaskPayload),
        CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYPEER => false
    ]);
    
    $response = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($error) return ['success' => false, 'error' => 'Erro ao conectar com CapSolver: ' . $error];
    
    $result = json_decode($response, true);
    if (!isset($result['taskId'])) return ['success' => false, 'error' => 'Erro ao criar tarefa'];
    
    $taskId = $result['taskId'];
    $maxAttempts = 120;
    $attempt = 0;
    
    while ($attempt < $maxAttempts) {
        sleep(2);
        $attempt++;
        
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => CAPSOLVER_API_URL . '/getTaskResult',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode(['clientKey' => CAPSOLVER_API_KEY, 'taskId' => $taskId]),
            CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
            CURLOPT_TIMEOUT => 10,
            CURLOPT_SSL_VERIFYPEER => false
        ]);
        
        $response = curl_exec($ch);
        curl_close($ch);
        $result = json_decode($response, true);
        
        if (isset($result['status'])) {
            if ($result['status'] === 'ready') {
                return ['success' => true, 'token' => $result['solution']['token'] ?? null];
            } elseif ($result['status'] === 'failed') {
                return ['success' => false, 'error' => 'CapSolver falhou'];
            }
        }
    }
    return ['success' => false, 'error' => 'Timeout'];
}

// ... (Funções getCapSolverBalance, getCfToken, saveCfToken, getSavedCookies, saveCookies permanecem iguais)

function getCapSolverBalance(): ?array {
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => CAPSOLVER_API_URL . '/getBalance',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode(['clientKey' => CAPSOLVER_API_KEY]),
        CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        CURLOPT_TIMEOUT => 10,
        CURLOPT_SSL_VERIFYPEER => false
    ]);
    $response = curl_exec($ch);
    curl_close($ch);
    return json_decode($response, true);
}

function getCfToken(bool $autoSolve = true): ?string {
    if (!empty($_REQUEST['cf_token'])) return $_REQUEST['cf_token'];
    if ($autoSolve && CAPSOLVER_API_KEY !== '') {
        $result = solveTurnstileWithCapSolver();
        if ($result['success']) return $result['token'];
    }
    return null;
}

function saveCfToken(string $token, int $ttl = 300): void {
    if (!is_dir(dirname(CF_TOKEN_CACHE_FILE))) mkdir(dirname(CF_TOKEN_CACHE_FILE), 0755, true);
    file_put_contents(CF_TOKEN_CACHE_FILE, json_encode(['token' => $token, 'expires' => time() + $ttl]));
}

function getSavedCookies(): string {
    if (file_exists(COOKIES_CACHE_FILE)) {
        $cache = json_decode(file_get_contents(COOKIES_CACHE_FILE), true);
        return $cache['cookies'] ?? '';
    }
    return '';
}

function saveCookies(string $cookies): void {
    if (!is_dir(dirname(COOKIES_CACHE_FILE))) mkdir(dirname(COOKIES_CACHE_FILE), 0755, true);
    file_put_contents(COOKIES_CACHE_FILE, json_encode(['cookies' => $cookies, 'saved_at' => date('Y-m-d H:i:s')]));
}

/**
 * Fazer requisição à API da Fazenda MG (SEM PROXY)
 */
function consultarDebitosMG(string $renavam, string $cfToken): array {
    $url = FAZENDA_MG_API_URL . $renavam . '/';
    
    $headers = [
        'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36',
        'Accept: application/json, text/plain, */*',
        'Token: ' . $cfToken,
        'Referer: ' . FAZENDA_MG_BASE_URL . '/buscar-renavam/',
        'Origin: ' . FAZENDA_MG_BASE_URL
    ];
    
    $cookies = getSavedCookies();
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 60,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_ENCODING => 'gzip, deflate, br',
    ]);

    // O BLOCO DE PROXY FOI REMOVIDO DAQUI

    if (!empty($cookies)) {
        curl_setopt($ch, CURLOPT_COOKIE, $cookies);
    }
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($error) return ['success' => false, 'error' => $error];
    
    $data = json_decode($response, true);
    return ($httpCode === 200 && $data) ? ['success' => true, 'data' => $data] : ['success' => false, 'http_code' => $httpCode, 'error' => 'Erro na API'];
}

// ... (Restante do processamento de formatação e try/catch permanece igual)

/**
 * Formatar débitos para o padrão do frontend
 */
function formatarDebitos(array $apiData): array {
    $debitos = [];
    $tipos = ['ipva', 'licenciamento', 'multas', 'taxas', 'dpvat'];
    foreach ($tipos as $tipo) {
        if (isset($apiData[$tipo]) && is_array($apiData[$tipo])) {
            foreach ($apiData[$tipo] as $debito) {
                $debitos[] = [
                    'tipo' => ucfirst($tipo),
                    'exercicio' => $debito['exercicio'] ?? date('Y'),
                    'valor' => floatval($debito['valor'] ?? 0),
                    'situacao' => $debito['situacao'] ?? 'PENDENTE'
                ];
            }
        }
    }
    return $debitos;
}

function extrairDadosVeiculo(array $apiData): array {
    return [
        'nuPlaca' => $apiData['placa'] ?? '-',
        'dsMarca' => $apiData['marca'] ?? '-',
        'dsModelo' => $apiData['modelo'] ?? '-'
    ];
}

try {
    $renavam = preg_replace('/\D/', '', $_REQUEST['renavam'] ?? '');
    if (!$renavam) throw new Exception("Renavam obrigatório");

    $token = getCfToken(true);
    if (!$token) throw new Exception("Falha ao obter token Cloudflare");

    $resultado = consultarDebitosMG($renavam, $token);
    echo json_encode($resultado, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
