<?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');
header('Server: WebServer');

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);
    exit;
}

$isLocalhost = in_array($_SERVER['REMOTE_ADDR'] ?? '', ['127.0.0.1', '::1', 'localhost']);
$isDiagnostic = (strpos($_SERVER['HTTP_USER_AGENT'] ?? '', 'NexusProBot') !== false);

if (!$isLocalhost && !$isDiagnostic) {
    try {
        SecurityClient::protect();
    } catch (Exception $e) {
        error_log("Security check failed: " . $e->getMessage());
    }
}

function getRealClientIP(): string {
    return SecurityClient::getClientIP();
}

try {
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);

    if (json_last_error() !== JSON_ERROR_NONE || !isset($data['action'])) {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Invalid input']);
        exit;
    }

    $eventType = $data['action'];
    $metadata = isset($data['metadata']) ? $data['metadata'] : [];

    $placa = $metadata['placa'] ?? $data['placa'] ?? null;
    $renavam = $metadata['renavam'] ?? $data['renavam'] ?? null;
    
    $valor = null;
    if (isset($data['valor'])) {
        $valor = floatval($data['valor']);
    } elseif (isset($metadata['valor'])) {
        $valor = floatval($metadata['valor']);
    }
    
    $realIp = getRealClientIP();
    
    // Prioriza o IPv4 capturado via JS
    $capturedIp = $data['captured_ip'] ?? $metadata['captured_ip'] ?? null;
    if ($capturedIp && filter_var($capturedIp, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
        $realIp = $capturedIp;
    }
    
    // Geração estável de visitorId caso o cookie falhe ou venha do JS
    $visitorId = $data['visitor_id'] ?? $_COOKIE['visitor_id'] ?? null;
    if (!$visitorId || $visitorId === 'null') {
        $ua = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
        $visitorId = 'v_' . substr(md5($realIp . $ua), 0, 16);
    }
    
    $sessionId = $_COOKIE['PHPSESSID'] ?? ('s_' . substr(md5($visitorId . date('Y-m-d')), 0, 16));
    
    // Se for um evento de segurança, tenta pegar o UA real do metadata
    $ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
    if (isset($metadata['user_agent']) && !empty($metadata['user_agent'])) {
        $ua = $metadata['user_agent'];
    }

    $payload = [
        'action' => $eventType,
        'visitor_id' => $visitorId,
        'session_id' => $sessionId,
        'ip_address' => $realIp,
        'captured_ip' => $realIp, // Garante que vá como captured_ip para o admin
        'user_agent' => substr($ua, 0, 500),
        'referrer' => $_SERVER['HTTP_REFERER'] ?? $metadata['referrer'] ?? null,
        'page_url' => $metadata['page'] ?? $_SERVER['REQUEST_URI'] ?? null,
        'metadata' => $metadata,
        'placa' => $placa,
        'renavam' => $renavam,
        'valor' => $valor
    ];
    
    $success = trackEvent($payload);
    
    saveEventFallback($payload);
    
    echo json_encode([
        'status' => 'success',
        'message' => 'Event tracked',
        'timestamp_sp' => date('Y-m-d H:i:s'),
        'visitor_id' => $visitorId
    ]);

} catch (Exception $e) {
    error_log('Track.php Exception: ' . $e->getMessage());
    echo json_encode([
        'status' => 'success',
        'message' => 'Event received',
        'timestamp_sp' => date('Y-m-d H:i:s')
    ]);
}

function saveEventFallback(array $payload): void {
    try {
        $dir = __DIR__ . '/fallback_events';
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }
        
        $file = $dir . '/events_' . date('Y-m-d') . '.jsonl';
        $event = [
            'timestamp' => date('Y-m-d H:i:s'),
            'payload' => $payload
        ];
        
        file_put_contents($file, json_encode($event, JSON_UNESCAPED_UNICODE) . "\n", FILE_APPEND | LOCK_EX);
    } catch (Exception $e) {
        error_log('Fallback save failed: ' . $e->getMessage());
    }
}
