<?php
/**
 * ============================================
 * FACEBOOK CONVERSION API - CLASSE UNIFICADA
 * ============================================
 */

require_once __DIR__ . '/config.php';

class FacebookCAPI {
    
    private $pixelId;
    private $accessToken;
    private $apiVersion;
    private $testEventCode;
    
    public function __construct() {
        $this->pixelId = FB_PIXEL_ID;
        $this->accessToken = FB_ACCESS_TOKEN;
        $this->apiVersion = FB_API_VERSION;
        $this->testEventCode = FB_TEST_EVENT_CODE;
    }
    
    private function generateEventId($prefix = 'evt') {
        return $prefix . '_' . bin2hex(random_bytes(8)) . '_' . time();
    }
    
    private function prepareUserData($data) {
        $userData = [];
        
        // Email (hash)
        if (!empty($data['email'])) {
            $email = strtolower(trim($data['email']));
            $userData['em'] = [hash('sha256', $email)];
        }
        
        // Telefone (hash)
        if (!empty($data['phone'])) {
            $phone = preg_replace('/\D/', '', $data['phone']);
            if (!empty($phone)) {
                if (strlen($phone) <= 11) {
                    $phone = '55' . $phone;
                }
                $userData['ph'] = [hash('sha256', $phone)];
            }
        }
        
        // Nome e Sobrenome (hash)
        if (!empty($data['name'])) {
            $nameParts = explode(' ', trim($data['name']));
            $firstName = strtolower(trim($nameParts[0]));
            $userData['fn'] = [hash('sha256', $firstName)];
            
            if (count($nameParts) > 1) {
                $lastName = strtolower(trim(end($nameParts)));
                $userData['ln'] = [hash('sha256', $lastName)];
            }
        }
        
        // CPF como external_id (hash)
        if (!empty($data['document'])) {
            $doc = preg_replace('/\D/', '', $data['document']);
            $userData['external_id'] = [hash('sha256', $doc)];
        }
        
        // Cidade (hash)
        if (!empty($data['cidade'])) {
            $cidade = strtolower(trim($data['cidade']));
            $cidade = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $cidade);
            $cidade = preg_replace('/[^a-z]/', '', $cidade);
            if (!empty($cidade)) {
                $userData['ct'] = [hash('sha256', $cidade)];
            }
        }
        
        // Estado (hash)
        if (!empty($data['estado'])) {
            $estado = strtolower(substr(trim($data['estado']), 0, 2));
            $userData['st'] = [hash('sha256', $estado)];
        }
        
        // CEP (hash)
        if (!empty($data['cep'])) {
            $cep = preg_replace('/\D/', '', $data['cep']);
            if (!empty($cep)) {
                $userData['zp'] = [hash('sha256', $cep)];
            }
        }
        
        // País (sempre BR)
        $userData['country'] = [hash('sha256', 'br')];
        
        // IP do cliente (NÃO hashear)
        if (!empty($data['ip'])) {
            $userData['client_ip_address'] = $data['ip'];
        } else {
            $clientIp = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? '';
            if (strpos($clientIp, ',') !== false) {
                $clientIp = trim(explode(',', $clientIp)[0]);
            }
            $userData['client_ip_address'] = $clientIp;
        }
        
        // User Agent (NÃO hashear)
        $userData['client_user_agent'] = $data['user_agent'] ?? $_SERVER['HTTP_USER_AGENT'] ?? '';
        
        // Facebook Click ID - fbc (NÃO hashear)
        if (!empty($data['fbc'])) {
            $fbc = $data['fbc'];
            $fbcParts = explode('.', $fbc);
            
            if (count($fbcParts) >= 4 && strlen($fbcParts[2]) > 0) {
                $fbcTimeRaw = $fbcParts[2];
                $nowSec = time();
                
                if (strlen($fbcTimeRaw) <= 10) {
                    $fbcTimeSec = intval($fbcTimeRaw);
                } else {
                    $fbcTimeSec = intval($fbcTimeRaw / 1000);
                }
                
                $maxAge = 7 * 24 * 60 * 60;
                $tolerance = 60;
                
                if ($fbcTimeSec <= ($nowSec + $tolerance) && $fbcTimeSec >= ($nowSec - $maxAge)) {
                    $userData['fbc'] = $fbc;
                    $userData['_fbc_creation_time'] = $fbcTimeSec;
                }
            }
        }
        
        // Facebook Browser ID - fbp (NÃO hashear)
        if (!empty($data['fbp'])) {
            $userData['fbp'] = $data['fbp'];
        }
        
        return $userData;
    }
    
    private function sendEvent($eventName, $userData, $customData, $sourceUrl = '', $eventId = null) {
        $url = "https://graph.facebook.com/{$this->apiVersion}/{$this->pixelId}/events?access_token={$this->accessToken}";
        
        $eventId = $eventId ?? $this->generateEventId(strtolower($eventName));
        
        if (isset($customData['value'])) {
            $customData['value'] = floatval($customData['value']);
        }
        $customData['currency'] = 'BRL';
        
        $fbcCreationTime = $userData['_fbc_creation_time'] ?? null;
        unset($userData['_fbc_creation_time']);
        
        $eventTime = time();
        if ($fbcCreationTime && $eventTime < $fbcCreationTime) {
            $eventTime = $fbcCreationTime;
        }
        
        $userData = array_filter($userData, function($v) {
            if (is_array($v)) {
                return !empty(array_filter($v, function($x) { return $x !== null; }));
            }
            return $v !== null && $v !== '';
        });
        
        $eventData = [
            'event_name' => $eventName,
            'event_time' => $eventTime,
            'event_id' => $eventId,
            'event_source_url' => $sourceUrl ?: (SITE_URL ?? ''),
            'action_source' => 'website',
            'user_data' => $userData,
            'custom_data' => $customData
        ];
        
        $payload = ['data' => [$eventData]];
        
        if (!empty($this->testEventCode)) {
            $payload['test_event_code'] = $this->testEventCode;
        }
        
        $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);
        $error = curl_error($ch);
        curl_close($ch);
        
        $success = $httpCode >= 200 && $httpCode < 300;
        
        logCheckout('facebook_capi.log', "$eventName", [
            'success' => $success,
            'event_id' => $eventId,
            'http_code' => $httpCode,
            'response' => json_decode($response, true),
            'error' => $error
        ]);
        
        return [
            'success' => $success,
            'event_id' => $eventId,
            'http_code' => $httpCode,
            'response' => json_decode($response, true)
        ];
    }
    
    public function pageView($data, $sourceUrl = '', $eventId = null) {
        $userData = $this->prepareUserData($data);
        $customData = [
            'content_name' => $data['content_name'] ?? PRODUTO_NOME
        ];
        return $this->sendEvent('PageView', $userData, $customData, $sourceUrl, $eventId);
    }
    
    public function viewContent($data, $value = 0, $sourceUrl = '', $eventId = null) {
        $userData = $this->prepareUserData($data);
        $customData = [
            'currency' => 'BRL',
            'value' => (float) $value,
            'content_type' => 'product',
            'content_name' => $data['content_name'] ?? PRODUTO_NOME,
            'content_ids' => [$data['content_id'] ?? PRODUTO_ID],
            'content_category' => 'Sorteios'
        ];
        return $this->sendEvent('ViewContent', $userData, $customData, $sourceUrl, $eventId);
    }
    
    public function addToCart($data, $value, $numItems = 1, $sourceUrl = '', $eventId = null) {
        $userData = $this->prepareUserData($data);
        $customData = [
            'currency' => 'BRL',
            'value' => (float) $value,
            'content_type' => 'product',
            'content_name' => $data['content_name'] ?? PRODUTO_NOME,
            'content_ids' => [$data['content_id'] ?? PRODUTO_ID],
            'content_category' => 'Sorteios',
            'num_items' => (int) $numItems
        ];
        return $this->sendEvent('AddToCart', $userData, $customData, $sourceUrl, $eventId);
    }
    
    public function initiateCheckout($data, $value, $numItems = 1, $sourceUrl = '', $eventId = null) {
        $userData = $this->prepareUserData($data);
        $customData = [
            'currency' => 'BRL',
            'value' => (float) $value,
            'content_type' => 'product',
            'content_name' => $data['content_name'] ?? PRODUTO_NOME,
            'content_ids' => [$data['content_id'] ?? PRODUTO_ID],
            'num_items' => (int) $numItems
        ];
        return $this->sendEvent('InitiateCheckout', $userData, $customData, $sourceUrl, $eventId);
    }
    
    public function addPaymentInfo($data, $value, $sourceUrl = '', $eventId = null) {
        $userData = $this->prepareUserData($data);
        $customData = [
            'currency' => 'BRL',
            'value' => (float) $value,
            'content_type' => 'product',
            'content_name' => $data['content_name'] ?? PRODUTO_NOME,
            'content_ids' => [$data['content_id'] ?? PRODUTO_ID]
        ];
        return $this->sendEvent('AddPaymentInfo', $userData, $customData, $sourceUrl, $eventId);
    }
    
    public function purchase($data, $value, $orderId, $numItems = 1, $sourceUrl = '', $eventId = null) {
        $userData = $this->prepareUserData($data);
        $customData = [
            'currency' => 'BRL',
            'value' => (float) $value,
            'content_type' => 'product',
            'content_name' => $data['content_name'] ?? PRODUTO_NOME,
            'content_ids' => [$data['content_id'] ?? PRODUTO_ID],
            'content_category' => 'Sorteios',
            'num_items' => (int) $numItems,
            'order_id' => $orderId
        ];
        return $this->sendEvent('Purchase', $userData, $customData, $sourceUrl, $eventId);
    }
    
    public function customEvent($eventName, $data, $customData = [], $sourceUrl = '', $eventId = null) {
        $userData = $this->prepareUserData($data);
        return $this->sendEvent($eventName, $userData, $customData, $sourceUrl, $eventId);
    }
}