<?php
require "../config.php";
ini_set('display_errors', 1);
error_reporting(E_ALL);
header('Content-Type: application/json');

$payevo_secret = isset($payevo_secret_key) ? (string)$payevo_secret_key : (string)($token_payment ?? '');
if ($payevo_secret === '') { echo json_encode(['success'=>false,'status'=>'UNKNOWN','isPaid'=>false,'error'=>'Chave secreta Payevo não configurada em OFERTA DO VITAO/config.php']); exit; }

// ===== Config / Paths =====
const PIX_DB_PATH = __DIR__ . '/dutty.json';   // fallback local (mesmo “banco” usado no gerar.php)
const UTM_SENT_DIR = __DIR__ . '/utm_sent';    // marca envios já feitos p/ evitar duplicidade

// ===== Helpers =====
function load_db(string $path): array {
    if (!file_exists($path) || filesize($path) === 0) return [];
    $json = file_get_contents($path);
    $data = json_decode($json, true);
    return is_array($data) ? $data : [];
}

/** Normaliza status para o front (APPROVED = pago) */
function map_status_for_front(?string $raw): string {
    $raw = strtoupper(trim((string)$raw));
    if (in_array($raw, ['COMPLETED','PAID','APPROVED','SUCCEEDED','CONCLUDED','AUTHORIZED'], true)) return 'APPROVED';
    if (in_array($raw, ['PENDING','WAITING_PAYMENT','PENDING_PAYMENT'], true)) return 'PENDING';
    if (in_array($raw, ['REFUSED','DECLINED'], true)) return 'DECLINED';
    if (in_array($raw, ['CANCELED','CANCELLED'], true)) return 'CANCELLED';
    return $raw !== '' ? $raw : 'UNKNOWN';
}

/** GET JSON com cURL */
function http_get_json(string $url): array {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_TIMEOUT        => 20,
        CURLOPT_CONNECTTIMEOUT => 8,
        CURLOPT_HTTPGET        => true,
        CURLOPT_HTTPHEADER     => ['Accept: application/json'],
    ]);
    $res  = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err  = curl_error($ch);
    curl_close($ch);

    if ($err) return ['error' => 'Erro de rede: '.$err, '_http' => $code];
    $json = json_decode($res, true);
    if (!is_array($json)) $json = ['error' => 'Resposta inválida: '.$res, '_http' => $code];
    if ($code < 200 || $code >= 300) {
        if (!isset($json['error'])) $json['error'] = 'HTTP '.$code;
        $json['_http'] = $code;
    }
    return $json;
}

/** Consulta status na Duttyfy (apenas UMA URL) */
function payevo_status(string $payevo_secret, string $transactionId): array {
    $k = trim((string)$payevo_secret);
    if ($k === '') return ['error' => 'Chave Payevo ausente'];

    $tid = trim((string)$transactionId);
    if ($tid === '') return ['error' => 'transactionId vazio'];

    $url = "https://apiv2.payevo.com.br/functions/v1/transactions/" . urlencode($tid);

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPGET        => true,
        CURLOPT_TIMEOUT        => 20,
        CURLOPT_CONNECTTIMEOUT => 8,
        CURLOPT_HTTPHEADER     => [
            'Accept: application/json',
            'Authorization: Basic ' . base64_encode($k),
        ],
    ]);
    $res  = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err  = curl_error($ch);
    curl_close($ch);

    if ($err) return ['error' => 'Erro de rede: '.$err, '_http' => $code];
    $json = json_decode((string)$res, true);
    if (!is_array($json)) $json = ['error' => 'Resposta inválida: '.$res, '_http' => $code];
    if ($code < 200 || $code >= 300) {
        $msg = $json['message'] ?? $json['error'] ?? $json['errors'] ?? ('HTTP '.$code);
        return ['error' => is_string($msg) ? $msg : json_encode($msg, JSON_UNESCAPED_UNICODE), '_http' => $code];
    }
    return $json;
}


/** Encontra o registro completo do TX no dutty.json */
function find_db_row_by_tx(string $id): ?array {
    $db = load_db(PIX_DB_PATH);
    for ($i = count($db) - 1; $i >= 0; $i--) {
        $row = $db[$i];
        if (!is_array($row)) continue;
        $txRow  = (string)($row['transactionId'] ?? '');
        $txResp = '';
        if (isset($row['resp']) && is_array($row['resp'])) {
            $txResp = (string)($row['resp']['transactionId'] ?? '');
        }
        if ($txRow === $id || $txResp === $id) {
            return $row;
        }
    }
    return null;
}

/** Fallback: procura no JSON local pelo transactionId (string/UUID) */
function fallback_local(string $id): array {
    $row = find_db_row_by_tx($id);
    if ($row) {
        $raw = '';
        if (isset($row['resp']) && is_array($row['resp'])) {
            $raw = (string)($row['resp']['status'] ?? '');
        }
        if ($raw === '' && isset($row['status'])) {
            $raw = (string)$row['status'];
        }
        return [
            'source'         => 'cache',
            'raw_status'     => $raw,
            'status'         => map_status_for_front($raw),
            'transaction_id' => $id,
            'paidAt'         => null,
            'success'        => true,
            'found'          => true,
        ];
    }
    return [
        'source'         => 'cache',
        'raw_status'     => null,
        'status'         => 'UNKNOWN',
        'transaction_id' => $id,
        'paidAt'         => null,
        'success'        => true,
        'found'          => false,
    ];
}

/** Cria diretório de flags se necessário */
function ensure_dir(string $dir): void {
    if (!is_dir($dir)) {
        @mkdir($dir, 0775, true);
    }
}

/** Caminho do flag de envio UTM por transação */
function utm_flag_path(string $tx): string {
    $safe = preg_replace('/[^A-Za-z0-9_.-]/', '_', $tx);
    return UTM_SENT_DIR . '/' . $safe . '.ok';
}

/** Dispara add_utm uma única vez por transação (idempotente via arquivo-flag) */
function maybe_dispatch_utm(string $txId, ?array $row, ?string $utmfy_token): void {
    if (!$row) return;
    if (!$utmfy_token) return;

    ensure_dir(UTM_SENT_DIR);
    $flag = utm_flag_path($txId);
    if (file_exists($flag)) return; // já enviado

    // Extrai dados do "banco"
    $lead   = $row['lead'] ?? [];
    $nome   = (string)($lead['name']     ?? '');
    $cpf    = (string)($lead['document'] ?? '');
    $email  = (string)($lead['email']    ?? '');
    $fone   = (string)($lead['phone']    ?? '');
    $valor  = (int)   ($row['valor_centavos'] ?? 0);

    $meta   = $row['meta'] ?? [];
    $utm_source   = $meta['utm_source']   ?? null;
    $utm_campaign = $meta['utm_campaign'] ?? null;
    $utm_medium   = $meta['utm_medium']   ?? null;
    $utm_content  = $meta['utm_content']  ?? null;
    $utm_term     = $meta['utm_term']     ?? null;

    // Garante existência da função add_utm (usa definição abaixo se necessário)
    if (!function_exists('add_utm')) {
        // define fallback (a mesma que você enviou)
        function add_utm($nome, $cpf, $email, $telefone, $valor, $utm_source, $utm_campaign, $utm_medium, $utm_content, $utm_term, $token, $utm_token){
            $apiUrl = 'https://api.utmify.com.br/api-credentials/orders';
            $apiToken = $utm_token;

            $amount = $valor; // em centavos
            $amount = number_format((float)str_replace(',', '.', $valor / 100), 2, '.', '');

            $gatewayFee = 0;
            $userCommission = $amount - $gatewayFee;
            $amountCents = (int) preg_replace('/\D+/', '', (string)$amount);

            $createdAt = date('Y-m-d H:i:s');

            $telefone_limpo = preg_replace('/\D/', '', $telefone);
            $cpf_limpo = preg_replace('/\D/', '', $cpf);

            $payload = [
                "orderId" => rand(10000, 19999),
                "platform" => "Pix",
                "paymentMethod" => "pix",
                "status" => "paid",
                "createdAt" => $createdAt,
                "approvedDate" => date("Y-m-d H:i:s"),
                "refundedAt" => null,
                "customer" => [
                    "name" => "".$nome."",
                    "email" => "".$email."",
                    "phone" => "".$telefone_limpo."",
                    "document" => "".$cpf_limpo."",
                    "country" => "BR"
                ],
                "products" => [[
                    "id" => "produto-externo",
                    "name" => "Produto Externo",
                    "planId" => 11,
                    "planName" => 'externo',
                    "quantity" => 1,
                    "priceInCents" => $amount
                ]],
                "trackingParameters" => [
                    "utm_source" => "".$utm_source."",
                    "utm_campaign" => "".$utm_campaign."",
                    "utm_medium" => "".$utm_medium."",
                    "utm_content" => "".$utm_content."",
                    "utm_term" => "".$utm_term.""
                ],
                "commission" => [
                    "totalPriceInCents" => $amountCents,
                    "gatewayFeeInCents" => $gatewayFee,
                    "userCommissionInCents" => $amountCents
                ],
                "isTest" => false
            ];

            $ch = curl_init($apiUrl);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/json',
                'x-api-token: ' . $apiToken
            ]);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));

            $response = curl_exec($ch);
            // Se quiser logar: file_put_contents(__DIR__.'/utmify_dispatch.log', '['.date('c')."] TX=$token RES=".$response."\n", FILE_APPEND);
            curl_close($ch);
        }
    }

    // Dispara
    try {
        add_utm($nome, $cpf, $email, $fone, $valor, $utm_source, $utm_campaign, $utm_medium, $utm_content, $utm_term, $txId, $utmfy_token);
        // marca flag para evitar duplicidade
        @file_put_contents($flag, date('c'));
    } catch (\Throwable $e) {
        // log opcional de erro
        @file_put_contents(__DIR__.'/utmify_dispatch.log', '['.date('c')."] TX=$txId ERROR=".$e->getMessage()."\n", FILE_APPEND);
    }
}

// ===== Entrada =====
$id = isset($_GET['id']) ? trim($_GET['id']) : (isset($_GET['transactionId']) ? trim($_GET['transactionId']) : '');
if ($id === '') {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Parâmetro id vazio']);
    exit;
}

// Captura a chave (prioridade: query -> variáveis -> env)
$duttyfy_secret = $token_payment ?? '';
$cfgCandidates = [
    $_GET['key'] ?? null,               // override via query (teste rápido)
    isset($duttyfy_secret) ? $duttyfy_secret : null,
    isset($token_payment_duttyfy) ? $token_payment_duttyfy : null,
    isset($token_payment) ? $token_payment : null,
    getenv('DUTTYFY_SECRET') ?: null,
];
foreach ($cfgCandidates as $cand) {
    if ($cand && is_string($cand) && trim($cand) !== '') { $duttyfy_secret = $cand; break; }
}

if ($duttyfy_secret === '') {
    // sem chave -> tenta só o fallback local
    $fb = fallback_local($id);
    echo json_encode($fb);
    exit;
}

// ===== Chama API da Duttyfy =====
$api = payevo_status($duttyfy_secret, $id);

// Erros de API
if (isset($api['error'])) {
    $msg = (string)$api['error'];
    $low = mb_strtolower($msg);

    // chave inválida -> devolve erro explícito
    if (strpos($low, 'chave') !== false && strpos($low, 'inválida') !== false) {
        echo json_encode([
            'success'        => false,
            'error'          => $msg,
            'status'         => 'UNKNOWN',
            'raw_status'     => null,
            'transaction_id' => $id,
        ]);
        exit;
    }

    // transação não encontrada -> fallback local
    if (strpos($low, 'não encontrada') !== false) {
        $fb = fallback_local($id);
        echo json_encode($fb);
        exit;
    }

    // erro genérico -> mantém polling sem quebrar
    echo json_encode([
        'success'        => true,
        'status'         => 'UNKNOWN',
        'raw_status'     => null,
        'transaction_id' => $id,
        'error'          => $msg,
        'source'         => 'api',
    ]);
    exit;
}

// Sucesso API
$raw   = isset($api['status']) ? (string)$api['status'] : '';
$paid  = $api['paidAt'] ?? null;

$mapped = map_status_for_front($raw);

// $mapped = 'APPROVED';
// === NOVO: se pago/aprovado, dispara UTMify uma vez ===
if ($mapped === 'APPROVED') {
    // carrega dados do dutty.json para montar o payload do UTMify
    $row = find_db_row_by_tx($id);
    // token do UTMify vem do config (ex.: $utmfy_token)
    $utm_token = isset($utmfy_token) ? $utmfy_token : null;
    maybe_dispatch_utm($id, $row, $utm_token);
}

echo json_encode([
    'success'        => true,
    'found'          => true,
    'status'         => $mapped,       // APPROVED | PENDING | ...
    'raw_status'     => $raw,          // "PENDING" | "COMPLETED"
    'paid_at'        => $paid,
    'transaction_id' => $id,
    'source'         => 'api',
]);
