<?php
// save-utm.php
session_start();

if (!defined('BASE_PATH')) {
    define('BASE_PATH', dirname(__FILE__));
}

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

// Responde a requisições OPTIONS (preflight)
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

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

try {
    // Carrega funções se existirem
    if (file_exists('includes/functions.php')) {
        require_once 'includes/functions.php';
    }
    
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    
    if ($data && !empty($data['utm_campaign'])) {
        // Sanitiza os dados se a função existir
        if (function_exists('sanitizeInput')) {
            $_SESSION['utm_params'] = [
                'utm_campaign' => sanitizeInput($data['utm_campaign']),
                'utm_source' => sanitizeInput($data['utm_source'] ?? ''),
                'utm_medium' => sanitizeInput($data['utm_medium'] ?? ''),
                'utm_term' => sanitizeInput($data['utm_term'] ?? ''),
                'utm_content' => sanitizeInput($data['utm_content'] ?? '')
            ];
        } else {
            // Sanitização básica
            $_SESSION['utm_params'] = [
                'utm_campaign' => htmlspecialchars(trim($data['utm_campaign'])),
                'utm_source' => htmlspecialchars(trim($data['utm_source'] ?? '')),
                'utm_medium' => htmlspecialchars(trim($data['utm_medium'] ?? '')),
                'utm_term' => htmlspecialchars(trim($data['utm_term'] ?? '')),
                'utm_content' => htmlspecialchars(trim($data['utm_content'] ?? ''))
            ];
        }
        
        $_SESSION['utm_timestamp'] = time();
        
        // Log se a função existir
        if (function_exists('logInfo')) {
            logInfo("UTM parameters saved: " . $data['utm_campaign']);
        }
        
        echo json_encode(['success' => true, 'utm_campaign' => $data['utm_campaign']]);
    } else {
        echo json_encode(['error' => 'Invalid data or missing utm_campaign']);
    }
} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
?>