<?php
require __DIR__ . '/config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);

$listingId = $input['listingId'] ?? null;
$currency = $input['currency'] ?? 'EUR';

if (!$listingId) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing listingId']);
    exit;
}

$fees = LISTING_FEE;
if (!isset($fees[$currency])) {
    http_response_code(400);
    echo json_encode(['error' => 'Unsupported currency', 'supported' => array_keys($fees)]);
    exit;
}

$amount = $fees[$currency];

$payload = json_encode([
    'amount' => $amount,
    'currency' => $currency,
    'metadata' => [
        'listingId' => $listingId,
        'orderId' => 'listing-' . $listingId,
    ],
]);

$url = BTCPAY_BASE_URL . '/api/v1/stores/' . BTCPAY_STORE_ID . '/invoices';

$context = stream_context_create([
    'http' => [
        'method' => 'POST',
        'header' => "Content-Type: application/json\r\nAuthorization: token " . BTCPAY_API_KEY . "\r\n",
        'content' => $payload,
        'ignore_errors' => true,
    ],
]);

$response = file_get_contents($url, false, $context);

if ($response === false) {
    http_response_code(502);
    echo json_encode(['error' => 'Failed to connect to payment server']);
    exit;
}

// Extract HTTP status from response headers
$statusCode = 500;
if (isset($http_response_header[0]) && preg_match('/\d{3}/', $http_response_header[0], $matches)) {
    $statusCode = (int)$matches[0];
}

$data = json_decode($response, true);

if ($statusCode >= 400) {
    http_response_code($statusCode);
    echo json_encode(['error' => $data['message'] ?? 'Invoice creation failed']);
    exit;
}

echo json_encode([
    'invoiceId' => $data['id'] ?? null,
    'checkoutLink' => $data['checkoutLink'] ?? null,
    'status' => $data['status'] ?? null,
    'expirationTime' => $data['expirationTime'] ?? null,
]);
