<?php
require_once __DIR__ . '/require_auth.php';

header('Content-Type: application/json');

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

try {
    // --- Database Connection ---
    $dbPath = __DIR__ . '/admin.db';
    $pdo = new PDO('sqlite:' . $dbPath);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // --- Create Table If Not Exists ---
    $pdo->exec("CREATE TABLE IF NOT EXISTS events (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        event_type TEXT NOT NULL,
        ip_address TEXT,
        user_agent TEXT,
        event_timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
        metadata TEXT,
        utm_source TEXT,
        utm_medium TEXT,
        utm_campaign TEXT
    )");

    // --- Process Request ---
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);

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

    // --- Prepare Data ---
    $eventType = $data['action'];
    $metadata = $data['metadata'];
    $utm = isset($metadata['utm']) ? $metadata['utm'] : [];

    $ip = $_SERVER['REMOTE_ADDR'];
    $userAgent = $_SERVER['HTTP_USER_AGENT'];

    // --- Insert into Database ---
    $stmt = $pdo->prepare(
        "INSERT INTO events (event_type, ip_address, user_agent, metadata, utm_source, utm_medium, utm_campaign) 
         VALUES (:event_type, :ip_address, :user_agent, :metadata, :utm_source, :utm_medium, :utm_campaign)"
    );

    $stmt->execute([
        ':event_type' => $eventType,
        ':ip_address' => $ip,
        ':user_agent' => $userAgent,
        ':metadata' => json_encode($metadata),
        ':utm_source' => isset($utm['utm_source']) ? $utm['utm_source'] : null,
        ':utm_medium' => isset($utm['utm_medium']) ? $utm['utm_medium'] : null,
        ':utm_campaign' => isset($utm['utm_campaign']) ? $utm['utm_campaign'] : null,
    ]);

    // --- Enviar dados para o serviço de rastreamento externo (UTMY) ---
    $apiKey = 'STpk0rbvVivAj6wBwFZdJOF7uHGJxNl8EOng'; // Sua chave de API
    $utmyEndpoint = 'https://api.utmy.com/v1/track'; // Endpoint hipotético para o serviço

    $payload = [
        'apiKey' => $apiKey,
        'eventType' => $eventType,
        'ipAddress' => $ip,
        'userAgent' => $userAgent,
        'metadata' => $metadata,
        'utm' => $utm
    ];

    $ch = curl_init($utmyEndpoint);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Accept: application/json'
    ]);
    // Descomente a linha abaixo se o serviço usar um cabeçalho de autorização Bearer
    // curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $apiKey]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    // Log da resposta do serviço externo (opcional, bom para depuração)
    if ($httpCode != 200) {
        // Você pode registrar o erro em um arquivo de log se desejar
        error_log("Erro ao enviar dados para UTMFY: HTTP {$httpCode} - Resposta: {$response}");
    }
    // --- Fim do envio para serviço externo ---

    echo json_encode(['status' => 'success', 'message' => 'Event tracked locally and sent to external service']);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => 'Internal Server Error', 'error' => $e->getMessage()]);
}
?>
