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

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

$invoiceId = $_GET['id'] ?? null;

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

$url = BTCPAY_BASE_URL . '/api/v1/stores/' . BTCPAY_STORE_ID . '/invoices/' . urlencode($invoiceId);

$context = stream_context_create([
    'http' => [
        'method' => 'GET',
        'header' => "Authorization: token " . BTCPAY_API_KEY . "\r\n",
        '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'] ?? 'Failed to fetch invoice status']);
    exit;
}

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