<?php
// track.php
// Sistema de rastreamento para analytics

session_start();
require_once 'includes/config.php';
require_once 'includes/db.php';
require_once 'includes/functions.php';

// Verifica se é uma requisição POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit;
}

$action = isset($_POST['action']) ? $_POST['action'] : '';

try {
    switch ($action) {
        case 'track_time':
            $page_id = isset($_POST['page_id']) ? intval($_POST['page_id']) : 0;
            $time_on_page = isset($_POST['time_on_page']) ? intval($_POST['time_on_page']) : 0;
            
            if ($page_id > 0 && $time_on_page > 0) {
                $session_id = session_id();
                $visitor_ip = $_SERVER['REMOTE_ADDR'];
                
                // Atualiza tempo na página na visualização mais recente
                $db->query("UPDATE page_views 
                           SET time_on_page = :time_on_page 
                           WHERE page_id = :page_id 
                           AND visitor_ip = :visitor_ip 
                           ORDER BY viewed_at DESC 
                           LIMIT 1");
                $db->bind(':time_on_page', $time_on_page);
                $db->bind(':page_id', $page_id);
                $db->bind(':visitor_ip', $visitor_ip);
                $db->execute();
            }
            break;
            
        case 'track_scroll':
            $page_id = isset($_POST['page_id']) ? intval($_POST['page_id']) : 0;
            $scroll_percentage = isset($_POST['scroll_percentage']) ? intval($_POST['scroll_percentage']) : 0;
            
            if ($page_id > 0) {
                $session_id = session_id();
                $visitor_ip = $_SERVER['REMOTE_ADDR'];
                
                $db->query("UPDATE page_views 
                           SET max_scroll_percentage = GREATEST(COALESCE(max_scroll_percentage, 0), :scroll_percentage)
                           WHERE page_id = :page_id 
                           AND visitor_ip = :visitor_ip 
                           ORDER BY viewed_at DESC 
                           LIMIT 1");
                $db->bind(':scroll_percentage', $scroll_percentage);
                $db->bind(':page_id', $page_id);
                $db->bind(':visitor_ip', $visitor_ip);
                $db->execute();
            }
            break;
            
        case 'track_engagement':
            $page_id = isset($_POST['page_id']) ? intval($_POST['page_id']) : 0;
            $engagement_type = isset($_POST['engagement_type']) ? $_POST['engagement_type'] : '';
            $engagement_data = isset($_POST['engagement_data']) ? $_POST['engagement_data'] : '';
            
            if ($page_id > 0 && !empty($engagement_type)) {
                $session_id = session_id();
                $visitor_ip = $_SERVER['REMOTE_ADDR'];
                
                $db->query("INSERT INTO page_engagements 
                           (page_id, session_id, visitor_ip, engagement_type, engagement_data, created_at) 
                           VALUES (:page_id, :session_id, :visitor_ip, :engagement_type, :engagement_data, NOW())");
                $db->bind(':page_id', $page_id);
                $db->bind(':session_id', $session_id);
                $db->bind(':visitor_ip', $visitor_ip);
                $db->bind(':engagement_type', $engagement_type);
                $db->bind(':engagement_data', $engagement_data);
                $db->execute();
            }
            break;
    }
    
    echo json_encode(['status' => 'success']);
    
} catch (Exception $e) {
    logError("Erro no rastreamento: " . $e->getMessage());
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>