<?php
// Xynex · PHP 8.1+ · Create an invoice (Guzzle)
//
//   composer require guzzlehttp/guzzle ramsey/uuid
//   XYNEX_API_KEY=cp_test_... php php-create-invoice.php

require __DIR__ . '/vendor/autoload.php';

use GuzzleHttp\Client;
use Ramsey\Uuid\Uuid;

$apiKey = getenv('XYNEX_API_KEY');
if (!$apiKey) {
    fwrite(STDERR, "Set XYNEX_API_KEY first.\n");
    exit(1);
}

$client = new Client(['base_uri' => 'https://api.xynex.app/v1/']);

try {
    $resp = $client->post('invoices', [
        'headers' => [
            'Authorization'   => 'Bearer ' . $apiKey,
            'Content-Type'    => 'application/json',
            'Idempotency-Key' => Uuid::uuid4()->toString(),
        ],
        'json' => [
            'reference' => 'order-' . substr(bin2hex(random_bytes(4)), 0, 8),
            'amount'    => 49.0,
            'currency'  => 'usd',
            'customer'  => ['email' => 'buyer@example.com'],
        ],
    ]);

    $body = json_decode((string) $resp->getBody(), true);
    echo "Checkout URL: " . $body['data']['checkout_url'] . PHP_EOL;
    echo "Invoice id:   " . $body['data']['id'] . PHP_EOL;
} catch (\Throwable $e) {
    fwrite(STDERR, "Xynex error: " . $e->getMessage() . PHP_EOL);
    exit(1);
}
