<?php


header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'Method not allowed']);
    exit;
}

// Carregar credenciais do arquivo de config centralizado
$_secrets = require __DIR__ . '/secrets-config.php';

define('UTMIFY_API_URL', $_secrets['utmify_api_url']);
define('UTMIFY_API_TOKEN', $_secrets['utmify_api_token']);
define('UTMIFY_PLATFORM', $_secrets['utmify_platform']);
define('UTMIFY_PENDING_DIR', __DIR__ . '/.utmify_pending');
define('UTMIFY_LOG_FILE', __DIR__ . '/.utmify_pending/utmify_log.jsonl');
define('UTMIFY_FAILED_DIR', __DIR__ . '/.utmify_pending/failed');

define('TIKTOK_PIXEL_ID', $_secrets['tiktok_pixel_id']);
define('TIKTOK_ACCESS_TOKEN', $_secrets['tiktok_access_token']);

// Meta Conversions API (CAPI)
define('META_PIXEL_ID', $_secrets['meta_pixel_id']);
define('META_ACCESS_TOKEN', $_secrets['meta_access_token']);

unset($_secrets);


function utc_now_str(): string {
    return gmdate('Y-m-d H:i:s');
}

function pending_path(string $orderId): string {
    if (!is_dir(UTMIFY_PENDING_DIR)) {
        @mkdir(UTMIFY_PENDING_DIR, 0755, true);
    }
    $safe = preg_replace('/[^a-zA-Z0-9_\-]/', '_', $orderId);
    if ($safe === '') $safe = md5($orderId);
    return UTMIFY_PENDING_DIR . '/' . $safe . '.json';
}

function utmify_log(string $level, string $msg, array $context = []): void {
    $entry = [
        'ts' => gmdate('Y-m-d\TH:i:s\Z'),
        'level' => $level,
        'msg' => $msg,
    ];
    if ($context) $entry['ctx'] = $context;
    @file_put_contents(UTMIFY_LOG_FILE, json_encode($entry, JSON_UNESCAPED_UNICODE) . "\n", FILE_APPEND | LOCK_EX);
}

function utmify_save_failed(string $orderId, array $payload, int $http, ?array $resp, string $err): void {
    $dir = UTMIFY_FAILED_DIR;
    if (!is_dir($dir)) @mkdir($dir, 0755, true);
    $safe = preg_replace('/[^a-zA-Z0-9_\-]/', '_', $orderId);
    $file = $dir . '/' . $safe . '_' . time() . '.json';
    @file_put_contents($file, json_encode([
        'payload' => $payload,
        'http' => $http,
        'response' => $resp,
        'curl_error' => $err,
        'failed_at' => gmdate('Y-m-d H:i:s'),
    ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
}

function utmify_send(array $payload): array {
    $json = json_encode($payload, JSON_UNESCAPED_UNICODE);
    if ($json === false) {
        return [false, 0, null, 'JSON_ENCODE_FAILED'];
    }

    $ch = curl_init(UTMIFY_API_URL);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'x-api-token: ' . UTMIFY_API_TOKEN,
        ],
        CURLOPT_POSTFIELDS => $json,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 20,
        CURLOPT_SSL_VERIFYPEER => true,
    ]);
    $response = curl_exec($ch);
    $http = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err = curl_error($ch);
    curl_close($ch);

    $respJson = null;
    if (is_string($response) && $response !== '') {
        $decoded = json_decode($response, true);
        if (is_array($decoded)) $respJson = $decoded;
    }

    $ok = ($err === '' && $http >= 200 && $http < 300);
    return [$ok, $http, $respJson, $err];
}

function tiktok_send_event(string $eventName, array $eventData): array {
    $payload = [
        'pixel_code' => TIKTOK_PIXEL_ID,
        'event' => $eventName,
        'event_id' => $eventData['event_id'] ?? null,
        'timestamp' => time(),
        'context' => [
            'ad' => [
                'callback' => $_COOKIE['ttclid'] ?? null,
            ],
            'user' => [
                'email' => !empty($eventData['customer']['email']) ? hash('sha256', strtolower(trim($eventData['customer']['email']))) : null,
                'phone_number' => !empty($eventData['customer']['phone']) ? hash('sha256', trim($eventData['customer']['phone'])) : null,
            ],
            'page' => [
                'url' => (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]",
            ],
        ],
        'properties' => [
            'content_id' => $eventData['product_id'] ?? null,
            'content_name' => $eventData['product_name'] ?? null,
            'value' => (float)($eventData['amount'] ?? 0),
            'currency' => 'EUR',
        ],
    ];

    if (defined('TIKTOK_TEST_EVENT_CODE') && TIKTOK_TEST_EVENT_CODE) {
        $payload['test_event_code'] = TIKTOK_TEST_EVENT_CODE;
    }

    $ch = curl_init('https://business-api.tiktok.com/open_api/v1.3/event/track/');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'Access-Token: ' . TIKTOK_ACCESS_TOKEN,
        ],
        CURLOPT_POSTFIELDS => json_encode($payload),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 20,
        CURLOPT_SSL_VERIFYPEER => true,
    ]);
    $response = curl_exec($ch);
    $http = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err = curl_error($ch);
    curl_close($ch);

    $respJson = null;
    if (is_string($response) && $response !== '') {
        $respJson = json_decode($response, true);
    }

    return [$http >= 200 && $http < 300, $http, $respJson, $err];
}

function meta_capi_send_event(string $eventName, array $eventData): array {
    $email = $eventData['customer']['email'] ?? null;
    $phone = $eventData['customer']['phone'] ?? null;

    $userData = [
        'client_ip_address' => $_SERVER['REMOTE_ADDR'] ?? null,
        'client_user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? null,
        'fbc' => $_COOKIE['_fbc'] ?? null,
        'fbp' => $_COOKIE['_fbp'] ?? null,
    ];
    if (!empty($email)) {
        $userData['em'] = [hash('sha256', strtolower(trim($email)))];
    }
    if (!empty($phone)) {
        $cleaned = preg_replace('/\D/', '', $phone);
        if ($cleaned !== '') {
            $userData['ph'] = [hash('sha256', $cleaned)];
        }
    }

    $payload = [
        'data' => [[
            'event_name' => $eventName,
            'event_time' => time(),
            'event_source_url' => 'https://confirmarbonus.lat' . ($_SERVER['REQUEST_URI'] ?? ''),
            'action_source' => 'website',
            'event_id' => $eventData['event_id'] ?? uniqid('meta_', true),
            'user_data' => $userData,
            'custom_data' => [
                'value' => (float)($eventData['amount'] ?? 0),
                'currency' => 'EUR',
                'order_id' => $eventData['order_id'] ?? ($eventData['event_id'] ?? uniqid()),
                'content_name' => $eventData['product_name'] ?? null,
                'content_ids' => [$eventData['product_id'] ?? 'unknown'],
                'content_type' => 'product',
            ],
        ]],
        'access_token' => META_ACCESS_TOKEN,
    ];

    $url = 'https://graph.facebook.com/v19.0/' . META_PIXEL_ID . '/events';
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        CURLOPT_POSTFIELDS => json_encode($payload),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 20,
        CURLOPT_SSL_VERIFYPEER => true,
    ]);
    $response = curl_exec($ch);
    $http = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err = curl_error($ch);
    curl_close($ch);

    $respJson = null;
    if (is_string($response) && $response !== '') {
        $respJson = json_decode($response, true);
    }

    return [$http >= 200 && $http < 300, $http, $respJson, $err];
}

$raw = file_get_contents('php://input');
$body = json_decode($raw, true);
if (!is_array($body)) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'Invalid JSON body']);
    exit;
}

$status = strtolower(trim((string)($body['status'] ?? 'waiting_payment')));
if (!in_array($status, ['waiting_payment', 'paid'], true)) {
    $status = 'waiting_payment';
}

$orderId = trim((string)($body['transaction_id'] ?? $body['orderId'] ?? ''));
if ($orderId === '') {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'Missing transaction_id']);
    exit;
}

$amount = (float)($body['amount'] ?? 0);
$amountCents = (int)round($amount * 100);
if ($amountCents < 0) $amountCents = 0;

$customer = is_array($body['customer'] ?? null) ? $body['customer'] : [];
$utms = is_array($body['utms'] ?? null) ? $body['utms'] : [];

// Garantir que email nunca seja vazio (Utmify pode rejeitar sem email)
if (empty($customer['email']) || !filter_var($customer['email'] ?? '', FILTER_VALIDATE_EMAIL)) {
    // Gerar email placeholder baseado no orderId para consistencia
    $safeId = preg_replace('/[^a-zA-Z0-9]/', '', $orderId);
    $customer['email'] = $safeId . '@cliente.temp';
}

// Garantir que name nunca seja vazio
if (empty(trim((string)($customer['name'] ?? '')))) {
    $customer['name'] = 'Cliente';
}
$productId = trim((string)($body['product_id'] ?? 'front-checkout'));
$productName = trim((string)($body['product_name'] ?? 'Produto'));
$method = strtolower(trim((string)($body['method'] ?? 'pix')));
// Mapear metodos de pagamento para valores aceites pela API Utmify
$methodMap = [
    'pix' => 'pix',
    'credit_card' => 'credit_card',
    'boleto' => 'boleto',
    'paypal' => 'paypal',
    'free_price' => 'free_price',
    'mbway' => 'pix',           // MB Way -> pix (mais proximo aceite pela Utmify)
    'multibanco' => 'boleto',   // Multibanco -> boleto (referencia bancaria)
    'mb' => 'pix',
];
$paymentMethod = $methodMap[$method] ?? 'pix';

$createdAt = utc_now_str();
$approvedDate = null;

if ($status === 'paid') {
    $savedRaw = @file_get_contents(pending_path($orderId));
    $saved = is_string($savedRaw) ? json_decode($savedRaw, true) : null;
    if (is_array($saved)) {
        $createdAt = (string)($saved['createdAt'] ?? $createdAt);
        if (!empty($saved['customer']) && is_array($saved['customer'])) $customer = $saved['customer'];
        if (!empty($saved['utms']) && is_array($saved['utms'])) $utms = $saved['utms'];
        if (!empty($saved['product_id'])) $productId = (string)$saved['product_id'];
        if (!empty($saved['product_name'])) $productName = (string)$saved['product_name'];
        if (!empty($saved['amount_cents'])) $amountCents = (int)$saved['amount_cents'];
        if (!empty($saved['payment_method'])) $paymentMethod = (string)$saved['payment_method'];
    }
    $approvedDate = utc_now_str();
}

$payload = [
    'orderId' => $orderId,
    'platform' => UTMIFY_PLATFORM,
    'paymentMethod' => $paymentMethod,
    'status' => $status,
    'createdAt' => $createdAt,
    'approvedDate' => $approvedDate,
    'refundedAt' => null,
    'customer' => [
        'name' => (string)($customer['name'] ?? ''),
        'email' => (string)($customer['email'] ?? ''),
        'phone' => (string)($customer['phone'] ?? null),
        'document' => (string)($customer['document'] ?? null),
    ],
    'products' => [[
        'id' => $productId !== '' ? $productId : 'front-checkout',
        'name' => $productName !== '' ? $productName : 'Produto',
        'planId' => null,
        'planName' => null,
        'quantity' => 1,
        'priceInCents' => $amountCents,
    ]],
    'trackingParameters' => [
        'src' => $utms['src'] ?? null,
        'sck' => $utms['sck'] ?? null,
        'utm_source' => $utms['utm_source'] ?? null,
        'utm_campaign' => $utms['utm_campaign'] ?? null,
        'utm_medium' => $utms['utm_medium'] ?? null,
        'utm_content' => $utms['utm_content'] ?? null,
        'utm_term' => $utms['utm_term'] ?? null,
    ],
    'commission' => [
        'totalPriceInCents' => $amountCents,
        'gatewayFeeInCents' => 0,
        'userCommissionInCents' => $amountCents,
        'currency' => 'EUR',
    ],
    'isTest' => false,
];

// Log do payload que sera enviado para debug
utmify_log('info', 'Enviando para Utmify', [
    'orderId' => $orderId,
    'status' => $status,
    'amount_cents' => $amountCents,
    'product_id' => $productId,
    'has_utms' => !empty(array_filter($utms)),
]);

// Envio com retry (max 2 tentativas)
$maxRetries = 2;
$ok = false;
$http = 0;
$respJson = null;
$curlErr = '';

for ($attempt = 1; $attempt <= $maxRetries; $attempt++) {
    [$ok, $http, $respJson, $curlErr] = utmify_send($payload);

    if ($ok) {
        utmify_log('info', 'Utmify OK', [
            'orderId' => $orderId,
            'status' => $status,
            'http' => $http,
            'attempt' => $attempt,
        ]);
        break;
    }

    utmify_log('error', 'Utmify FALHOU', [
        'orderId' => $orderId,
        'status' => $status,
        'http' => $http,
        'curl_error' => $curlErr,
        'response' => $respJson,
        'attempt' => $attempt,
    ]);

    if ($attempt < $maxRetries) {
        usleep(500000); // 500ms antes de retry
    }
}

// Se falhou apos todos os retries, salvar para reprocessamento manual
if (!$ok) {
    utmify_save_failed($orderId, $payload, $http, $respJson, $curlErr);
}

if ($status === 'paid') {
    // TikTok CAPI - only for front-checkout (original behavior)
    if ($productId === 'front-checkout') {
        tiktok_send_event('CompletePayment', [
            'event_id' => $orderId,
            'amount' => $amount,
            'product_id' => $productId,
            'product_name' => $productName,
            'customer' => $customer,
        ]);
    }

    // Meta Conversions API - Purchase event for ALL paid transactions
    meta_capi_send_event('Purchase', [
        'event_id' => $orderId,
        'order_id' => $orderId,
        'amount' => $amount,
        'product_id' => $productId,
        'product_name' => $productName,
        'customer' => $customer,
    ]);
}

if ($status === 'waiting_payment') {
    $pending = [
        'createdAt' => $createdAt,
        'customer' => $customer,
        'utms' => $utms,
        'product_id' => $productId,
        'product_name' => $productName,
        'amount_cents' => $amountCents,
        'payment_method' => $paymentMethod,
    ];
    @file_put_contents(pending_path($orderId), json_encode($pending, JSON_UNESCAPED_UNICODE));
}

if ($status === 'paid' && $ok) {
    @unlink(pending_path($orderId));
}

echo json_encode([
    'ok' => $ok,
    'status' => $status,
    'http' => $http,
    'curl_error' => $curlErr !== '' ? $curlErr : null,
    'upstream' => $respJson,
], JSON_UNESCAPED_UNICODE);
exit;

