<?php
// Configuração e cliente da Vennox — mesma lógica de vennox.server.ts

// Credenciais: defina como variáveis de ambiente ou preencha abaixo.
define('VENNOX_BASE', getenv('VENNOX_BASE') ?: 'https://api.vennoxprovisorio.com');
define('VENNOX_PUBLIC_KEY', getenv('VENNOX_PUBLIC_KEY') ?: 'vennoxpay_live_RtSgZ6tYXCHVkTRpQ6th9fQqeqQcptj3');
define('VENNOX_SECRET_KEY', getenv('VENNOX_SECRET_KEY') ?: 'sk_live_ahuF33jRMNC3EPcaxlF8VQ0W9xHOKc14');

// Pasta onde os pedidos ficam armazenados (equivalente à tabela pix_orders)
define('ORDERS_DIR', __DIR__ . '/../storage/orders');

function vennox_request($path, $method = 'GET', $payload = null) {
    $ch = curl_init(VENNOX_BASE . $path);
    $headers = [
        'Content-Type: application/json',
        'Accept: application/json',
        'Authorization: Basic ' . base64_encode(VENNOX_PUBLIC_KEY . ':' . VENNOX_SECRET_KEY),
    ];
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_TIMEOUT => 30,
    ]);
    if ($payload !== null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload, JSON_UNESCAPED_UNICODE));
    }
    $raw = curl_exec($ch);
    $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($raw === false) { $raw = ''; }
    $json = json_decode($raw, true);
    if (!is_array($json)) { $json = null; }
    return ['status' => $status, 'json' => $json, 'raw' => $raw];
}

// A API pode devolver { data: [ {...} ] }, { data: {...} } ou o objeto direto
function vennox_unwrap($payload) {
    $d = (is_array($payload) && array_key_exists('data', $payload)) ? $payload['data'] : $payload;
    if (is_array($d) && array_keys($d) === range(0, count($d) - 1)) {
        return $d[0] ?? [];
    }
    return $d ?? [];
}

function only_digits($v) {
    return preg_replace('/\D/', '', (string) $v);
}

function json_out($data, $code = 200) {
    http_response_code($code);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}
