<?php
/**
 * ============================================
 * UTMIFY - INTEGRAÇÃO DE CONVERSÕES
 * ============================================
 * Envia pedidos para o UTMify com tracking completo
 */

require_once __DIR__ . '/config.php';

class Utmify {
    
    private $token;
    private $apiUrl = 'https://api.utmify.com.br/api-credentials/orders';
    
    public function __construct() {
        $this->token = UTMIFY_TOKEN;
    }
    
    /**
     * Envia pedido para UTMify
     */
    public function sendOrder($orderId, $status, $amountCents, $customer, $product, $utms) {
        $payload = [
            'orderId' => (string) $orderId,
            'platform' => 'SmartCheckout',
            'paymentMethod' => 'pix',
            'status' => $status,
            'createdAt' => date('Y-m-d H:i:s'),
            'approvedDate' => ($status === 'paid') ? date('Y-m-d H:i:s') : null,
            'refundedAt' => ($status === 'refunded') ? date('Y-m-d H:i:s') : 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'] ?? $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1'
            ],
            'products' => [[
                'id' => $product['id'] ?? PRODUTO_ID,
                'name' => $product['name'] ?? PRODUTO_NOME,
                '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
        ];
        
        $ch = curl_init($this->apiUrl);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($payload),
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'x-api-token: ' . $this->token
            ],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error = curl_error($ch);
        curl_close($ch);
        
        $success = $httpCode >= 200 && $httpCode < 300;
        
        logCheckout('utmify.log', "Order $orderId - Status: $status", [
            'success' => $success,
            'http_code' => $httpCode,
            'response' => json_decode($response, true),
            'error' => $error
        ]);
        
        return [
            'success' => $success,
            'http_code' => $httpCode,
            'response' => json_decode($response, true)
        ];
    }
    
    /**
     * Envia pedido pendente (PIX gerado)
     */
    public function sendPending($orderId, $amountCents, $customer, $product, $utms) {
        return $this->sendOrder($orderId, 'waiting_payment', $amountCents, $customer, $product, $utms);
    }
    
    /**
     * Envia pedido pago
     */
    public function sendPaid($orderId, $amountCents, $customer, $product, $utms) {
        return $this->sendOrder($orderId, 'paid', $amountCents, $customer, $product, $utms);
    }
    
    /**
     * Envia reembolso
     */
    public function sendRefunded($orderId, $amountCents, $customer, $product, $utms) {
        return $this->sendOrder($orderId, 'refunded', $amountCents, $customer, $product, $utms);
    }
}
