<?php
/**
 * TESTE DE UTMs
 * Acesse: api/test-utm.php
 * Envia um JSON de teste para verificar se as UTMs estão sendo recebidas
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

// Simula o input que vem do pagamento.html
$testInput = [
    'nome' => 'Teste Usuario',
    'cpf' => '12345678901',
    'email' => 'teste@teste.com',
    'telefone' => '11999999999',
    'cotas' => 1,
    'valor' => 3990,
    'utm_source' => 'facebook',
    'utm_medium' => 'cpc',
    'utm_campaign' => 'mega_virada_2025',
    'utm_content' => 'video_01',
    'utm_term' => 'bolao',
    'sck' => 'abc123',
    'src' => 'fb_ads',
    'fbc' => 'fb.1.1234567890.abcdef',
    'fbp' => 'fb.1.1234567890.123456789'
];

// Simula a lógica do pix.php
$cliente = $testInput['cliente'] ?? null;

if ($cliente) {
    $tracking = $testInput['tracking'] ?? [];
} else {
    // Formato novo: campos diretos
    if (isset($testInput['tracking']) && is_array($testInput['tracking']) && !empty($testInput['tracking'])) {
        $tracking = $testInput['tracking'];
    } else {
        // Campos individuais enviados diretamente no body
        $tracking = [
            'utm_source' => $testInput['utm_source'] ?? '',
            'utm_medium' => $testInput['utm_medium'] ?? '',
            'utm_campaign' => $testInput['utm_campaign'] ?? '',
            'utm_content' => $testInput['utm_content'] ?? '',
            'utm_term' => $testInput['utm_term'] ?? '',
            'sck' => $testInput['sck'] ?? '',
            'src' => $testInput['src'] ?? '',
            'fbc' => $testInput['fbc'] ?? '',
            'fbp' => $testInput['fbp'] ?? ''
        ];
    }
}

echo json_encode([
    'status' => 'OK',
    'message' => 'Teste de captura de UTMs',
    'input_recebido' => $testInput,
    'tracking_extraido' => $tracking,
    'verificacao' => [
        'utm_source_ok' => !empty($tracking['utm_source']),
        'utm_medium_ok' => !empty($tracking['utm_medium']),
        'utm_campaign_ok' => !empty($tracking['utm_campaign']),
        'sck_ok' => !empty($tracking['sck']),
        'fbc_ok' => !empty($tracking['fbc']),
        'fbp_ok' => !empty($tracking['fbp'])
    ]
], JSON_PRETTY_PRINT);