<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

$renavam = preg_replace('/\D/', '', $_REQUEST['renavam'] ?? '');
if (strlen($renavam) < 9) {
    echo json_encode(['success' => false, 'error' => 'Renavam inválido.']);
    exit;
}

$key = "FX87BRWAE6RMWU5CZEQR9IO5EV5CQHCJ";
$url = "http://69.5.189.108:3000/consultar/rj/$key/$renavam";

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);

if ($data && $data['success']) {
    $result = $data['data'];
    $result['success'] = true;
    echo json_encode($result);
}
else {
    echo json_encode(['success' => false, 'error' => $data['error'] ?? 'Erro na consulta RJ']);
}
