<?php
/**
 * ============================================
 * WEBHOOK - CONFIRMAÇÃO DE PAGAMENTO
 * ============================================
 * Recebe webhooks de múltiplos gateways (Umbrella, TechByNet)
 * e dispara eventos para Facebook e UTMify
 */

require_once __DIR__ . '/config.php';
@include_once __DIR__ . '/facebook_capi.php';
@include_once __DIR__ . '/utmify.php';

header('Content-Type: application/json');

logCheckout('webhook.log', '=== WEBHOOK RECEBIDO ===');

// Recebe payload
$payload = file_get_contents('php://input');
$data = json_decode($payload, true);

if (!$data) {
    logCheckout('webhook.log', 'Payload inválido', ['raw' => substr($payload, 0, 500)]);
    http_response_code(400);
    echo json_encode(['error' => 'Payload inválido']);
    exit;
}

logCheckout('webhook.log', 'Dados recebidos', $data);

// ============================================
// DETECTA O GATEWAY PELO PAYLOAD
// ============================================
$detectedGateway = detectGateway($data);
logCheckout('webhook.log', "Gateway detectado: $detectedGateway");

// Obtém configuração do gateway
global $GATEWAYS;
$gatewayConfig = $GATEWAYS[$detectedGateway] ?? $GATEWAYS[GATEWAY_ATIVO];

// ============================================
// EXTRAI DADOS CONFORME O GATEWAY
// ============================================
$webhookData = extractWebhookData($data, $detectedGateway);

$orderId = $webhookData['order_id'];
$status = $webhookData['status'];
$amountCents = $webhookData['amount'];
$amount = $amountCents / 100;
$customer = $webhookData['customer'];

// Mapeia status para interno
$statusNorm = mapStatus($status, $gatewayConfig);

logCheckout('webhook.log', 'Dados extraídos', [
    'gateway' => $detectedGateway,
    'order_id' => $orderId,
    'status_api' => $status,
    'status_norm' => $statusNorm,
    'amount' => $amount
]);

// ============================================
// VERIFICA SE É DO PRODUTO CORRETO
// ============================================
$isProdutoCorreto = false;
$savedData = null;
$jsonFile = UTM_STORAGE_DIR . $orderId . '.json';

if (file_exists($jsonFile)) {
    $savedData = json_decode(file_get_contents($jsonFile), true);
    $isProdutoCorreto = true;
    logCheckout('webhook.log', 'JSON encontrado - produto válido');
}

// Verifica também nos produtos do webhook
if (!$isProdutoCorreto && !empty($webhookData['products'])) {
    foreach ($webhookData['products'] as $product) {
        $productTitle = $product['title'] ?? $product['name'] ?? '';
        if (strpos($productTitle, PRODUTO_NOME) !== false) {
            $isProdutoCorreto = true;
            break;
        }
    }
}

if (!$isProdutoCorreto) {
    logCheckout('webhook.log', 'IGNORADO - Produto não permitido');
    http_response_code(200);
    echo json_encode([
        'success' => true,
        'message' => 'Produto não permitido - ignorado',
        'order_id' => $orderId
    ]);
    exit;
}

// ============================================
// PREPARA DADOS DO CLIENTE E UTMs
// ============================================
if ($savedData) {
    $customer = array_merge($customer, $savedData['customer'] ?? []);
    $utms = [
        'utm_source' => $savedData['utm_source'] ?? '',
        'utm_medium' => $savedData['utm_medium'] ?? '',
        'utm_campaign' => $savedData['utm_campaign'] ?? '',
        'utm_content' => $savedData['utm_content'] ?? '',
        'utm_term' => $savedData['utm_term'] ?? '',
        'sck' => $savedData['sck'] ?? '',
        'src' => $savedData['src'] ?? '',
        'fbc' => $savedData['fbc'] ?? '',
        'fbp' => $savedData['fbp'] ?? ''
    ];
    $clientIp = $savedData['customer_ip'] ?? $_SERVER['REMOTE_ADDR'] ?? '';
    $cotas = $savedData['cotas'] ?? 1;
} else {
    $utms = [];
    $clientIp = $_SERVER['REMOTE_ADDR'] ?? '';
    $cotas = 1;
}

// ============================================
// PROCESSA CONFORME STATUS
// ============================================
$results = [
    'fb_purchase' => false,
    'utmify' => false
];

if ($statusNorm === 'paid') {
    logCheckout('webhook.log', 'Processando PAGAMENTO CONFIRMADO');
    
    // Facebook Purchase
    if (class_exists('FacebookCAPI')) {
        $fb = new FacebookCAPI();
        $fbUserData = [
            'email' => $customer['email'] ?? null,
            'phone' => $customer['phone'] ?? null,
            'name' => $customer['name'] ?? null,
            'document' => $customer['document'] ?? null,
            'fbc' => $utms['fbc'] ?? null,
            'fbp' => $utms['fbp'] ?? null,
            'ip' => $clientIp
        ];
        
        $purchaseResult = $fb->purchase($fbUserData, $amount, $orderId, $cotas);
        $results['fb_purchase'] = $purchaseResult['success'] ?? false;
        $results['fb_event_id'] = $purchaseResult['event_id'] ?? null;
        
        logCheckout('webhook.log', 'Facebook Purchase enviado', $purchaseResult);
    }
    
    // UTMify Paid
    if (class_exists('Utmify')) {
        $utmify = new Utmify();
        $utmifyResult = $utmify->sendPaid(
            $orderId,
            $amountCents,
            [
                'name' => $customer['name'] ?? '',
                'email' => $customer['email'] ?? '',
                'phone' => $customer['phone'] ?? '',
                'document' => $customer['document'] ?? '',
                'ip' => $clientIp
            ],
            [
                'id' => PRODUTO_ID,
                'name' => PRODUTO_NOME,
                'quantity' => $cotas
            ],
            $utms
        );
        $results['utmify'] = $utmifyResult['success'] ?? false;
        
        logCheckout('webhook.log', 'UTMify Paid enviado', $utmifyResult);
    }
    
} elseif ($statusNorm === 'refunded') {
    logCheckout('webhook.log', 'Processando REEMBOLSO');
    
    if (class_exists('Utmify')) {
        $utmify = new Utmify();
        $utmifyResult = $utmify->sendRefunded(
            $orderId,
            $amountCents,
            [
                'name' => $customer['name'] ?? '',
                'email' => $customer['email'] ?? '',
                'phone' => $customer['phone'] ?? '',
                'document' => $customer['document'] ?? '',
                'ip' => $clientIp
            ],
            [
                'id' => PRODUTO_ID,
                'name' => PRODUTO_NOME,
                'quantity' => $cotas
            ],
            $utms
        );
        $results['utmify'] = $utmifyResult['success'] ?? false;
        
        logCheckout('webhook.log', 'UTMify Refunded enviado', $utmifyResult);
    }
}

logCheckout('webhook.log', '=== WEBHOOK FINALIZADO ===', $results);

http_response_code(200);
echo json_encode([
    'success' => true,
    'gateway' => $detectedGateway,
    'order_id' => $orderId,
    'status' => $statusNorm,
    'amount' => $amount,
    'results' => $results
]);


// ============================================
// FUNÇÕES AUXILIARES
// ============================================

/**
 * Detecta qual gateway enviou o webhook pelo formato do payload
 */
function detectGateway($data) {
    // TechByNet geralmente tem campos específicos
    if (isset($data['transaction_id']) || isset($data['pix_code'])) {
        return 'techbynet';
    }
    
    // Umbrella geralmente tem estrutura data.data ou objectId
    if (isset($data['objectId']) || isset($data['data']['data'])) {
        return 'umbrella';
    }
    
    // Verifica pelo header se disponível
    $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    if (stripos($userAgent, 'techbynet') !== false) {
        return 'techbynet';
    }
    if (stripos($userAgent, 'umbrella') !== false) {
        return 'umbrella';
    }
    
    // Default: usa gateway ativo
    return GATEWAY_ATIVO;
}

/**
 * Extrai dados do webhook conforme o gateway
 */
function extractWebhookData($data, $gateway) {
    $result = [
        'order_id' => '',
        'status' => '',
        'amount' => 0,
        'customer' => [
            'name' => '',
            'email' => '',
            'phone' => '',
            'document' => ''
        ],
        'products' => []
    ];
    
    if ($gateway === 'umbrella') {
        // Umbrella: dados podem estar em data ou data.data
        $webhookData = $data['data']['data'] ?? $data['data'] ?? $data;
        
        $result['order_id'] = $webhookData['id'] ?? $data['objectId'] ?? uniqid('order_');
        $result['status'] = $webhookData['status'] ?? '';
        $result['amount'] = $webhookData['amount'] ?? 0;
        
        $customer = $webhookData['customer'] ?? $webhookData['payer'] ?? [];
        $result['customer'] = [
            'name' => $customer['name'] ?? '',
            'email' => $customer['email'] ?? '',
            'phone' => $customer['phone'] ?? '',
            'document' => $customer['document']['number'] ?? $customer['document'] ?? ''
        ];
        
        $result['products'] = $webhookData['products'] ?? $webhookData['items'] ?? [];
        
    } elseif ($gateway === 'techbynet') {
        // TechByNet: estrutura mais plana
        $result['order_id'] = $data['id'] ?? $data['transaction_id'] ?? $data['external_reference'] ?? uniqid('order_');
        $result['status'] = $data['status'] ?? '';
        $result['amount'] = $data['amount'] ?? 0;
        
        $result['customer'] = [
            'name' => $data['payer_name'] ?? $data['customer_name'] ?? '',
            'email' => $data['payer_email'] ?? $data['customer_email'] ?? '',
            'phone' => $data['payer_phone'] ?? $data['customer_phone'] ?? '',
            'document' => $data['payer_document'] ?? $data['customer_document'] ?? ''
        ];
        
        $result['products'] = $data['products'] ?? $data['items'] ?? [];
        
    } else {
        // Fallback genérico
        $webhookData = $data['data'] ?? $data;
        
        $result['order_id'] = $webhookData['id'] ?? uniqid('order_');
        $result['status'] = $webhookData['status'] ?? '';
        $result['amount'] = $webhookData['amount'] ?? 0;
        
        $customer = $webhookData['customer'] ?? [];
        $result['customer'] = [
            'name' => $customer['name'] ?? '',
            'email' => $customer['email'] ?? '',
            'phone' => $customer['phone'] ?? '',
            'document' => $customer['document'] ?? ''
        ];
        
        $result['products'] = $webhookData['products'] ?? [];
    }
    
    return $result;
}