<?php
declare(strict_types=1);
require_once dirname(__DIR__) . '/includes/payment_revenda_helper.php';

header("Content-Type: application/json; charset=UTF-8");
require_once __DIR__ . '/../includes/whatsapp_helper.php';

$dbPath = dirname(__DIR__) . "/db.db";
$jsonFile = dirname(__DIR__) . "/thefulltv_pagamentos.json";

/*
|--------------------------------------------------------------------------
| HELPERS
|--------------------------------------------------------------------------
*/
function webhookLog(string $msg): void
{
    file_put_contents(
        __DIR__ . "/thefulltv_webhook.log",
        date("[Y-m-d H:i:s] ") . $msg . "\n",
        FILE_APPEND
    );
}

function webhookDumpLog(string $raw, array $headers): void
{
    file_put_contents(
        __DIR__ . "/thefulltv_webhook_dump.log",
        date("[Y-m-d H:i:s] ") . "RAW: $raw\nHEADERS: " . json_encode($headers, JSON_UNESCAPED_UNICODE) . "\n\n",
        FILE_APPEND
    );
}

function jsonResponse(array $data, int $httpCode = 200): void
{
    http_response_code($httpCode);
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

function abrirDb(string $dbPath): PDO
{
    $db = new PDO("sqlite:" . $dbPath, null, null, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);

    return $db;
}

function columnExists(PDO $db, string $table, string $column): bool
{
    $stmt = $db->query("PRAGMA table_info($table)");
    $columns = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($columns as $col) {
        if (($col["name"] ?? "") === $column) {
            return true;
        }
    }

    return false;
}

function garantirColunasConfig(PDO $db): void
{
    if (!columnExists($db, "pushin_config", "mercado_pago_token")) {
        $db->exec("ALTER TABLE pushin_config ADD COLUMN mercado_pago_token TEXT");
        webhookLog("Coluna pushin_config.mercado_pago_token criada");
    }

    if (!columnExists($db, "pushin_config", "webhook_token")) {
        $db->exec("ALTER TABLE pushin_config ADD COLUMN webhook_token TEXT");
        webhookLog("Coluna pushin_config.webhook_token criada");
    }

    if (!columnExists($db, "pushin_config", "paypal_client_id")) {
        $db->exec("ALTER TABLE pushin_config ADD COLUMN paypal_client_id TEXT");
        webhookLog("Coluna pushin_config.paypal_client_id criada");
    }

    if (!columnExists($db, "pushin_config", "paypal_client_secret")) {
        $db->exec("ALTER TABLE pushin_config ADD COLUMN paypal_client_secret TEXT");
        webhookLog("Coluna pushin_config.paypal_client_secret criada");
    }

    if (!columnExists($db, "pushin_config", "paypal_mode")) {
        $db->exec("ALTER TABLE pushin_config ADD COLUMN paypal_mode TEXT");
        webhookLog("Coluna pushin_config.paypal_mode criada");
    }

    if (!columnExists($db, "pushin_config", "paypal_webhook_id")) {
        $db->exec("ALTER TABLE pushin_config ADD COLUMN paypal_webhook_id TEXT");
        webhookLog("Coluna pushin_config.paypal_webhook_id criada");
    }
}

function obterConfigPushin(PDO $db): array
{
    $stmt = $db->query("
        SELECT
            pushin_token,
            webhook_token,
            mercado_pago_token,
            paypal_client_id,
            paypal_client_secret,
            paypal_mode,
            paypal_webhook_id
        FROM pushin_config
        WHERE id = 1
        LIMIT 1
    ");

    $cfg = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$cfg) {
        return [
            "pushin_token" => "",
            "webhook_token" => "",
            "mercado_pago_token" => "",
            "paypal_client_id" => "",
            "paypal_client_secret" => "",
            "paypal_mode" => "sandbox",
            "paypal_webhook_id" => "",
        ];
    }

    return [
        "pushin_token" => trim((string)($cfg["pushin_token"] ?? "")),
        "webhook_token" => trim((string)($cfg["webhook_token"] ?? "")),
        "mercado_pago_token" => trim((string)($cfg["mercado_pago_token"] ?? "")),
        "paypal_client_id" => trim((string)($cfg["paypal_client_id"] ?? "")),
        "paypal_client_secret" => trim((string)($cfg["paypal_client_secret"] ?? "")),
        "paypal_mode" => trim((string)($cfg["paypal_mode"] ?? "sandbox")),
        "paypal_webhook_id" => trim((string)($cfg["paypal_webhook_id"] ?? "")),
    ];
}

function obterTokenWebhookPushin(PDO $db): string
{
    $cfg = obterConfigPushin($db);

    if ($cfg["webhook_token"] !== "") {
        return $cfg["webhook_token"];
    }

    return $cfg["pushin_token"];
}

function obterTokenMercadoPago(PDO $db): string
{
    $cfg = obterConfigPushin($db);
    return $cfg["mercado_pago_token"];
}

function normalizarMac(?string $mac): string
{
    $mac = strtoupper(trim((string)$mac));

    if ($mac === "") {
        return "";
    }

    $mac = preg_replace('/[^A-F0-9]/', '', $mac);

    if (strlen($mac) !== 12) {
        return "";
    }

    $normalizado = implode(":", str_split($mac, 2));

    if ($normalizado === "00:00:00:00:00:00" || $normalizado === "02:00:00:00:00:00") {
        return "";
    }

    return $normalizado;
}

function garantirArquivoPagamentos(string $path): void
{
    if (!file_exists($path)) {
        file_put_contents(
            $path,
            json_encode(["pagamentos" => []], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
        );
    }
}

function carregarPagamentos(string $path): array
{
    garantirArquivoPagamentos($path);

    $raw = @file_get_contents($path);
    $json = json_decode((string)$raw, true);

    if (!is_array($json) || !isset($json["pagamentos"]) || !is_array($json["pagamentos"])) {
        return ["pagamentos" => []];
    }

    return $json;
}

function salvarPagamentos(string $path, array $store): bool
{
    $fp = fopen($path, "c+");
    if (!$fp) {
        return false;
    }

    try {
        if (!flock($fp, LOCK_EX)) {
            fclose($fp);
            return false;
        }

        rewind($fp);
        ftruncate($fp, 0);
        fwrite($fp, json_encode($store, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
        fflush($fp);
        flock($fp, LOCK_UN);
        fclose($fp);

        return true;
    } catch (Throwable $e) {
        @flock($fp, LOCK_UN);
        @fclose($fp);
        return false;
    }
}

function httpGetJson(string $url, array $headers = [], int $timeout = 20): array
{
    $ch = curl_init($url);

    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_HTTPHEADER => $headers,
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);

    curl_close($ch);

    $decoded = null;
    if ($response !== false && $response !== null && $response !== "") {
        $decoded = json_decode($response, true);
    }

    return [
        "http_code" => $httpCode,
        "response_raw" => $response,
        "response_json" => $decoded,
        "error" => $error,
    ];
}

function httpPostJson(string $url, array $headers, array $payload, int $timeout = 30): array
{
    $ch = curl_init($url);

    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE),
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_CONNECTTIMEOUT => 10,
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);

    curl_close($ch);

    $decoded = null;
    if ($response !== false && $response !== null && $response !== "") {
        $decoded = json_decode($response, true);
    }

    return [
        "http_code" => $httpCode,
        "response_raw" => $response,
        "response_json" => $decoded,
        "error" => $error,
    ];
}

function httpPostFormBasicAuth(string $url, array $headers, string $body, string $userPwd, int $timeout = 30): array
{
    $ch = curl_init($url);

    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POSTFIELDS => $body,
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_USERPWD => $userPwd,
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);

    curl_close($ch);

    $decoded = null;
    if ($response !== false && $response !== null && $response !== "") {
        $decoded = json_decode($response, true);
    }

    return [
        "http_code" => $httpCode,
        "response_raw" => $response,
        "response_json" => $decoded,
        "error" => $error,
    ];
}

function buscarPagamentoPorPaymentId(array &$store, string $paymentId): array
{
    foreach ($store["pagamentos"] as $i => &$pg) {
        if (strtolower((string)($pg["payment_id"] ?? "")) === strtolower($paymentId)) {
            return ["index" => $i, "pagamento" => &$pg];
        }
    }

    $null = null;
    return ["index" => -1, "pagamento" => &$null];
}

function buscarPagamentoPorExternalReference(array &$store, string $externalReference): array
{
    foreach ($store["pagamentos"] as $i => &$pg) {
        if (strtolower((string)($pg["external_reference"] ?? "")) === strtolower($externalReference)) {
            return ["index" => $i, "pagamento" => &$pg];
        }
    }

    $null = null;
    return ["index" => -1, "pagamento" => &$null];
}

function statusEhPago(string $status): bool
{
    $status = strtolower(trim($status));
    return in_array($status, ["paid", "approved", "completed", "accredited"], true);
}

function diasPlano(array $pagamento): int
{
    return intval($pagamento["produtos"]["dias"] ?? 0);
}

function atualizarStatusPagamento(array &$pagamento, string $status, ?array $detalhes = null, ?string $detalheCampo = null): void
{
    $pagamento["status"] = strtolower($status);
    $pagamento["updated_at"] = date("Y-m-d H:i:s");

    if ($detalhes !== null && $detalheCampo !== null) {
        $pagamento[$detalheCampo] = $detalhes;
    }
}

function registrarBaixaSqlite(PDO $db, array $pagamento, string $username, string $mac, int $diasPlano): void
{
    try {
        $db->exec("
            CREATE TABLE IF NOT EXISTS pagamentos_pix_baixas (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                payment_id TEXT,
                gateway_nome TEXT,
                external_reference TEXT,
                mac TEXT,
                username TEXT,
                dias INTEGER,
                valor REAL,
                status TEXT,
                payload_json TEXT,
                criado_em TEXT
            )
        ");

        $stmt = $db->prepare("
            INSERT INTO pagamentos_pix_baixas
            (payment_id, gateway_nome, external_reference, mac, username, dias, valor, status, payload_json, criado_em)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");

        $stmt->execute([
            (string)($pagamento["payment_id"] ?? ""),
            (string)($pagamento["gateway_nome"] ?? ""),
            (string)($pagamento["external_reference"] ?? ""),
            $mac,
            $username,
            $diasPlano,
            floatval($pagamento["total"] ?? 0),
            strtolower((string)($pagamento["status"] ?? "")),
            json_encode($pagamento, JSON_UNESCAPED_UNICODE),
            date("Y-m-d H:i:s"),
        ]);
    } catch (Throwable $e) {
        webhookLog("Falha ao registrar baixa no SQLite: " . $e->getMessage());
    }
}

function renovarUsuarioPorMac(PDO $db, string $mac, int $diasPlano, array $pagamento): array
{
    $mac = normalizarMac($mac);

    if ($mac === "") {
        return ["success" => false, "error" => "MAC inválido"];
    }

    if ($diasPlano <= 0) {
        return ["success" => false, "error" => "Dias do plano inválido"];
    }

    $stmt = $db->prepare("SELECT * FROM usuarios WHERE mac = ? LIMIT 1");
    $stmt->execute([$mac]);
    $usuario = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$usuario) {
        return [
            "success" => false,
            "error" => "Usuário não encontrado pelo MAC",
            "mac" => $mac
        ];
    }

    $username = trim((string)($usuario["username"] ?? ""));
    $agora = time();
    $vencimentoAtual = intval($usuario["vencimento"] ?? 0);

    if ($vencimentoAtual > $agora) {
        $novoVencimento = $vencimentoAtual + ($diasPlano * 86400);
    } else {
        $novoVencimento = $agora + ($diasPlano * 86400);
    }

    $up = $db->prepare("
        UPDATE usuarios
        SET status = 'ativo',
            vencimento = ?,
            whatsapp_activated_at = strftime('%s','now')
        WHERE mac = ?
    ");
    $up->execute([$novoVencimento, $mac]);

    registrarBaixaSqlite($db, $pagamento, $username, $mac, $diasPlano);

    if ($username !== "") {
        $apiUrl = "https://xtream.thefull.site/api/renovar_user.php?token=TOKEN_APP_123456";

        $payload = json_encode([
            "usuario" => $username,
            "dias" => $diasPlano
        ], JSON_UNESCAPED_UNICODE);

        $ch = curl_init($apiUrl);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_HTTPHEADER => ["Content-Type: application/json"],
            CURLOPT_TIMEOUT => 20
        ]);
        $resp = curl_exec($ch);
        $err = curl_error($ch);
        curl_close($ch);

        webhookLog("XTREAM RENOVAR USER={$username} DIAS={$diasPlano} RESP=" . ($resp ?: "") . " ERR=" . ($err ?: ""));
    }

    webhookLog("USUARIO RENOVADO MAC={$mac} USER={$username} DIAS={$diasPlano} VENCIMENTO=" . date("Y-m-d H:i:s", $novoVencimento));

    // Integração principal com o bot Node.js para confirmar a renovação no WhatsApp.
    if (!empty($usuario['whatsapp'])) {
        wa_ensure_schema($db);
        $templates = wa_get_templates($db);
        $usuario['vencimento'] = $novoVencimento;
        $payloadZap = wa_build_user_payload($usuario, (string)($templates['confirmacao_renovacao'] ?? ''), 'confirmacao_renovacao', $diasPlano . ' dias');
        $botResp = wa_bot_request($db, 'POST', '/send', $payloadZap);
        wa_log_send($db, $payloadZap, $botResp);
        webhookLog('WHATSAPP RENOVACAO MAC=' . $mac . ' RESP=' . json_encode($botResp['data'] ?? [], JSON_UNESCAPED_UNICODE));
    }

    return [
        "success" => true,
        "mac" => $mac,
        "username" => $username,
        "novo_vencimento_ts" => $novoVencimento,
        "novo_vencimento" => date("Y-m-d H:i:s", $novoVencimento),
    ];
}

function processarBaixa(PDO $db, string $jsonFile, array &$store, array &$pagamento, string $status, ?array $detalhes = null, ?string $detalheCampo = null): array
{
    revenda_credit_ensure_schema($db);
    atualizarStatusPagamento($pagamento, $status, $detalhes, $detalheCampo);

    if (!salvarPagamentos($jsonFile, $store)) {
        return [
            "success" => false,
            "error" => "Falha ao salvar JSON de pagamentos"
        ];
    }

    $paymentContext = is_array($pagamento['payment_context'] ?? null) ? $pagamento['payment_context'] : [];
    if (($paymentContext['type'] ?? '') === 'revenda_credito') {
        revenda_credit_upsert_order($db, [
            'payment_id' => (string)($pagamento['payment_id'] ?? ''),
            'external_reference' => (string)($pagamento['external_reference'] ?? ''),
            'revendedor_id' => (int)($paymentContext['revendedor_id'] ?? 0),
            'opcao_id' => isset($paymentContext['opcao_id']) ? (int)$paymentContext['opcao_id'] : null,
            'creditos' => (int)($paymentContext['creditos'] ?? 0),
            'valor' => (float)($pagamento['total'] ?? 0),
            'gateway_nome' => (string)($pagamento['gateway_nome'] ?? ''),
            'status' => strtolower((string)$status),
            'payload_json' => json_encode($pagamento, JSON_UNESCAPED_UNICODE),
        ]);
    }

    if (!statusEhPago($status)) {
        webhookLog("STATUS ATUALIZADO, MAS AINDA NÃO PAGO → payment_id=" . ($pagamento["payment_id"] ?? "") . " status={$status}");
        return [
            "success" => true,
            "paid" => false,
            "status" => $status
        ];
    }

    if (($paymentContext['type'] ?? '') === 'revenda_credito') {
        $creditResult = revenda_credit_apply_payment($db, $pagamento);
        if (!$creditResult['success']) {
            webhookLog('ERRO AO CREDITAR REVENDa ' . json_encode($creditResult, JSON_UNESCAPED_UNICODE));
            return $creditResult;
        }
        webhookLog('CREDITOS APLICADOS REVENDa payment_id=' . ($pagamento['payment_id'] ?? '') . ' resultado=' . json_encode($creditResult, JSON_UNESCAPED_UNICODE));
        return $creditResult + ['paid' => true, 'status' => $status];
    }

    if (($paymentContext['type'] ?? '') === 'chatbot_renovacao') {
        return renovarUsuarioPorContexto($db, $paymentContext, $pagamento);
    }

    if (($paymentContext['type'] ?? '') === 'chatbot_revenda_criar') {
        return criarRevendaPorPagamentoChatbot($db, $paymentContext, $pagamento);
    }

    if (($paymentContext['type'] ?? '') === 'chatbot_revenda_renovar') {
        return renovarRevendaPorPagamentoChatbot($db, $paymentContext, $pagamento);
    }

    $mac = normalizarMac((string)($pagamento["mac"] ?? ""));
    $dias = diasPlano($pagamento);

    if ($mac === "") {
        return ["success" => false, "error" => "Pagamento pago sem MAC válido"];
    }

    if ($dias <= 0) {
        return ["success" => false, "error" => "Pagamento pago sem dias do plano"];
    }

    return renovarUsuarioPorMac($db, $mac, $dias, $pagamento);
}


function renovarUsuarioPorContexto(PDO $db, array $paymentContext, array $pagamento): array
{
    $diasPlano = max(1, (int)($paymentContext['dias'] ?? diasPlano($pagamento) ?? 0));
    $usuarioId = (int)($paymentContext['usuario_id'] ?? 0);
    $whatsapp = preg_replace('/\D+/', '', (string)($paymentContext['whatsapp'] ?? $pagamento['whatsapp'] ?? ''));

    if ($usuarioId > 0) {
        $st = $db->prepare("SELECT rowid AS rid, * FROM usuarios WHERE rowid = ? OR usuario_id = ? LIMIT 1");
        $st->execute([$usuarioId, $usuarioId]);
        $usuario = $st->fetch(PDO::FETCH_ASSOC) ?: null;
        if ($usuario) {
            return renovarUsuarioPorMac($db, (string)($usuario['mac'] ?? ''), $diasPlano, $pagamento);
        }
    }

    if ($whatsapp !== '') {
        $st = $db->prepare("SELECT rowid AS rid, * FROM usuarios WHERE replace(replace(replace(replace(COALESCE(whatsapp,''), '+', ''), '-', ''), '(', ''), ')', '') LIKE ? ORDER BY rowid DESC LIMIT 1");
        $st->execute(['%' . $whatsapp . '%']);
        $usuario = $st->fetch(PDO::FETCH_ASSOC) ?: null;
        if ($usuario) {
            return renovarUsuarioPorMac($db, (string)($usuario['mac'] ?? ''), $diasPlano, $pagamento);
        }
    }

    return ['success' => false, 'error' => 'Usuário não localizado para renovação do chatbot'];
}

function gerarCredencialChatbot(string $prefix): string
{
    return strtolower($prefix . substr(bin2hex(random_bytes(6)), 0, 6));
}

function criarRevendaPorPagamentoChatbot(PDO $db, array $paymentContext, array $pagamento): array
{
    $creditos = (int)($paymentContext['creditos'] ?? 0);
    $nome = trim((string)($pagamento['nome'] ?? 'Revenda WhatsApp'));
    $whatsapp = preg_replace('/\D+/', '', (string)($pagamento['whatsapp'] ?? ''));
    $email = trim((string)($pagamento['email'] ?? ''));
    if ($email === '') {
        $email = 'revenda' . substr($whatsapp ?: (string)time(), -6) . '@thefulltv.local';
    }
    $username = gerarCredencialChatbot('rev');
    $password = gerarCredencialChatbot('tv');
    $vencimento = date('Y-m-d', strtotime('+30 days'));
    $st = $db->prepare("INSERT INTO revendedores (username,password,email,status,nome,mac_limit,vencimento,creditos,whatsapp) VALUES (?,?,?,?,?,?,?,?,?)");
    $st->execute([$username, $password, $email, 'ativo', $nome, 0, $vencimento, $creditos, $whatsapp]);
    $id = (int)$db->lastInsertId();
    try {
        $rev = $db->prepare("SELECT * FROM revendedores WHERE id = ? LIMIT 1");
        $rev->execute([$id]);
        $row = $rev->fetch(PDO::FETCH_ASSOC) ?: null;
        if ($row) {
            wa_send_revenda_event($db, $row, 'revenda_criada', ['link_painel' => rtrim(((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://') . ($_SERVER['HTTP_HOST'] ?? 'localhost'), '/')]);
        }
    } catch (Throwable $e) {}
    return ['success' => true, 'paid' => true, 'status' => 'approved', 'revendedor_id' => $id, 'username' => $username, 'password' => $password, 'creditos' => $creditos];
}

function renovarRevendaPorPagamentoChatbot(PDO $db, array $paymentContext, array $pagamento): array
{
    $revendedorId = (int)($paymentContext['revendedor_id'] ?? 0);
    if ($revendedorId <= 0) {
        return ['success' => false, 'error' => 'Revenda não informada para renovação'];
    }
    $st = $db->prepare("SELECT * FROM revendedores WHERE id = ? LIMIT 1");
    $st->execute([$revendedorId]);
    $rev = $st->fetch(PDO::FETCH_ASSOC) ?: null;
    if (!$rev) {
        return ['success' => false, 'error' => 'Revenda não encontrada para renovação'];
    }
    $base = strtotime((string)($rev['vencimento'] ?? ''));
    if (!$base || $base < time()) $base = time();
    $novoVencimento = date('Y-m-d', strtotime('+30 days', $base));
    $creditos = max(0, (int)($paymentContext['creditos'] ?? 0));
    $db->prepare("UPDATE revendedores SET vencimento = ?, status = 'ativo', creditos = COALESCE(creditos,0) + ? WHERE id = ?")->execute([$novoVencimento, $creditos, $revendedorId]);
    $st->execute([$revendedorId]);
    $rev = $st->fetch(PDO::FETCH_ASSOC) ?: $rev;
    try { wa_send_revenda_event($db, $rev, 'revenda_renovada'); } catch (Throwable $e) {}
    return ['success' => true, 'paid' => true, 'status' => 'approved', 'revendedor_id' => $revendedorId, 'novo_vencimento' => $novoVencimento, 'creditos_adicionados' => $creditos];
}


/*
|--------------------------------------------------------------------------
| MERCADO PAGO
|--------------------------------------------------------------------------
*/
function consultarPagamentoMercadoPago(PDO $db, string $paymentId): array
{
    $tokenMp = obterTokenMercadoPago($db);

    if ($tokenMp === "") {
        return [
            "success" => false,
            "error" => "Token Mercado Pago não encontrado no banco"
        ];
    }

    $url = "https://api.mercadopago.com/v1/payments/" . urlencode($paymentId);

    $res = httpGetJson($url, [
        "Authorization: Bearer {$tokenMp}",
        "Accept: application/json"
    ], 20);

    if (!empty($res["error"])) {
        return [
            "success" => false,
            "error" => "Erro CURL ao consultar Mercado Pago",
            "details" => $res["error"]
        ];
    }

    if (!in_array((int)$res["http_code"], [200, 201], true) || !is_array($res["response_json"])) {
        return [
            "success" => false,
            "error" => "Falha ao consultar pagamento no Mercado Pago",
            "http_code" => $res["http_code"],
            "details" => $res["response_json"] ?: $res["response_raw"]
        ];
    }

    $mp = $res["response_json"];

    return [
        "success" => true,
        "payment" => $mp,
        "payment_id" => (string)($mp["id"] ?? ""),
        "status" => strtolower((string)($mp["status"] ?? "")),
        "external_reference" => (string)($mp["external_reference"] ?? "")
    ];
}

/*
|--------------------------------------------------------------------------
| PAYPAL
|--------------------------------------------------------------------------
*/
function getPaypalBaseUrl(string $mode): string
{
    return strtolower($mode) === "live"
        ? "https://api-m.paypal.com"
        : "https://api-m.sandbox.paypal.com";
}

function getPaypalAccessToken(PDO $db): array
{
    $cfg = obterConfigPushin($db);
    $clientId = $cfg["paypal_client_id"];
    $clientSecret = $cfg["paypal_client_secret"];
    $mode = $cfg["paypal_mode"] !== "" ? $cfg["paypal_mode"] : "sandbox";

    if ($clientId === "" || $clientSecret === "") {
        return [
            "success" => false,
            "error" => "PayPal Client ID/Secret não configurados"
        ];
    }

    $baseUrl = getPaypalBaseUrl($mode);

    $res = httpPostFormBasicAuth(
        $baseUrl . "/v1/oauth2/token",
        [
            "Accept: application/json",
            "Accept-Language: pt-BR",
            "Content-Type: application/x-www-form-urlencoded"
        ],
        "grant_type=client_credentials",
        $clientId . ":" . $clientSecret,
        30
    );

    if (!empty($res["error"])) {
        return [
            "success" => false,
            "error" => "Erro CURL ao gerar access token PayPal",
            "details" => $res["error"]
        ];
    }

    if ((int)$res["http_code"] !== 200 || !is_array($res["response_json"]) || empty($res["response_json"]["access_token"])) {
        return [
            "success" => false,
            "error" => "Não foi possível obter access token do PayPal",
            "details" => $res["response_json"] ?: $res["response_raw"]
        ];
    }

    return [
        "success" => true,
        "mode" => $mode,
        "access_token" => (string)$res["response_json"]["access_token"]
    ];
}

function verificarWebhookPaypal(PDO $db, array $headers, string $raw, array $payloadJson): array
{
    $cfg = obterConfigPushin($db);
    $webhookId = $cfg["paypal_webhook_id"];

    if ($webhookId === "") {
        return [
            "success" => false,
            "error" => "paypal_webhook_id não configurado no banco"
        ];
    }

    $token = getPaypalAccessToken($db);
    if (!$token["success"]) {
        return $token;
    }

    $baseUrl = getPaypalBaseUrl($token["mode"]);

    $verifyPayload = [
        "auth_algo" => $headers["PAYPAL-AUTH-ALGO"] ?? $headers["Paypal-Auth-Algo"] ?? $headers["paypal-auth-algo"] ?? "",
        "cert_url" => $headers["PAYPAL-CERT-URL"] ?? $headers["Paypal-Cert-Url"] ?? $headers["paypal-cert-url"] ?? "",
        "transmission_id" => $headers["PAYPAL-TRANSMISSION-ID"] ?? $headers["Paypal-Transmission-Id"] ?? $headers["paypal-transmission-id"] ?? "",
        "transmission_sig" => $headers["PAYPAL-TRANSMISSION-SIG"] ?? $headers["Paypal-Transmission-Sig"] ?? $headers["paypal-transmission-sig"] ?? "",
        "transmission_time" => $headers["PAYPAL-TRANSMISSION-TIME"] ?? $headers["Paypal-Transmission-Time"] ?? $headers["paypal-transmission-time"] ?? "",
        "webhook_id" => $webhookId,
        "webhook_event" => $payloadJson
    ];

    foreach (["auth_algo", "cert_url", "transmission_id", "transmission_sig", "transmission_time"] as $campo) {
        if (trim((string)$verifyPayload[$campo]) === "") {
            return [
                "success" => false,
                "error" => "Headers do webhook PayPal incompletos",
                "missing" => $campo
            ];
        }
    }

    $res = httpPostJson(
        $baseUrl . "/v1/notifications/verify-webhook-signature",
        [
            "Authorization: Bearer " . $token["access_token"],
            "Accept: application/json",
            "Content-Type: application/json"
        ],
        $verifyPayload,
        30
    );

    if (!empty($res["error"])) {
        return [
            "success" => false,
            "error" => "Erro CURL ao verificar assinatura do webhook PayPal",
            "details" => $res["error"]
        ];
    }

    $json = $res["response_json"];
    $verificationStatus = strtoupper((string)($json["verification_status"] ?? ""));

    if ((int)$res["http_code"] !== 200 || $verificationStatus !== "SUCCESS") {
        return [
            "success" => false,
            "error" => "Falha na verificação do webhook PayPal",
            "details" => $json ?: $res["response_raw"]
        ];
    }

    return [
        "success" => true,
        "details" => $json
    ];
}

function paypalGetOrder(PDO $db, string $orderId): array
{
    $token = getPaypalAccessToken($db);
    if (!$token["success"]) {
        return $token;
    }

    $baseUrl = getPaypalBaseUrl($token["mode"]);

    $res = httpGetJson(
        $baseUrl . "/v2/checkout/orders/" . urlencode($orderId),
        [
            "Authorization: Bearer " . $token["access_token"],
            "Accept: application/json"
        ],
        30
    );

    if (!empty($res["error"])) {
        return [
            "success" => false,
            "error" => "Erro CURL ao consultar order PayPal",
            "details" => $res["error"]
        ];
    }

    if ((int)$res["http_code"] !== 200 || !is_array($res["response_json"]) || empty($res["response_json"]["id"])) {
        return [
            "success" => false,
            "error" => "Erro ao consultar order PayPal",
            "details" => $res["response_json"] ?: $res["response_raw"]
        ];
    }

    return [
        "success" => true,
        "order" => $res["response_json"],
        "order_id" => (string)$res["response_json"]["id"],
        "status" => (string)($res["response_json"]["status"] ?? "")
    ];
}

function paypalCaptureOrder(PDO $db, string $orderId): array
{
    $token = getPaypalAccessToken($db);
    if (!$token["success"]) {
        return $token;
    }

    $baseUrl = getPaypalBaseUrl($token["mode"]);

    $res = httpPostJson(
        $baseUrl . "/v2/checkout/orders/" . urlencode($orderId) . "/capture",
        [
            "Authorization: Bearer " . $token["access_token"],
            "Accept: application/json",
            "Content-Type: application/json",
            "PayPal-Request-Id: CAPTURE_" . $orderId
        ],
        [],
        30
    );

    if (!empty($res["error"])) {
        return [
            "success" => false,
            "error" => "Erro CURL ao capturar order PayPal",
            "details" => $res["error"]
        ];
    }

    if (!in_array((int)$res["http_code"], [200, 201], true) || !is_array($res["response_json"]) || empty($res["response_json"]["id"])) {
        return [
            "success" => false,
            "error" => "Erro ao capturar order PayPal",
            "details" => $res["response_json"] ?: $res["response_raw"]
        ];
    }

    return [
        "success" => true,
        "capture" => $res["response_json"],
        "order_id" => (string)$res["response_json"]["id"],
        "status" => strtoupper((string)($res["response_json"]["status"] ?? ""))
    ];
}

function paypalGetCaptureIdFromOrder(array $order): string
{
    $captures = $order["purchase_units"][0]["payments"]["captures"] ?? [];
    if (!empty($captures[0]["id"])) {
        return (string)$captures[0]["id"];
    }
    return "";
}

function processarBaixaPaypalPorOrder(PDO $db, string $jsonFile, array &$store, array &$pagamento, array $orderDetails): array
{
    $status = strtoupper((string)($orderDetails["status"] ?? ""));
    $captureId = paypalGetCaptureIdFromOrder($orderDetails);

    $pagamento["gateway"] = 3;
    $pagamento["gateway_nome"] = "paypal";
    $pagamento["paypal_order"] = $orderDetails;
    if ($captureId !== "") {
        $pagamento["paypal_capture_id"] = $captureId;
    }

    if ($status === "COMPLETED") {
        return processarBaixa(
            $db,
            $jsonFile,
            $store,
            $pagamento,
            "completed",
            $orderDetails,
            "paypal_order"
        );
    }

    if ($status === "APPROVED") {
        $capture = paypalCaptureOrder($db, (string)$orderDetails["id"]);

        if (!$capture["success"]) {
            webhookLog("Falha ao capturar order PayPal {$orderDetails["id"]}: " . json_encode($capture, JSON_UNESCAPED_UNICODE));
            return $capture;
        }

        $pagamento["paypal_capture"] = $capture["capture"];

        return processarBaixa(
            $db,
            $jsonFile,
            $store,
            $pagamento,
            "completed",
            $capture["capture"],
            "paypal_capture"
        );
    }

    return processarBaixa(
        $db,
        $jsonFile,
        $store,
        $pagamento,
        strtolower($status),
        $orderDetails,
        "paypal_order"
    );
}

/*
|--------------------------------------------------------------------------
| INÍCIO
|--------------------------------------------------------------------------
*/
$headersRaw = function_exists("getallheaders") ? getallheaders() : [];
$headers = [];
foreach ($headersRaw as $k => $v) {
    $headers[$k] = $v;
}
$raw = file_get_contents("php://input");
webhookDumpLog($raw, $headers);

try {
    $db = abrirDb($dbPath);
    garantirColunasConfig($db);
} catch (Throwable $e) {
    webhookLog("ERRO AO ABRIR DB: " . $e->getMessage());
    jsonResponse(["success" => false, "error" => "Erro ao abrir banco"], 500);
}

$store = carregarPagamentos($jsonFile);
$payloadJson = json_decode($raw, true);

/*
|--------------------------------------------------------------------------
| PUSHIN PAY
|--------------------------------------------------------------------------
*/
$tokenEsperadoPushin = obterTokenWebhookPushin($db);

$tokenRecebidoPushin =
    $headers["x-pushinpay-token"]
    ?? $headers["X-Pushinpay-Token"]
    ?? $_SERVER["HTTP_X_PUSHINPAY_TOKEN"]
    ?? "";

if ($tokenRecebidoPushin !== "") {
    if ($tokenEsperadoPushin === "") {
        webhookLog("Webhook Pushin recebido, mas token esperado não está configurado no banco");
        jsonResponse(["success" => false, "error" => "Token Pushin não configurado"], 500);
    }

    if (!hash_equals($tokenEsperadoPushin, $tokenRecebidoPushin)) {
        webhookLog("TOKEN PUSHIN INVÁLIDO");
        jsonResponse(["success" => false, "error" => "Token inválido"], 401);
    }

    $pushinPayload = [];
    parse_str($raw, $pushinPayload);

    $id = $pushinPayload["id"] ?? ($_POST["id"] ?? null);
    $status = $pushinPayload["status"] ?? ($_POST["status"] ?? null);

    if (!$id || !$status) {
        webhookLog("PUSHIN sem id/status");
        jsonResponse(["success" => false, "error" => "Campos obrigatórios ausentes"], 400);
    }

    $paymentId = strtolower((string)$id);
    $status = strtolower((string)$status);

    $found = buscarPagamentoPorPaymentId($store, $paymentId);

    if ($found["index"] < 0 || !is_array($found["pagamento"])) {
        webhookLog("PUSHIN payment_id não encontrado no JSON: {$paymentId}");
        jsonResponse(["success" => true, "message" => "Pagamento não localizado, ignorado"]);
    }

    $resultado = processarBaixa(
        $db,
        $jsonFile,
        $store,
        $found["pagamento"],
        $status,
        null,
        null
    );

    webhookLog("PUSHIN PROCESSADO payment_id={$paymentId} status={$status} resultado=" . json_encode($resultado, JSON_UNESCAPED_UNICODE));
    jsonResponse([
        "success" => true,
        "gateway" => "pushinpay",
        "resultado" => $resultado
    ]);
}
/*
|--------------------------------------------------------------------------
| PAYPAL WEBHOOK OFICIAL
|--------------------------------------------------------------------------
*/
$isPaypalWebhook =
    isset($headers["PAYPAL-TRANSMISSION-ID"]) ||
    isset($headers["Paypal-Transmission-Id"]) ||
    isset($headers["paypal-transmission-id"]);

if ($isPaypalWebhook) {
    if (!is_array($payloadJson)) {
        webhookLog("PAYPAL webhook com JSON inválido");
        jsonResponse(["success" => false, "error" => "JSON inválido"], 400);
    }

    $verify = verificarWebhookPaypal($db, $headers, $raw, $payloadJson);

    if (!$verify["success"]) {
        webhookLog("PAYPAL webhook rejeitado: " . json_encode($verify, JSON_UNESCAPED_UNICODE));
        jsonResponse([
            "success" => false,
            "error" => $verify["error"],
            "details" => $verify["details"] ?? null
        ], 401);
    }

    $eventType = strtoupper((string)($payloadJson["event_type"] ?? ""));
    $resource = is_array($payloadJson["resource"] ?? null) ? $payloadJson["resource"] : [];

    if ($eventType === "CHECKOUT.ORDER.APPROVED") {
        $orderId = (string)($resource["id"] ?? "");

        if ($orderId === "") {
            webhookLog("PAYPAL CHECKOUT.ORDER.APPROVED sem order id");
            jsonResponse(["success" => false, "error" => "Order ID ausente"], 400);
        }

        $found = buscarPagamentoPorPaymentId($store, $orderId);

        if ($found["index"] < 0 || !is_array($found["pagamento"])) {
            webhookLog("PAYPAL order não encontrada no JSON: {$orderId}");
            jsonResponse([
                "success" => true,
                "message" => "Order não localizada, ignorada",
                "event_type" => $eventType
            ]);
        }

        $orderDetails = paypalGetOrder($db, $orderId);
        if (!$orderDetails["success"]) {
            webhookLog("Falha ao consultar order PayPal {$orderId}: " . json_encode($orderDetails, JSON_UNESCAPED_UNICODE));
            jsonResponse([
                "success" => false,
                "error" => $orderDetails["error"],
                "details" => $orderDetails["details"] ?? null
            ], 500);
        }

        $resultado = processarBaixaPaypalPorOrder(
            $db,
            $jsonFile,
            $store,
            $found["pagamento"],
            $orderDetails["order"]
        );

        webhookLog("PAYPAL APPROVED PROCESSADO order_id={$orderId} resultado=" . json_encode($resultado, JSON_UNESCAPED_UNICODE));
        jsonResponse([
            "success" => true,
            "gateway" => "paypal",
            "event_type" => $eventType,
            "order_id" => $orderId,
            "resultado" => $resultado
        ]);
    }

    if ($eventType === "PAYMENT.CAPTURE.COMPLETED") {
        $captureId = (string)($resource["id"] ?? "");
        $supplementary = is_array($resource["supplementary_data"] ?? null) ? $resource["supplementary_data"] : [];
        $relatedIds = is_array($supplementary["related_ids"] ?? null) ? $supplementary["related_ids"] : [];
        $orderId = (string)($relatedIds["order_id"] ?? "");

        if ($orderId === "") {
            webhookLog("PAYPAL PAYMENT.CAPTURE.COMPLETED sem order_id relacionado");
            jsonResponse([
                "success" => true,
                "message" => "Capture sem order_id relacionado, ignorada",
                "capture_id" => $captureId
            ]);
        }

        $found = buscarPagamentoPorPaymentId($store, $orderId);

        if ($found["index"] < 0 || !is_array($found["pagamento"])) {
            webhookLog("PAYPAL capture order não encontrada no JSON: {$orderId}");
            jsonResponse([
                "success" => true,
                "message" => "Order não localizada, ignorada",
                "order_id" => $orderId
            ]);
        }

        $found["pagamento"]["gateway"] = 3;
        $found["pagamento"]["gateway_nome"] = "paypal";
        $found["pagamento"]["paypal_capture_id"] = $captureId;

        $resultado = processarBaixa(
            $db,
            $jsonFile,
            $store,
            $found["pagamento"],
            "completed",
            $resource,
            "paypal_capture"
        );

        webhookLog("PAYPAL CAPTURE COMPLETED PROCESSADO order_id={$orderId} capture_id={$captureId} resultado=" . json_encode($resultado, JSON_UNESCAPED_UNICODE));
        jsonResponse([
            "success" => true,
            "gateway" => "paypal",
            "event_type" => $eventType,
            "order_id" => $orderId,
            "capture_id" => $captureId,
            "resultado" => $resultado
        ]);
    }

    if ($eventType === "PAYMENT.CAPTURE.DENIED") {
        $captureId = (string)($resource["id"] ?? "");
        $supplementary = is_array($resource["supplementary_data"] ?? null) ? $resource["supplementary_data"] : [];
        $relatedIds = is_array($supplementary["related_ids"] ?? null) ? $supplementary["related_ids"] : [];
        $orderId = (string)($relatedIds["order_id"] ?? "");

        if ($orderId !== "") {
            $found = buscarPagamentoPorPaymentId($store, $orderId);

            if ($found["index"] >= 0 && is_array($found["pagamento"])) {
                $found["pagamento"]["gateway"] = 3;
                $found["pagamento"]["gateway_nome"] = "paypal";
                $found["pagamento"]["paypal_capture_id"] = $captureId;

                $resultado = processarBaixa(
                    $db,
                    $jsonFile,
                    $store,
                    $found["pagamento"],
                    "denied",
                    $resource,
                    "paypal_capture"
                );

                webhookLog("PAYPAL CAPTURE DENIED PROCESSADO order_id={$orderId} capture_id={$captureId} resultado=" . json_encode($resultado, JSON_UNESCAPED_UNICODE));
                jsonResponse([
                    "success" => true,
                    "gateway" => "paypal",
                    "event_type" => $eventType,
                    "order_id" => $orderId,
                    "capture_id" => $captureId,
                    "resultado" => $resultado
                ]);
            }
        }

        jsonResponse([
            "success" => true,
            "gateway" => "paypal",
            "event_type" => $eventType,
            "message" => "Evento processado sem order correspondente"
        ]);
    }

    webhookLog("PAYPAL EVENTO NÃO TRATADO: {$eventType}");
    jsonResponse([
        "success" => true,
        "gateway" => "paypal",
        "event_type" => $eventType,
        "message" => "Evento recebido e ignorado"
    ]);
}

/*
|--------------------------------------------------------------------------
| MERCADO PAGO WEBHOOK
|--------------------------------------------------------------------------
*/
if (is_array($payloadJson) && (
    (($payloadJson["type"] ?? "") === "payment") ||
    (($payloadJson["action"] ?? "") === "payment.updated")
)) {
    $mpPaymentId = (string)($payloadJson["data"]["id"] ?? "");

    if ($mpPaymentId === "") {
        webhookLog("WEBHOOK MP sem payment id");
        jsonResponse(["success" => false, "error" => "Webhook MP sem payment id"], 400);
    }

    $consulta = consultarPagamentoMercadoPago($db, $mpPaymentId);

    if (!$consulta["success"]) {
        webhookLog("ERRO CONSULTA MP payment_id={$mpPaymentId} detalhe=" . json_encode($consulta, JSON_UNESCAPED_UNICODE));
        jsonResponse([
            "success" => false,
            "error" => $consulta["error"],
            "details" => $consulta["details"] ?? null
        ], 500);
    }

    $mpPayment = $consulta["payment"];
    $status = strtolower((string)($consulta["status"] ?? ""));
    $paymentId = (string)($consulta["payment_id"] ?? "");
    $externalReference = (string)($consulta["external_reference"] ?? "");

    $found = buscarPagamentoPorPaymentId($store, $paymentId);

    if ($found["index"] < 0 && $externalReference !== "") {
        $found = buscarPagamentoPorExternalReference($store, $externalReference);
    }

    if ($found["index"] < 0 || !is_array($found["pagamento"])) {
        webhookLog("MP payment não encontrado no JSON payment_id={$paymentId} external_reference={$externalReference}");
        jsonResponse([
            "success" => true,
            "gateway" => "mercadopago",
            "message" => "Pagamento MP não localizado no JSON, ignorado",
            "payment_id" => $paymentId,
            "external_reference" => $externalReference,
            "status" => $status
        ]);
    }

    $found["pagamento"]["payment_id"] = $paymentId;
    if ($externalReference !== "") {
        $found["pagamento"]["external_reference"] = $externalReference;
    }
    $found["pagamento"]["gateway"] = 1;
    $found["pagamento"]["gateway_nome"] = "mercadopago";

    $resultado = processarBaixa(
        $db,
        $jsonFile,
        $store,
        $found["pagamento"],
        $status,
        $mpPayment,
        "mp_consulta"
    );

    webhookLog("MP PROCESSADO payment_id={$paymentId} status={$status} external_reference={$externalReference} resultado=" . json_encode($resultado, JSON_UNESCAPED_UNICODE));
    jsonResponse([
        "success" => true,
        "gateway" => "mercadopago",
        "payment_id" => $paymentId,
        "external_reference" => $externalReference,
        "status" => $status,
        "resultado" => $resultado
    ]);
}

/*
|--------------------------------------------------------------------------
| CONSULTA MANUAL MP
|--------------------------------------------------------------------------
*/
$modo = $_GET["modo"] ?? $_POST["modo"] ?? ($payloadJson["modo"] ?? "");

if ($modo === "consultar_mp") {
    $mpPaymentId = trim((string)($_GET["payment_id"] ?? $_POST["payment_id"] ?? ($payloadJson["payment_id"] ?? "")));

    if ($mpPaymentId === "") {
        jsonResponse(["success" => false, "error" => "payment_id obrigatório"], 400);
    }

    $consulta = consultarPagamentoMercadoPago($db, $mpPaymentId);

    if (!$consulta["success"]) {
        jsonResponse($consulta, 500);
    }

    $paymentId = (string)($consulta["payment_id"] ?? "");
    $status = (string)($consulta["status"] ?? "");
    $externalReference = (string)($consulta["external_reference"] ?? "");

    $found = buscarPagamentoPorPaymentId($store, $paymentId);
    if ($found["index"] < 0 && $externalReference !== "") {
        $found = buscarPagamentoPorExternalReference($store, $externalReference);
    }

    $resultadoBaixa = null;

    if ($found["index"] >= 0 && is_array($found["pagamento"])) {
        $found["pagamento"]["payment_id"] = $paymentId;
        if ($externalReference !== "") {
            $found["pagamento"]["external_reference"] = $externalReference;
        }
        $found["pagamento"]["gateway"] = 1;
        $found["pagamento"]["gateway_nome"] = "mercadopago";

        $resultadoBaixa = processarBaixa(
            $db,
            $jsonFile,
            $store,
            $found["pagamento"],
            $status,
            $consulta["payment"],
            "mp_consulta"
        );
    }

    jsonResponse([
        "success" => true,
        "gateway" => "mercadopago",
        "consulta" => [
            "payment_id" => $paymentId,
            "external_reference" => $externalReference,
            "status" => $status,
            "payment" => $consulta["payment"]
        ],
        "baixa" => $resultadoBaixa
    ]);
}

/*
|--------------------------------------------------------------------------
| CONSULTA MANUAL PAYPAL
|--------------------------------------------------------------------------
*/
if ($modo === "consultar_paypal") {
    $orderId = trim((string)($_GET["payment_id"] ?? $_POST["payment_id"] ?? ($payloadJson["payment_id"] ?? "")));

    if ($orderId === "") {
        jsonResponse(["success" => false, "error" => "payment_id obrigatório"], 400);
    }

    $found = buscarPagamentoPorPaymentId($store, $orderId);

    if ($found["index"] < 0 || !is_array($found["pagamento"])) {
        jsonResponse([
            "success" => false,
            "error" => "Pagamento PayPal não encontrado no JSON"
        ], 404);
    }

    $orderDetails = paypalGetOrder($db, $orderId);
    if (!$orderDetails["success"]) {
        jsonResponse($orderDetails, 500);
    }

    $resultado = processarBaixaPaypalPorOrder(
        $db,
        $jsonFile,
        $store,
        $found["pagamento"],
        $orderDetails["order"]
    );

    jsonResponse([
        "success" => true,
        "gateway" => "paypal",
        "consulta" => [
            "payment_id" => $orderId,
            "status" => $orderDetails["status"],
            "order" => $orderDetails["order"]
        ],
        "baixa" => $resultado
    ]);
}

webhookLog("REQUISIÇÃO NÃO RECONHECIDA");
jsonResponse([
    "success" => false,
    "error" => "Requisição não reconhecida"
], 400);