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

$placa = strtoupper(trim($_REQUEST['placa'] ?? ''));
$capturedIp = $_REQUEST['captured_ip'] ?? null;

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

$key = "FX87BRWAE6RMWU5CZEQR9IO5EV5CQHCJ";
$url = "http://localhost:3000/consultar/$key/$placa";

$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']) {
    $res = $data['data'];
    $veiculo = $res['vehicle'] ?? [];
    $debitos = $res['debts'] ?? [];
    
    // Calcula valor total
    $valorTotal = 0;
    foreach($debitos as $d) {
        $valorTotal += (float)($d['amount'] ?? 0);
    }

    // Tracking
    trackEvent([
        'action' => 'consulta_placa',
        'placa' => $placa,
        'renavam' => $veiculo['renavam'] ?? '',
        'valor' => $valorTotal,
        'captured_ip' => $capturedIp,
        'metadata' => [
            'status' => 'sucesso',
            'origem' => 'pr/api.php',
            'modelo' => $veiculo['model'] ?? 'N/A',
            'proprietario' => $veiculo['owner'] ?? 'N/A'
        ]
    ]);

    echo json_encode([
        'success' => true,
        'veiculo' => $veiculo,
        'debitos' => $debitos,
        'valorTotal' => $valorTotal
    ]);
} else {
    echo json_encode(['success' => false, 'error' => $data['error'] ?? 'Veiculo nao encontrado no PR']);
}
