<?php
/**
 * ============================================
 * FACEBOOK CAPI - SIMPLIFICADO
 * ============================================
 * Envia eventos de conversão para o Facebook
 */

class FacebookCAPI {
    
    private $pixelId = '3061241000727171';
    private $accessToken = 'EAARtphyE16sBQAYRIu5AVFC9PZAZBSUGA875QI6QdZCHrvk0Q1UVEXALi6fhLQ7pZBJbFhAhggv2k1bIYKZAgpcWdxtGFmPHnauDQhmFhLV0GTMhTBbnsSsQjctdw8mbHPvZAHOuTtxQZCDpBGlX3ZArHdjTTBiv0GHYKAFZB0UAxU0P9GLIqm6ZB3i5Q0VrImZABqldAZDZD';
    private $testEventCode = ''; // Deixe vazio em produção
    
    /**
     * Envia evento Purchase para o Facebook
     * Chamado pelo webhook quando pagamento é confirmado
     */
    public function sendPurchase($txId, $valorReais, $utmData = []) {
        $this->log("Iniciando envio Purchase", [
            'txId' => $txId,
            'valor' => $valorReais
        ]);
        
        // Prepara dados do usuário
        $userData = [];
        
        // Email
        $email = $utmData['customer']['email'] ?? $utmData['email'] ?? null;
        if ($email) {
            $userData['em'] = [hash('sha256', strtolower(trim($email)))];
        }
        
        // Telefone
        $phone = $utmData['customer']['phone'] ?? $utmData['telefone'] ?? $utmData['celular'] ?? null;
        if ($phone) {
            $phone = preg_replace('/\D/', '', $phone);
            if (strlen($phone) <= 11) {
                $phone = '55' . $phone;
            }
            $userData['ph'] = [hash('sha256', $phone)];
        }
        
        // Nome
        $name = $utmData['customer']['name'] ?? $utmData['nome'] ?? null;
        if ($name) {
            $nameParts = explode(' ', trim($name));
            $userData['fn'] = [hash('sha256', strtolower($nameParts[0]))];
            if (count($nameParts) > 1) {
                $userData['ln'] = [hash('sha256', strtolower(end($nameParts)))];
            }
        }
        
        // CPF como external_id
        $cpf = $utmData['customer']['document'] ?? $utmData['cpf'] ?? null;
        if ($cpf) {
            $cpf = preg_replace('/\D/', '', $cpf);
            $userData['external_id'] = [hash('sha256', $cpf)];
        }
        
        // Data de Nascimento (formato YYYYMMDD)
        $dob = $utmData['customer']['birth_date'] ?? $utmData['birth_date'] ?? $utmData['data_nascimento'] ?? null;
        if ($dob) {
            // Remove qualquer formatação e converte para YYYYMMDD
            $dob = preg_replace('/\D/', '', $dob);
            // Se veio no formato DDMMYYYY, converte para YYYYMMDD
            if (strlen($dob) === 8) {
                // Detecta se é DDMMYYYY ou YYYYMMDD
                $year = substr($dob, 0, 4);
                if ($year < 1900 || $year > 2100) {
                    // É DDMMYYYY, converte para YYYYMMDD
                    $dob = substr($dob, 4, 4) . substr($dob, 2, 2) . substr($dob, 0, 2);
                }
            }
            $userData['db'] = [hash('sha256', $dob)];
        }
        
        // País
        $userData['country'] = [hash('sha256', 'br')];
        
        // IP
        $ip = $utmData['customer_ip'] ?? $utmData['ip'] ?? $_SERVER['REMOTE_ADDR'] ?? '';
        if ($ip) {
            $userData['client_ip_address'] = $ip;
        }
        
        // User Agent
        $userData['client_user_agent'] = $utmData['user_agent'] ?? $_SERVER['HTTP_USER_AGENT'] ?? '';
        
        // FBC (Facebook Click ID)
        if (!empty($utmData['fbc'])) {
            $userData['fbc'] = $utmData['fbc'];
        }
        
        // FBP (Facebook Browser ID)
        if (!empty($utmData['fbp'])) {
            $userData['fbp'] = $utmData['fbp'];
        }
        
        // Dados do evento
        $eventData = [
            'event_name' => 'Purchase',
            'event_time' => time(),
            'event_id' => 'purchase_' . $txId . '_' . time(),
            'event_source_url' => $utmData['source_url'] ?? 'https://checkout-carlinhosmaia.com',
            'action_source' => 'website',
            'user_data' => $userData,
            'custom_data' => [
                'currency' => 'BRL',
                'value' => floatval($valorReais),
                'content_type' => 'product',
                'content_name' => $utmData['produto'] ?? 'Cotas',
                'content_ids' => [$utmData['produto_id'] ?? 'premios-001'],
                'num_items' => intval($utmData['cotas'] ?? 1),
                'order_id' => $txId
            ]
        ];
        
        // Payload para a API
        $payload = ['data' => [$eventData]];
        
        if (!empty($this->testEventCode)) {
            $payload['test_event_code'] = $this->testEventCode;
        }
        
        // URL da API
        $url = "https://graph.facebook.com/v18.0/{$this->pixelId}/events?access_token={$this->accessToken}";
        
        $this->log("Enviando para Facebook API", [
            'url' => 'graph.facebook.com/.../events',
            'event_id' => $eventData['event_id'],
            'value' => $valorReais,
            'has_email' => isset($userData['em']),
            'has_phone' => isset($userData['ph']),
            'has_fbc' => isset($userData['fbc']),
            'has_fbp' => isset($userData['fbp'])
        ]);
        
        // Envia requisição
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($payload),
            CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_SSL_VERIFYPEER => true
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);
        
        $responseData = json_decode($response, true);
        $success = $httpCode >= 200 && $httpCode < 300;
        
        $this->log("Resposta Facebook API", [
            'success' => $success,
            'http_code' => $httpCode,
            'events_received' => $responseData['events_received'] ?? 0,
            'messages' => $responseData['messages'] ?? [],
            'fbtrace_id' => $responseData['fbtrace_id'] ?? null,
            'curl_error' => $curlError ?: null
        ]);
        
        return [
            'success' => $success,
            'event_id' => $eventData['event_id'],
            'http_code' => $httpCode,
            'events_received' => $responseData['events_received'] ?? 0,
            'response' => $responseData
        ];
    }
    
    /**
     * Log para debug
     */
    private function log($message, $data = []) {
        $logDir = __DIR__ . '/logs';
        if (!is_dir($logDir)) {
            @mkdir($logDir, 0755, true);
        }
        
        $logFile = $logDir . '/facebook_capi.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);
    }
    
    /**
     * Métodos adicionais para outros eventos (usados pelo tracking.php)
     */
    public function pageView($data, $sourceUrl = '', $eventId = null) {
        return $this->sendGenericEvent('PageView', $data, 0, 1, $sourceUrl, $eventId);
    }
    
    public function viewContent($data, $value = 0, $sourceUrl = '', $eventId = null) {
        return $this->sendGenericEvent('ViewContent', $data, $value, 1, $sourceUrl, $eventId);
    }
    
    public function addToCart($data, $value, $numItems = 1, $sourceUrl = '', $eventId = null) {
        return $this->sendGenericEvent('AddToCart', $data, $value, $numItems, $sourceUrl, $eventId);
    }
    
    public function initiateCheckout($data, $value, $numItems = 1, $sourceUrl = '', $eventId = null) {
        return $this->sendGenericEvent('InitiateCheckout', $data, $value, $numItems, $sourceUrl, $eventId);
    }
    
    public function addPaymentInfo($data, $value, $sourceUrl = '', $eventId = null) {
        return $this->sendGenericEvent('AddPaymentInfo', $data, $value, 1, $sourceUrl, $eventId);
    }
    
    public function purchase($data, $value, $orderId, $numItems = 1, $sourceUrl = '', $eventId = null) {
        // Converte para o formato do sendPurchase
        $utmData = [
            'customer' => [
                'email' => $data['email'] ?? null,
                'phone' => $data['phone'] ?? null,
                'name' => $data['name'] ?? null,
                'document' => $data['document'] ?? null
            ],
            'customer_ip' => $data['ip'] ?? null,
            'user_agent' => $data['user_agent'] ?? null,
            'fbc' => $data['fbc'] ?? null,
            'fbp' => $data['fbp'] ?? null,
            'produto' => $data['content_name'] ?? 'Cotas',
            'produto_id' => $data['content_id'] ?? 'premios-001',
            'cotas' => $numItems,
            'source_url' => $sourceUrl
        ];
        
        return $this->sendPurchase($orderId, $value, $utmData);
    }
    
    public function customEvent($eventName, $data, $customData = [], $sourceUrl = '', $eventId = null) {
        return $this->sendGenericEvent($eventName, $data, $customData['value'] ?? 0, 1, $sourceUrl, $eventId);
    }
    
    /**
     * Evento genérico (para AddToCart, ViewContent, etc)
     * IMPORTANTE: $eventId deve ser o MESMO enviado pelo Pixel do browser para deduplicação!
     */
    private function sendGenericEvent($eventName, $data, $value, $numItems, $sourceUrl, $eventId = null) {
        // Prepara user data
        $userData = [];
        
        if (!empty($data['email'])) {
            $userData['em'] = [hash('sha256', strtolower(trim($data['email'])))];
        }
        if (!empty($data['phone'])) {
            $phone = preg_replace('/\D/', '', $data['phone']);
            if (strlen($phone) <= 11) $phone = '55' . $phone;
            $userData['ph'] = [hash('sha256', $phone)];
        }
        if (!empty($data['name'])) {
            $nameParts = explode(' ', trim($data['name']));
            $userData['fn'] = [hash('sha256', strtolower($nameParts[0]))];
            if (count($nameParts) > 1) {
                $userData['ln'] = [hash('sha256', strtolower(end($nameParts)))];
            }
        }
        if (!empty($data['document'])) {
            $userData['external_id'] = [hash('sha256', preg_replace('/\D/', '', $data['document']))];
        }
        
        // Data de Nascimento (formato YYYYMMDD)
        $dob = $data['birth_date'] ?? $data['data_nascimento'] ?? null;
        if ($dob) {
            $dob = preg_replace('/\D/', '', $dob);
            if (strlen($dob) === 8) {
                $year = substr($dob, 0, 4);
                if ($year < 1900 || $year > 2100) {
                    $dob = substr($dob, 4, 4) . substr($dob, 2, 2) . substr($dob, 0, 2);
                }
            }
            $userData['db'] = [hash('sha256', $dob)];
        }
        
        $userData['country'] = [hash('sha256', 'br')];
        
        if (!empty($data['ip'])) {
            $userData['client_ip_address'] = $data['ip'];
        }
        if (!empty($data['user_agent'])) {
            $userData['client_user_agent'] = $data['user_agent'];
        }
        if (!empty($data['fbc'])) {
            $userData['fbc'] = $data['fbc'];
        }
        if (!empty($data['fbp'])) {
            $userData['fbp'] = $data['fbp'];
        }
        
        // IMPORTANTE: Usa o event_id do frontend se fornecido (para deduplicação com Pixel)
        // Se não fornecido, gera um novo
        if (empty($eventId)) {
            $eventId = strtolower($eventName) . '_' . bin2hex(random_bytes(8)) . '_' . time();
        }
        
        $eventData = [
            'event_name' => $eventName,
            'event_time' => time(),
            'event_id' => $eventId,
            'event_source_url' => $sourceUrl ?: 'https://checkout-carlinhosmaia.com',
            'action_source' => 'website',
            'user_data' => $userData,
            'custom_data' => [
                'currency' => 'BRL',
                'value' => floatval($value),
                'content_type' => 'product',
                'content_name' => $data['content_name'] ?? 'Cotas',
                'content_ids' => [$data['content_id'] ?? 'premios-001'],
                'num_items' => intval($numItems)
            ]
        ];
        
        $payload = ['data' => [$eventData]];
        
        if (!empty($this->testEventCode)) {
            $payload['test_event_code'] = $this->testEventCode;
        }
        
        $url = "https://graph.facebook.com/v18.0/{$this->pixelId}/events?access_token={$this->accessToken}";
        
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($payload),
            CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        $this->log("$eventName enviado", [
            'event_id' => $eventId,
            'http_code' => $httpCode,
            'value' => $value
        ]);
        
        return [
            'success' => $httpCode >= 200 && $httpCode < 300,
            'event_id' => $eventId,
            'http_code' => $httpCode,
            'response' => json_decode($response, true)
        ];
    }
}