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

class Utmify {
    
    private $token;
    private $apiUrl = 'https://api.utmify.com.br/api-credentials/orders';
    private $enabled = true;
    
    public function __construct() {
        // Tenta carregar do arquivo de configuração
        $configFile = __DIR__ . '/utmify_config.json';
        
        if (file_exists($configFile)) {
            $config = json_decode(file_get_contents($configFile), true);
            $this->token = $config['api_token'] ?? '';
            $this->enabled = $config['enabled'] ?? true;
            if (!empty($config['base_url'])) {
                $this->apiUrl = $config['base_url'];
            }
        }
        
        // Fallback para constante se existir
        if (empty($this->token) && defined('UTMIFY_TOKEN')) {
            $this->token = UTMIFY_TOKEN;
        }
    }
    
    /**
     * Verifica se está configurado
     */
    public function isConfigured() {
        return $this->enabled && !empty($this->token) && $this->token !== 'SEU_TOKEN_UTMIFY_AQUI';
    }
    
    /**
     * Envia pedido para UTMify
     */
    public function sendOrder($orderId, $status, $amountCents, $customer, $product, $utms) {
        if (!$this->isConfigured()) {
            $this->log("UTMify não configurado - pulando envio");
            return ['success' => false, 'error' => 'Token não configurado'];
        }
        
        $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'] ?? (defined('PRODUTO_ID') ? PRODUTO_ID : 'produto-001'),
                'name' => $product['name'] ?? (defined('PRODUTO_NOME') ? PRODUTO_NOME : '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
        ];
        
        $this->log("Enviando $status", ['orderId' => $orderId, 'amount' => $amountCents / 100]);
        
        $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;
        
        $this->log("Resposta UTMify", [
            'success' => $success,
            'http_code' => $httpCode,
            'response' => substr($response, 0, 300),
            '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);
    }
    
    /**
     * Log para debug
     */
    private function log($message, $data = []) {
        $logDir = __DIR__ . '/logs';
        if (!is_dir($logDir)) {
            @mkdir($logDir, 0755, true);
        }
        
        $logFile = $logDir . '/utmify.log';
        $timestamp = date('Y-m-d H:i:s');
        
        $logLine = "[$timestamp] $message";
        if (!empty($data)) {
            $logLine .= ' | ' . json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        }
        $logLine .= "\n";
        
        @file_put_contents($logFile, $logLine, FILE_APPEND | LOCK_EX);
    }
}