<?php
// api/analytics.php - API Completa de Rastreamento para Relatórios

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

// Define BASE_PATH se não estiver definido
if (!defined('BASE_PATH')) {
    define('BASE_PATH', dirname(dirname(__FILE__)));
}

require_once BASE_PATH . '/includes/config.php';
require_once BASE_PATH . '/includes/db.php';
require_once BASE_PATH . '/includes/functions.php';
require_once BASE_PATH . '/includes/visitor-tracking.php';

/**
 * Classe principal para Analytics
 */
class AnalyticsAPI {
    private $db;
    private $visitorHash;
    private $clientIP;
    private $userAgent;
    private $sessionId;
    
    public function __construct() {
        global $db;
        $this->db = $db;
        $this->clientIP = $this->getClientIP();
        $this->userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
        $this->visitorHash = $this->generateVisitorHash();
        $this->sessionId = $this->getOrCreateSessionId();
    }
    
    /**
     * Gera hash único do visitante
     */
    private function generateVisitorHash() {
        $fingerprint = $this->clientIP . '-' . $this->userAgent;
        
        if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
            $fingerprint .= '-' . $_SERVER['HTTP_ACCEPT_LANGUAGE'];
        }
        
        return hash('sha256', $fingerprint);
    }
    
    /**
     * Obtém IP real do cliente
     */
    private function getClientIP() {
        $ipKeys = [
            'HTTP_CF_CONNECTING_IP',
            'HTTP_CLIENT_IP',
            'HTTP_X_FORWARDED_FOR',
            'HTTP_X_FORWARDED',
            'HTTP_X_CLUSTER_CLIENT_IP',
            'HTTP_FORWARDED_FOR',
            'HTTP_FORWARDED',
            'REMOTE_ADDR'
        ];
        
        foreach ($ipKeys as $key) {
            if (array_key_exists($key, $_SERVER) === true) {
                $ip = $_SERVER[$key];
                if (strpos($ip, ',') !== false) {
                    $ip = explode(',', $ip)[0];
                }
                $ip = trim($ip);
                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {
                    return $ip;
                }
            }
        }
        
        return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    }
    
    /**
     * Obtém ou cria ID da sessão
     */
    private function getOrCreateSessionId() {
        // Verifica se existe uma sessão ativa (últimos 30 minutos)
        $this->db->query("SELECT session_id FROM user_sessions 
                         WHERE visitor_hash = :visitor_hash 
                         AND ended_at IS NULL 
                         AND started_at > DATE_SUB(NOW(), INTERVAL 30 MINUTE) 
                         ORDER BY started_at DESC LIMIT 1");
        $this->db->bind(':visitor_hash', $this->visitorHash);
        $result = $this->db->single();
        
        if ($result) {
            return $result['session_id'];
        }
        
        // Cria nova sessão
        return $this->createNewSession();
    }
    
    /**
     * Cria nova sessão
     */
    private function createNewSession() {
        $sessionId = bin2hex(random_bytes(32));
        $referrer = $_SERVER['HTTP_REFERER'] ?? null;
        $source = $this->extractTrafficSource($referrer);
        
        $this->db->query("INSERT INTO user_sessions 
                         (session_id, visitor_hash, source, medium, referrer, device_type, browser, os, started_at) 
                         VALUES (:session_id, :visitor_hash, :source, :medium, :referrer, :device_type, :browser, :os, NOW())");
        
        $this->db->bind(':session_id', $sessionId);
        $this->db->bind(':visitor_hash', $this->visitorHash);
        $this->db->bind(':source', $source['source']);
        $this->db->bind(':medium', $source['medium']);
        $this->db->bind(':referrer', $referrer);
        $this->db->bind(':device_type', $this->detectDeviceType());
        $this->db->bind(':browser', $this->detectBrowser());
        $this->db->bind(':os', $this->detectOS());
        
        $this->db->execute();
        
        return $sessionId;
    }
    
    /**
     * Extrai fonte de tráfego
     */
    private function extractTrafficSource($referrer) {
        if (empty($referrer)) {
            return ['source' => 'direct', 'medium' => 'none'];
        }
        
        $domain = parse_url($referrer, PHP_URL_HOST);
        
        // Redes sociais
        $socialNetworks = [
            'facebook.com' => 'facebook',
            'twitter.com' => 'twitter',
            'instagram.com' => 'instagram',
            'linkedin.com' => 'linkedin',
            'youtube.com' => 'youtube',
            'tiktok.com' => 'tiktok'
        ];
        
        foreach ($socialNetworks as $network => $name) {
            if (strpos($domain, $network) !== false) {
                return ['source' => $name, 'medium' => 'social'];
            }
        }
        
        // Mecanismos de busca
        $searchEngines = [
            'google.' => 'google',
            'bing.com' => 'bing',
            'yahoo.com' => 'yahoo',
            'duckduckgo.com' => 'duckduckgo'
        ];
        
        foreach ($searchEngines as $engine => $name) {
            if (strpos($domain, $engine) !== false) {
                return ['source' => $name, 'medium' => 'organic'];
            }
        }
        
        return ['source' => $domain, 'medium' => 'referral'];
    }
    
    /**
     * Detecta tipo de dispositivo
     */
    private function detectDeviceType() {
        if (preg_match('/mobile|android|iphone/i', $this->userAgent)) {
            return 'mobile';
        } elseif (preg_match('/tablet|ipad/i', $this->userAgent)) {
            return 'tablet';
        }
        return 'desktop';
    }
    
    /**
     * Detecta navegador
     */
    private function detectBrowser() {
        if (preg_match('/Chrome/i', $this->userAgent)) return 'Chrome';
        if (preg_match('/Firefox/i', $this->userAgent)) return 'Firefox';
        if (preg_match('/Safari/i', $this->userAgent)) return 'Safari';
        if (preg_match('/Edge/i', $this->userAgent)) return 'Edge';
        if (preg_match('/Opera/i', $this->userAgent)) return 'Opera';
        return 'Unknown';
    }
    
    /**
     * Detecta sistema operacional
     */
    private function detectOS() {
        if (preg_match('/Windows/i', $this->userAgent)) return 'Windows';
        if (preg_match('/Mac/i', $this->userAgent)) return 'macOS';
        if (preg_match('/Linux/i', $this->userAgent)) return 'Linux';
        if (preg_match('/Android/i', $this->userAgent)) return 'Android';
        if (preg_match('/iOS/i', $this->userAgent)) return 'iOS';
        return 'Unknown';
    }
    
    /**
     * Registra visualização de página
     */
    public function trackPageView($data) {
        $pageId = isset($data['page_id']) ? intval($data['page_id']) : 0;
        $pageUrl = isset($data['page_url']) ? $data['page_url'] : '';
        $pageTitle = isset($data['page_title']) ? $data['page_title'] : '';
        
        if ($pageId <= 0) {
            throw new Exception('ID da página é obrigatório');
        }
        
        // Verificar se a página existe
        $this->db->query("SELECT id, title, type FROM pages WHERE id = :page_id");
        $this->db->bind(':page_id', $pageId);
        $page = $this->db->single();
        
        if (!$page) {
            throw new Exception('Página não encontrada');
        }
        
        $currentDate = date('Y-m-d');
        $currentDateTime = date('Y-m-d H:i:s');
        
        // 1. Registrar visitante único
        $isNewUniqueVisit = $this->trackUniqueVisitor($pageId, $currentDate, $currentDateTime);
        
        // 2. Registrar view completa
        $this->db->query("INSERT INTO page_views 
                         (page_id, visitor_ip, visitor_hash, session_date, user_agent, referrer, viewed_at) 
                         VALUES (:page_id, :visitor_ip, :visitor_hash, :session_date, :user_agent, :referrer, NOW())");
        
        $this->db->bind(':page_id', $pageId);
        $this->db->bind(':visitor_ip', $this->clientIP);
        $this->db->bind(':visitor_hash', $this->visitorHash);
        $this->db->bind(':session_date', $currentDate);
        $this->db->bind(':user_agent', $this->userAgent);
        $this->db->bind(':referrer', $_SERVER['HTTP_REFERER'] ?? null);
        
        $this->db->execute();
        $viewId = $this->db->lastInsertId();
        
        // 3. Atualizar sessão
        $this->updateSession($pageId, $isNewUniqueVisit);
        
        return [
            'success' => true,
            'view_id' => $viewId,
            'is_new_unique_visit' => $isNewUniqueVisit,
            'visitor_hash' => $this->visitorHash,
            'session_id' => $this->sessionId
        ];
    }
    
    /**
     * Registra visitante único
     */
    private function trackUniqueVisitor($pageId, $currentDate, $currentDateTime) {
        // Verificar se já visitou hoje
        $this->db->query("SELECT id, visit_count FROM unique_page_visitors 
                         WHERE page_id = :page_id 
                         AND visitor_hash = :visitor_hash 
                         AND visit_date = :visit_date");
        
        $this->db->bind(':page_id', $pageId);
        $this->db->bind(':visitor_hash', $this->visitorHash);
        $this->db->bind(':visit_date', $currentDate);
        
        $existing = $this->db->single();
        
        if ($existing) {
            // Atualizar visita existente
            $this->db->query("UPDATE unique_page_visitors 
                             SET last_visit_time = :last_visit_time, 
                                 visit_count = visit_count + 1 
                             WHERE id = :id");
            
            $this->db->bind(':last_visit_time', $currentDateTime);
            $this->db->bind(':id', $existing['id']);
            $this->db->execute();
            
            return false; // Não é nova visita única
        } else {
            // Nova visita única
            $this->db->query("INSERT INTO unique_page_visitors 
                             (page_id, visitor_hash, visit_date, first_visit_time, last_visit_time, visit_count) 
                             VALUES (:page_id, :visitor_hash, :visit_date, :first_visit_time, :last_visit_time, 1)");
            
            $this->db->bind(':page_id', $pageId);
            $this->db->bind(':visitor_hash', $this->visitorHash);
            $this->db->bind(':visit_date', $currentDate);
            $this->db->bind(':first_visit_time', $currentDateTime);
            $this->db->bind(':last_visit_time', $currentDateTime);
            $this->db->execute();
            
            return true; // Nova visita única
        }
    }
    
    /**
     * Atualiza sessão
     */
    private function updateSession($pageId, $isNewPage = false) {
        // Buscar sessão atual
        $this->db->query("SELECT id, first_page_id, pages_visited FROM user_sessions 
                         WHERE session_id = :session_id");
        $this->db->bind(':session_id', $this->sessionId);
        $session = $this->db->single();
        
        if ($session) {
            $updates = "last_page_id = :page_id";
            $params = [':page_id' => $pageId];
            
            // Se é a primeira página da sessão
            if (empty($session['first_page_id'])) {
                $updates .= ", first_page_id = :first_page_id";
                $params[':first_page_id'] = $pageId;
            }
            
            // Incrementar páginas visitadas se for nova página
            if ($isNewPage) {
                $updates .= ", pages_visited = pages_visited + 1";
            }
            
            $this->db->query("UPDATE user_sessions SET {$updates} WHERE id = :session_id");
            foreach ($params as $key => $value) {
                $this->db->bind($key, $value);
            }
            $this->db->bind(':session_id', $session['id']);
            $this->db->execute();
        }
    }
    
    /**
     * Registra engajamento
     */
    public function trackEngagement($data) {
        $pageId = isset($data['page_id']) ? intval($data['page_id']) : 0;
        $timeSpent = isset($data['time_spent']) ? intval($data['time_spent']) : 0;
        $maxScroll = isset($data['max_scroll']) ? intval($data['max_scroll']) : 0;
        $isActive = isset($data['is_active']) ? (bool)$data['is_active'] : true;
        
        if ($pageId <= 0) {
            throw new Exception('ID da página é obrigatório');
        }
        
        $currentDate = date('Y-m-d');
        
        // Verificar engagement existente hoje
        $this->db->query("SELECT id, time_spent, max_scroll FROM page_engagement 
                         WHERE page_id = :page_id 
                         AND visitor_hash = :visitor_hash 
                         AND DATE(created_at) = :current_date
                         ORDER BY created_at DESC LIMIT 1");
        
        $this->db->bind(':page_id', $pageId);
        $this->db->bind(':visitor_hash', $this->visitorHash);
        $this->db->bind(':current_date', $currentDate);
        
        $existing = $this->db->single();
        
        if ($existing) {
            // Atualizar se os valores forem maiores
            $newTimeSpent = max($existing['time_spent'], $timeSpent);
            $newMaxScroll = max($existing['max_scroll'], $maxScroll);
            
            $this->db->query("UPDATE page_engagement 
                             SET time_spent = :time_spent,
                                 max_scroll = :max_scroll,
                                 scroll_depth_25 = :scroll_25,
                                 scroll_depth_50 = :scroll_50,
                                 scroll_depth_75 = :scroll_75,
                                 scroll_depth_100 = :scroll_100,
                                 is_active = :is_active,
                                 updated_at = NOW()
                             WHERE id = :id");
            
            $this->db->bind(':time_spent', $newTimeSpent);
            $this->db->bind(':max_scroll', $newMaxScroll);
            $this->db->bind(':scroll_25', $newMaxScroll >= 25 ? 1 : 0);
            $this->db->bind(':scroll_50', $newMaxScroll >= 50 ? 1 : 0);
            $this->db->bind(':scroll_75', $newMaxScroll >= 75 ? 1 : 0);
            $this->db->bind(':scroll_100', $newMaxScroll >= 100 ? 1 : 0);
            $this->db->bind(':is_active', $isActive ? 1 : 0);
            $this->db->bind(':id', $existing['id']);
            
            $this->db->execute();
            $engagementId = $existing['id'];
        } else {
            // Criar novo registro
            $this->db->query("INSERT INTO page_engagement 
                             (page_id, visitor_hash, visitor_ip, time_spent, max_scroll, 
                              scroll_depth_25, scroll_depth_50, scroll_depth_75, scroll_depth_100,
                              is_active, user_agent, created_at)
                             VALUES (:page_id, :visitor_hash, :visitor_ip, :time_spent, :max_scroll,
                                     :scroll_25, :scroll_50, :scroll_75, :scroll_100,
                                     :is_active, :user_agent, NOW())");
            
            $this->db->bind(':page_id', $pageId);
            $this->db->bind(':visitor_hash', $this->visitorHash);
            $this->db->bind(':visitor_ip', $this->clientIP);
            $this->db->bind(':time_spent', $timeSpent);
            $this->db->bind(':max_scroll', $maxScroll);
            $this->db->bind(':scroll_25', $maxScroll >= 25 ? 1 : 0);
            $this->db->bind(':scroll_50', $maxScroll >= 50 ? 1 : 0);
            $this->db->bind(':scroll_75', $maxScroll >= 75 ? 1 : 0);
            $this->db->bind(':scroll_100', $maxScroll >= 100 ? 1 : 0);
            $this->db->bind(':is_active', $isActive ? 1 : 0);
            $this->db->bind(':user_agent', $this->userAgent);
            
            $this->db->execute();
            $engagementId = $this->db->lastInsertId();
        }
        
        return [
            'success' => true,
            'engagement_id' => $engagementId,
            'time_spent' => $timeSpent,
            'max_scroll' => $maxScroll
        ];
    }
    
    /**
     * Registra ação específica
     */
    public function trackAction($data) {
        $pageId = isset($data['page_id']) ? intval($data['page_id']) : 0;
        $actionType = isset($data['action_type']) ? $data['action_type'] : '';
        $actionTarget = isset($data['action_target']) ? $data['action_target'] : '';
        $targetUrl = isset($data['target_url']) ? $data['target_url'] : '';
        $timeSpent = isset($data['time_spent']) ? intval($data['time_spent']) : 0;
        $maxScroll = isset($data['max_scroll']) ? intval($data['max_scroll']) : 0;
        
        if ($pageId <= 0 || empty($actionType)) {
            throw new Exception('ID da página e tipo de ação são obrigatórios');
        }
        
        $this->db->query("INSERT INTO page_actions 
                         (page_id, visitor_hash, visitor_ip, action_type, action_target, target_url, 
                          time_spent, max_scroll, user_agent, created_at)
                         VALUES (:page_id, :visitor_hash, :visitor_ip, :action_type, :action_target, :target_url,
                                 :time_spent, :max_scroll, :user_agent, NOW())");
        
        $this->db->bind(':page_id', $pageId);
        $this->db->bind(':visitor_hash', $this->visitorHash);
        $this->db->bind(':visitor_ip', $this->clientIP);
        $this->db->bind(':action_type', $actionType);
        $this->db->bind(':action_target', $actionTarget);
        $this->db->bind(':target_url', $targetUrl);
        $this->db->bind(':time_spent', $timeSpent);
        $this->db->bind(':max_scroll', $maxScroll);
        $this->db->bind(':user_agent', $this->userAgent);
        
        $this->db->execute();
        $actionId = $this->db->lastInsertId();
        
        // Se for uma conversão, registrar no tracking de conversões
        if (in_array($actionType, ['cta-click', 'next-step', 'registration', 'purchase'])) {
            $this->trackConversion($pageId, $actionType);
        }
        
        return [
            'success' => true,
            'action_id' => $actionId,
            'action_type' => $actionType
        ];
    }
    
    /**
     * Registra conversão
     */
    private function trackConversion($pageId, $conversionType) {
        // Buscar landing page da sessão
        $this->db->query("SELECT first_page_id FROM user_sessions WHERE session_id = :session_id");
        $this->db->bind(':session_id', $this->sessionId);
        $session = $this->db->single();
        
        $landingPageId = $session ? $session['first_page_id'] : $pageId;
        
        // Determinar etapa do funil
        $this->db->query("SELECT type FROM pages WHERE id = :page_id");
        $this->db->bind(':page_id', $pageId);
        $page = $this->db->single();
        
        $funnelStep = 1;
        if ($page) {
            switch ($page['type']) {
                case 'landing': $funnelStep = 1; break;
                case 'step1': $funnelStep = 2; break;
                case 'step2': $funnelStep = 3; break;
                case 'step3': $funnelStep = 4; break;
                case 'registration': $funnelStep = 5; break;
            }
        }
        
        $this->db->query("INSERT INTO conversion_tracking 
                         (visitor_hash, landing_page_id, current_page_id, conversion_type, 
                          funnel_step, source, medium, converted_at)
                         SELECT :visitor_hash, :landing_page_id, :current_page_id, :conversion_type,
                                :funnel_step, us.source, us.medium, NOW()
                         FROM user_sessions us 
                         WHERE us.session_id = :session_id");
        
        $this->db->bind(':visitor_hash', $this->visitorHash);
        $this->db->bind(':landing_page_id', $landingPageId);
        $this->db->bind(':current_page_id', $pageId);
        $this->db->bind(':conversion_type', $conversionType);
        $this->db->bind(':funnel_step', $funnelStep);
        $this->db->bind(':session_id', $this->sessionId);
        
        $this->db->execute();
        
        // Marcar sessão como tendo conversão
        $this->db->query("UPDATE user_sessions SET has_conversion = 1 WHERE session_id = :session_id");
        $this->db->bind(':session_id', $this->sessionId);
        $this->db->execute();
    }
    
    /**
     * Registra evento customizado
     */
    public function trackCustomEvent($data) {
        $pageId = isset($data['page_id']) ? intval($data['page_id']) : null;
        $eventCategory = isset($data['event_category']) ? $data['event_category'] : '';
        $eventAction = isset($data['event_action']) ? $data['event_action'] : '';
        $eventLabel = isset($data['event_label']) ? $data['event_label'] : null;
        $eventValue = isset($data['event_value']) ? intval($data['event_value']) : null;
        $customData = isset($data['custom_data']) ? $data['custom_data'] : null;
        
        if (empty($eventCategory) || empty($eventAction)) {
            throw new Exception('Categoria e ação do evento são obrigatórios');
        }
        
        $this->db->query("INSERT INTO custom_events 
                         (page_id, visitor_hash, event_category, event_action, event_label, 
                          event_value, custom_data, created_at)
                         VALUES (:page_id, :visitor_hash, :event_category, :event_action, :event_label,
                                 :event_value, :custom_data, NOW())");
        
        $this->db->bind(':page_id', $pageId);
        $this->db->bind(':visitor_hash', $this->visitorHash);
        $this->db->bind(':event_category', $eventCategory);
        $this->db->bind(':event_action', $eventAction);
        $this->db->bind(':event_label', $eventLabel);
        $this->db->bind(':event_value', $eventValue);
        $this->db->bind(':custom_data', $customData ? json_encode($customData) : null);
        
        $this->db->execute();
        
        return [
            'success' => true,
            'event_id' => $this->db->lastInsertId()
        ];
    }
    
    /**
     * Finaliza sessão
     */
    public function endSession($data) {
        $totalTimeSpent = isset($data['total_time_spent']) ? intval($data['total_time_spent']) : 0;
        $pagesVisited = isset($data['pages_visited']) ? intval($data['pages_visited']) : 1;
        
        // Determinar se foi bounce (visitou apenas uma página)
        $isBounce = $pagesVisited <= 1 ? 1 : 0;
        
        $this->db->query("UPDATE user_sessions 
                         SET ended_at = NOW(),
                             total_time_spent = :total_time_spent,
                             is_bounce = :is_bounce
                         WHERE session_id = :session_id");
        
        $this->db->bind(':total_time_spent', $totalTimeSpent);
        $this->db->bind(':is_bounce', $isBounce);
        $this->db->bind(':session_id', $this->sessionId);
        
        $this->db->execute();
        
        return [
            'success' => true,
            'session_ended' => true
        ];
    }
}

// Processar requisição
try {
    // Só aceitar POST (exceto para status)
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        http_response_code(200);
        exit;
    }
    
    if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['action']) && $_GET['action'] === 'status') {
        echo json_encode([
            'success' => true,
            'status' => 'API Analytics ativa',
            'timestamp' => date('Y-m-d H:i:s'),
            'version' => '1.0.0'
        ]);
        exit;
    }
    
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['error' => 'Método não permitido']);
        exit;
    }
    
    // Obter dados da requisição
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        throw new Exception('Dados inválidos');
    }
    
    $action = isset($input['action']) ? $input['action'] : '';
    
    if (empty($action)) {
        throw new Exception('Ação não especificada');
    }
    
    // Instanciar API
    $analytics = new AnalyticsAPI();
    
    // Processar ação
    switch ($action) {
        case 'page_view':
            $result = $analytics->trackPageView($input);
            break;
            
        case 'engagement':
            $result = $analytics->trackEngagement($input);
            break;
            
        case 'action':
            $result = $analytics->trackAction($input);
            break;
            
        case 'custom_event':
            $result = $analytics->trackCustomEvent($input);
            break;
            
        case 'end_session':
            $result = $analytics->endSession($input);
            break;
            
        default:
            throw new Exception('Ação não reconhecida: ' . $action);
    }
    
    echo json_encode($result);
    
} catch (Exception $e) {
    logError("Erro na API Analytics: " . $e->getMessage());
    
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>

<!-- 
JavaScript Cliente para usar com a API

<script>
class AnalyticsTracker {
    constructor(baseUrl = '/api/analytics.php') {
        this.baseUrl = baseUrl;
        this.sessionData = {
            startTime: Date.now(),
            pageStartTime: Date.now(),
            maxScroll: 0,
            isActive: true,
            pageId: null,
            totalTimeSpent: 0
        };
        
        this.init();
    }
    
    init() {
        // Detectar quando a página perde/ganha foco
        document.addEventListener('visibilitychange', () => {
            this.sessionData.isActive = !document.hidden;
        });
        
        // Rastrear scroll
        window.addEventListener('scroll', () => {
            const scrollPercent = Math.round(
                (window.scrollY / (document.body.scrollHeight - window.innerHeight)) * 100
            );
            this.sessionData.maxScroll = Math.max(this.sessionData.maxScroll, scrollPercent);
        });
        
        // Enviar dados ao sair da página
        window.addEventListener('beforeunload', () => {
            this.endSession();
        });
        
        // Enviar engajamento periodicamente
        setInterval(() => {
            this.sendEngagement();
        }, 30000); // A cada 30 segundos
    }
    
    async trackPageView(pageId, pageUrl = window.location.href, pageTitle = document.title) {
        this.sessionData.pageId = pageId;
        this.sessionData.pageStartTime = Date.now();
        
        return this.sendData({
            action: 'page_view',
            page_id: pageId,
            page_url: pageUrl,
            page_title: pageTitle
        });
    }
    
    async trackAction(actionType, actionTarget = '', targetUrl = '') {
        const timeSpent = Math.round((Date.now() - this.sessionData.pageStartTime) / 1000);
        
        return this.sendData({
            action: 'action',
            page_id: this.sessionData.pageId,
            action_type: actionType,
            action_target: actionTarget,
            target_url: targetUrl,
            time_spent: timeSpent,
            max_scroll: this.sessionData.maxScroll
        });
    }
    
    async trackCustomEvent(category, action, label = null, value = null, customData = null) {
        return this.sendData({
            action: 'custom_event',
            page_id: this.sessionData.pageId,
            event_category: category,
            event_action: action,
            event_label: label,
            event_value: value,
            custom_data: customData
        });
    }
    
    async sendEngagement() {
        if (!this.sessionData.pageId) return;
        
        const timeSpent = Math.round((Date.now() - this.sessionData.pageStartTime) / 1000);
        
        return this.sendData({
            action: 'engagement',
            page_id: this.sessionData.pageId,
            time_spent: timeSpent,
            max_scroll: this.sessionData.maxScroll,
            is_active: this.sessionData.isActive
        });
    }
    
    async endSession() {
        const totalTimeSpent = Math.round((Date.now() - this.sessionData.startTime) / 1000);
        
        // Usar sendBeacon para garantir que seja enviado
        if (navigator.sendBeacon) {
            const data = JSON.stringify({
                action: 'end_session',
                total_time_spent: totalTimeSpent
            });
            
            navigator.sendBeacon(this.baseUrl, data);
        } else {
            return this.sendData({
                action: 'end_session',
                total_time_spent: totalTimeSpent
            });
        }
    }
    
    async sendData(data) {
        try {
            const response = await fetch(this.baseUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            });
            
            return await response.json();
        } catch (error) {
            console.error('Erro no tracking:', error);
            return { success: false, error: error.message };
        }
    }
}

// Uso do tracker
const tracker = new AnalyticsTracker();

// Rastrear visualização da página (chamado quando a página carrega)
tracker.trackPageView(PAGE_ID); // Definir PAGE_ID globalmente

// Rastrear cliques em CTAs
document.querySelectorAll('[data-track-action]').forEach(element => {
    element.addEventListener('click', function(e) {
        const actionType = this.getAttribute('data-track-action');
        const actionTarget = this.getAttribute('data-track-target') || this.innerText;
        const targetUrl = this.href || this.getAttribute('data-target-url');
        
        tracker.trackAction(actionType, actionTarget, targetUrl);
    });
});

// Rastrear eventos customizados
function trackCustomEvent(category, action, label, value, customData) {
    tracker.trackCustomEvent(category, action, label, value, customData);
}
</script>
-->