<?php
header('Content-Type: application/json');

$allowedOrigins = ['https://dgray.io', 'http://localhost:5500', 'http://localhost:8080'];
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (in_array($origin, $allowedOrigins)) {
    header('Access-Control-Allow-Origin: ' . $origin);
} else {
    header('Access-Control-Allow-Origin: https://dgray.io');
}

header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri = rtrim($uri, '/');

switch ($uri) {
    case '/challenge':
        require __DIR__ . '/challenge.php';
        break;
    case '/verify':
        require __DIR__ . '/verify.php';
        break;
    case '/btcpay/invoice':
        require __DIR__ . '/btcpay-invoice.php';
        break;
    case '/btcpay/status':
        require __DIR__ . '/btcpay-status.php';
        break;
    case '/btcpay/webhook':
        require __DIR__ . '/btcpay-webhook.php';
        break;
    default:
        http_response_code(404);
        echo json_encode(['error' => 'Not found']);
}
