<?php
/**
 * Endpoint de Tracking LOCAL
 * 
 * Recebe eventos do frontend e salva diretamente no admin.db local.
 * Não depende de servidor remoto.
 * 
 * @version 6.0 - 100% Local
 */

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

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');

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

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

date_default_timezone_set('America/Sao_Paulo');

/**
 * Obter IP real do cliente
 */
function getRealClientIP(): string {
    $headers = [
        'HTTP_CF_CONNECTING_IP',
        'HTTP_X_REAL_IP',
        'HTTP_X_FORWARDED_FOR',
        'HTTP_CLIENT_IP',
        'REMOTE_ADDR'
    ];
    
    foreach ($headers as $header) {
        if (!empty($_SERVER[$header])) {
            $ip = $_SERVER[$header];
            if (strpos($ip, ',') !== false) {
                $ip = trim(explode(',', $ip)[0]);
            }
            if (filter_var($ip, FILTER_VALIDATE_IP)) {
                return $ip;
            }
        }
    }
    
    return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
}

try {
    // Conectar ao banco local
    $dbPath = __DIR__ . '/eodf15mk/admin.db';
    $pdo = new PDO('sqlite:' . $dbPath);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Criar tabela de eventos se não existir
    $pdo->exec("CREATE TABLE IF NOT EXISTS events (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        event_type TEXT NOT NULL,
        event_timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
        visitor_id TEXT,
        session_id TEXT,
        ip_address TEXT,
        user_agent TEXT,
        referrer TEXT,
        page_url TEXT,
        metadata TEXT,
        placa TEXT,
        renavam TEXT,
        valor REAL,
        utm_source TEXT,
        utm_medium TEXT,
        utm_campaign TEXT
    )");
    
    // Processar entrada
    $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 = $data['metadata'] ?? [];

    // Extrair dados
    $placa = $metadata['placa'] ?? $metadata['veiculo']['placa'] ?? null;
    $renavam = $metadata['renavam'] ?? $metadata['veiculo']['renavam'] ?? null;
    
    $valor = null;
    if (isset($metadata['valor'])) {
        $valor = floatval($metadata['valor']);
    } elseif (isset($metadata['value'])) {
        $valor = floatval($metadata['value']);
    } elseif (isset($metadata['amount'])) {
        $valor = floatval($metadata['amount']);
    }
    
    // Gerar ou recuperar visitor_id
    $visitorId = $_COOKIE['visitor_id'] ?? null;
    if (!$visitorId) {
        $visitorId = 'v_' . bin2hex(random_bytes(16));
        setcookie('visitor_id', $visitorId, time() + (365 * 24 * 60 * 60), '/', '', false, true);
    }
    
    $realIp = getRealClientIP();
    $sessionId = $_COOKIE['PHPSESSID'] ?? ('s_' . substr(md5($visitorId . date('Y-m-d')), 0, 16));
    
    // Inserir evento no banco local
    $stmt = $pdo->prepare("
        INSERT INTO events (
            event_type, event_timestamp, visitor_id, session_id, 
            ip_address, user_agent, referrer, page_url, 
            metadata, placa, renavam, valor,
            utm_source, utm_medium, utm_campaign
        ) VALUES (
            :event_type, :timestamp, :visitor_id, :session_id,
            :ip_address, :user_agent, :referrer, :page_url,
            :metadata, :placa, :renavam, :valor,
            :utm_source, :utm_medium, :utm_campaign
        )
    ");
    
    $stmt->execute([
        ':event_type' => $eventType,
        ':timestamp' => date('Y-m-d H:i:s'),
        ':visitor_id' => $visitorId,
        ':session_id' => $sessionId,
        ':ip_address' => $realIp,
        ':user_agent' => substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 500),
        ':referrer' => $_SERVER['HTTP_REFERER'] ?? $metadata['referrer'] ?? null,
        ':page_url' => $metadata['page'] ?? $_SERVER['REQUEST_URI'] ?? null,
        ':metadata' => json_encode($metadata, JSON_UNESCAPED_UNICODE),
        ':placa' => $placa,
        ':renavam' => $renavam,
        ':valor' => $valor,
        ':utm_source' => $metadata['utm_source'] ?? null,
        ':utm_medium' => $metadata['utm_medium'] ?? null,
        ':utm_campaign' => $metadata['utm_campaign'] ?? null
    ]);
    
    echo json_encode([
        'status' => 'success',
        'message' => 'Event tracked',
        'timestamp_sp' => date('Y-m-d H:i:s'),
        'visitor_id' => $visitorId,
        'event_id' => $pdo->lastInsertId()
    ]);

} catch (Exception $e) {
    error_log('Track.php Exception: ' . $e->getMessage());
    
    echo json_encode([
        'status' => 'error',
        'message' => 'Internal error',
        'debug' => $e->getMessage()
    ]);
}
