<?php
$apiKey = 'sk-live-bc98f3d4c2230d6c82949ddc52d46bfe';
$customerId = '6c4e08bd-54ac-40fe-980b-ba80239ddf3e';

// Step 1: Get exchange rate (USD to GBP)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.bridge.xyz/v0/exchange_rates?from=usd&to=gbp');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Api-Key: ' . $apiKey,
    'Content-Type: application/json'
]);

$rateResponse = curl_exec($ch);
$rates = json_decode($rateResponse, true);

echo "=== Current Exchange Rates ===\n";
echo "Midmarket Rate: " . $rates['midmarket_rate'] . "\n";
echo "Sell Rate (USD→GBP): " . $rates['sell_rate'] . "\n\n";

// Step 2: Create GBP External Account (sort_code + account_number)
curl_setopt($ch, CURLOPT_URL, 'https://api.bridge.xyz/v0/customers/' . $customerId . '/external_accounts');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Api-Key: ' . $apiKey,
    'Content-Type: application/json',
    'Idempotency-Key: ' . uniqid()
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    'currency' => 'gbp',
    'account_type' => 'gb',
    'account_owner_name' => 'John Doe',
    'first_name' => 'John',
    'last_name' => 'Doe',
    'bank_name' => 'Your Bank Name',
    'account' => [
        'sort_code' => '123456',        // 6-digit sort code
        'account_number' => '12345678'  // 8-digit account number
    ]
]));

$extResponse = curl_exec($ch);
$extAccount = json_decode($extResponse, true);
$externalAccountId = $extAccount['id'];

echo "=== External Account Created ===\n";
echo "External Account ID: " . $externalAccountId . "\n\n";

// Step 3: Create Liquidation Address (USDC Polygon → GBP)
curl_setopt($ch, CURLOPT_URL, 'https://api.bridge.xyz/v0/customers/' . $customerId . '/liquidation_addresses');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Api-Key: ' . $apiKey,
    'Content-Type: application/json',
    'Idempotency-Key: ' . uniqid()
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    'chain' => 'polygon',
    'currency' => 'usdc',
    'external_account_id' => $externalAccountId,
    'destination_payment_rail' => 'faster_payments',
    'destination_currency' => 'gbp'
]));

$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);

echo "=== Liquidation Address Created ===\n";
echo "Address: " . $data['address'] . "\n";
echo "Chain: " . $data['chain'] . "\n";
echo "Send USDC to this address to offramp to GBP!\n";
?>