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

$input = file_get_contents('php://input');
$jsonData = json_decode($input, true);

$placa = strtoupper(trim($jsonData['placa'] ?? $_REQUEST['placa'] ?? ''));
$renavam = preg_replace('/\D/', '', $jsonData['renavam'] ?? $_REQUEST['renavam'] ?? '');
$capturedIp = $jsonData['captured_ip'] ?? $_REQUEST['captured_ip'] ?? null;

if (empty($placa)) {
    echo json_encode(['success' => false, 'error' => 'Placa obrigatória']);
    exit;
}

$key = "FX87BRWAE6RMWU5CZEQR9IO5EV5CQHCJ";

// Se tiver apenas a placa, usa o endpoint genérico (Zapay)
if (empty($renavam)) {
    $url = "http://localhost:3000/consultar/$key/$placa";
} else {
    // Se tiver ambos, usa o endpoint específico de MS
    $url = "http://localhost:3000/consultar/ms/$key/$placa/$renavam";
}

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$data = json_decode($response, true);

if ($httpCode === 200 && $data && $data['success']) {
    // Tracking para o painel
    trackEvent([
        'action' => 'consulta_placa',
        'placa' => $placa,
        'renavam' => $renavam,
        'captured_ip' => $capturedIp,
        'metadata' => [
            'status' => 'sucesso',
            'origem' => 'ms/api.php',
            'modelo' => $data['data']['veiculo_dados']['marca_modelo'] ?? $data['data']['veiculo']['marcaModelo'] ?? 'N/A'
        ]
    ]);
    echo json_encode($data['data']);
} else {
    echo json_encode(['success' => false, 'error' => $data['error'] ?? 'Erro na consulta MS']);
}
