<?php
// includes/track.php
// Endpoint para tracking de conversões

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

// Inclui sistema de tracking UTM
if (file_exists(BASE_PATH . '/includes/utm-tracking.php')) {
    require_once BASE_PATH . '/includes/utm-tracking.php';
}

// Headers para JSON
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');

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

try {
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    
    // Fallback para POST tradicional
    if (!$data) {
        $data = $_POST;
    }
    
    if (!isset($data['action'])) {
        throw new Exception('Ação não especificada');
    }
    
    $action = $data['action'];
    $pageId = intval($data['page_id'] ?? 0);
    $tipo = sanitizeInput($data['tipo'] ?? '');
    
    // Coleta UTMs enviados
    $utmData = $data['utm_data'] ?? [];
    
    // Adiciona dados da requisição
    $additionalData = [
        'action_type' => $tipo,
        'referrer' => $data['referrer'] ?? $_SERVER['HTTP_REFERER'] ?? '',
        'timestamp' => $data['timestamp'] ?? time(),
        'ip' => $_SERVER['REMOTE_ADDR'] ?? '',
        'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? ''
    ];
    
    // Mescla UTMs da sessão com UTMs enviados
    if (function_exists('getUtmParams')) {
        $sessionUtms = getUtmParams();
        $utmData = array_merge($sessionUtms, $utmData);
    }
    
    $result = false;
    
    switch ($action) {
        case 'redirect':
        case 'conversion':
            if (function_exists('registerConversion')) {
                // Adiciona UTMs aos dados adicionais
                $additionalData = array_merge($additionalData, $utmData);
                $result = registerConversion($pageId, $tipo, $additionalData);
            }
            break;
            
        case 'step_navigation':
            if (function_exists('registerConversion')) {
                $additionalData['from_step'] = $data['from'] ?? '';
                $additionalData['to_step'] = $data['to'] ?? '';
                $additionalData = array_merge($additionalData, $utmData);
                $result = registerConversion($pageId, 'step_navigation', $additionalData);
            }
            break;
            
        default:
            throw new Exception('Ação inválida: ' . $action);
    }
    
    // Resposta de sucesso
    echo json_encode([
        'success' => true,
        'result' => $result,
        'message' => 'Tracking registrado com sucesso',
        'debug' => [
            'action' => $action,
            'page_id' => $pageId,
            'tipo' => $tipo,
            'utm_count' => count($utmData),
            'has_utm_function' => function_exists('registerConversion')
        ]
    ]);
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage(),
        'debug' => [
            'input_data' => $data ?? null,
            'post_data' => $_POST,
            'file_exists' => file_exists(BASE_PATH . '/includes/utm-tracking.php')
        ]
    ]);
    
    // Log do erro
    if (function_exists('logError')) {
        logError("Erro no tracking: " . $e->getMessage());
    }
}
?>