<?php
/**
 * DEBUG - Ver payload enviado ao UTMify
 */

date_default_timezone_set('America/Sao_Paulo');
header('Content-Type: text/plain; charset=utf-8');

require_once __DIR__ . '/utmify.php';

echo "=== DEBUG UTMIFY ===\n\n";

// Verifica configuração
$configFile = __DIR__ . '/utmify_config.json';
if (file_exists($configFile)) {
    $config = json_decode(file_get_contents($configFile), true);
    echo "Token configurado: " . substr($config['api_token'] ?? 'N/A', 0, 10) . "...\n";
    echo "Enabled: " . ($config['enabled'] ? 'Sim' : 'Não') . "\n\n";
} else {
    echo "⚠️ Arquivo utmify_config.json não encontrado!\n\n";
}

// Dados de teste
$orderId = 'teste-' . time();
$amountCents = 1794;

$customer = [
    'name' => 'Teste Debug',
    'email' => 'teste@teste.com',
    'phone' => '11999999999',
    'document' => '12345678900',
    'ip' => '127.0.0.1'
];

$product = [
    'id' => 'premios-001',
    'name' => 'Prêmios do Carlinhos',
    'quantity' => 6
];

$utms = [
    'sck' => '',
    'src' => '',
    'utm_source' => 'FB',
    'utm_medium' => 'teste',
    'utm_campaign' => 'teste-debug',
    'utm_content' => '',
    'utm_term' => ''
];

// Monta o payload igual a classe Utmify
$payload = [
    'orderId' => (string) $orderId,
    'platform' => 'SmartCheckout',
    'paymentMethod' => 'pix',
    'status' => 'paid',
    'createdAt' => date('Y-m-d H:i:s'),
    'approvedDate' => date('Y-m-d H:i:s'),
    'refundedAt' => null,
    'customer' => [
        'name' => $customer['name'] ?? 'Cliente',
        'email' => $customer['email'] ?? '',
        'phone' => '+55' . preg_replace('/\D/', '', $customer['phone'] ?? ''),
        'document' => preg_replace('/\D/', '', $customer['document'] ?? ''),
        'country' => 'BR',
        'ip' => $customer['ip'] ?? '127.0.0.1'
    ],
    'products' => [[
        'id' => $product['id'] ?? 'produto-001',
        'name' => $product['name'] ?? 'Produto',
        'planId' => null,
        'planName' => null,
        'quantity' => (int) ($product['quantity'] ?? 1),
        'priceInCents' => (int) $amountCents
    ]],
    'trackingParameters' => [
        'src' => (string) ($utms['src'] ?? ''),
        'sck' => (string) ($utms['sck'] ?? ''),
        'utm_source' => (string) ($utms['utm_source'] ?? ''),
        'utm_medium' => (string) ($utms['utm_medium'] ?? ''),
        'utm_campaign' => (string) ($utms['utm_campaign'] ?? ''),
        'utm_content' => (string) ($utms['utm_content'] ?? ''),
        'utm_term' => (string) ($utms['utm_term'] ?? '')
    ],
    'commission' => [
        'totalPriceInCents' => (int) $amountCents,
        'gatewayFeeInCents' => 0,
        'userCommissionInCents' => (int) $amountCents
    ],
    'isTest' => false
];

echo "=== PAYLOAD QUE SERÁ ENVIADO ===\n";
echo json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n\n";

echo "=== ENVIANDO PARA UTMIFY ===\n";

$utmify = new Utmify();

if (!$utmify->isConfigured()) {
    echo "❌ UTMify NÃO está configurado!\n";
    echo "Verifique o token em utmify_config.json\n";
    exit;
}

$result = $utmify->sendPaid($orderId, $amountCents, $customer, $product, $utms);

echo "\n=== RESULTADO ===\n";
echo "Success: " . ($result['success'] ? 'Sim' : 'Não') . "\n";
echo "HTTP Code: " . ($result['http_code'] ?? 'N/A') . "\n";
echo "Response: " . json_encode($result['response'] ?? null, JSON_PRETTY_PRINT) . "\n";

echo "\n=== VERIFIQUE NO UTMIFY ===\n";
echo "1. Vá no painel do UTMify\n";
echo "2. Procure pelo pedido: $orderId\n";
echo "3. Se não aparecer, o problema é:\n";
echo "   - Token inválido\n";
echo "   - Produto não cadastrado\n";
echo "   - Conta com problema\n";