<?php
// Uma função para chamar a API
// Explicação: https://xflowpayments.com/blog/api-pix-php/
// xflow.php
const XFLOW_BASE = 'https://app.xflowpayments.com/api/v1';

function xflow(string $method, string $path, ?array $body = null, ?string $idempotencyKey = null): array
{
    $headers = ['Accept: application/json'];
    if ($body !== null) {
        $headers[] = 'Content-Type: application/json';
    }
    if ($idempotencyKey !== null) {
        $headers[] = 'Idempotency-Key: ' . $idempotencyKey;
    }

    $ch = curl_init(XFLOW_BASE . $path);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST  => $method,
        CURLOPT_HTTPAUTH       => CURLAUTH_BASIC,
        CURLOPT_USERPWD        => getenv('XFLOW_PUBLIC_KEY') . ':' . getenv('XFLOW_SECRET_KEY'),
        CURLOPT_HTTPHEADER     => $headers,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 30,
    ]);
    if ($body !== null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
    }

    $raw = curl_exec($ch);
    if ($raw === false) {
        throw new RuntimeException('Falha de rede: ' . curl_error($ch));
    }
    $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    $json = json_decode($raw, true) ?? [];

    if ($status >= 400) {
        throw new RuntimeException(sprintf(
            '%d %s: %s (%s)',
            $status,
            $json['error'] ?? 'erro',
            $json['message'] ?? '',
            $json['request_id'] ?? 'sem request_id'
        ), $status);
    }
    return $json;
}
