<?php
require 'vendor/autoload.php';

use Firebase\JWT\JWT;

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

// === CONFIGURATION ===
$clientId = 'f395d64a1cc4cb4ae0f6a56194513536';  // replace
$privateKeyPath = "safehaven/privatekey.pem";    // path to your RSA private key
$tokenUrl = 'https://api.sandbox.safehavenmfb.com/oauth/token';
$subaccountUrl = 'https://api.sandbox.safehavenmfb.com/accounts/v2/subaccount';

// Load your private key
$privateKey = @file_get_contents($privateKeyPath);
if (!$privateKey) {
    http_response_code(500);
    echo json_encode(array('error' => 'Private key file not found or unreadable'));
    exit;
}

// Generate JWT (client_assertion)
$now = time();
$jti = base64_encode(openssl_random_pseudo_bytes(16));  // replacement for random_bytes
$payload = array(
    'iss' => $clientId,
    'sub' => $clientId,
    'aud' => $tokenUrl,
    'iat' => $now,
    'exp' => $now + 300,  // valid for 5 minutes
    'jti' => $jti
);
$jwt = JWT::encode($payload, $privateKey, 'RS256');

// Step 1: Get Bearer token
$ch = curl_init($tokenUrl);
curl_setopt_array($ch, array(
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => array(
        'Content-Type: application/json',
        'Accept: application/json',
    ),
    CURLOPT_POSTFIELDS => json_encode(array(
        'grant_type' => 'client_credentials',
        'client_assertion_type' => 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
        'client_assertion' => $jwt
    )),
));
$response = curl_exec($ch);
if (curl_errno($ch)) {
    http_response_code(500);
    echo json_encode(array('error' => 'Token request error', 'message' => curl_error($ch)));
    curl_close($ch);
    exit;
}
curl_close($ch);

$tokenResp = json_decode($response, true);
if (!isset($tokenResp['access_token'])) {
    http_response_code(500);
    echo json_encode(array('error' => 'Invalid token response', 'response' => $tokenResp));
    exit;
}
$accessToken = $tokenResp['access_token'];

// Step 2: Create subaccount
$input = json_decode(file_get_contents('php://input'), true);
if (!is_array($input) || !isset($input['phone']) || !isset($input['email'])) {
    http_response_code(400);
    echo json_encode(array('error' => 'Invalid input — provide phone and email'));
    exit;
}

$body = array(
    'phoneNumber' => $input['phone'],
    'emailAddress' => $input['email'],
    'externalReference' => isset($input['externalReference']) ? $input['externalReference'] : uniqid(),
    'identityType' => isset($input['identityType']) ? $input['identityType'] : 'BVN',
    'identityNumber' => isset($input['identityNumber']) ? $input['identityNumber'] : '',
    'identityId' => isset($input['identityId']) ? $input['identityId'] : '',
    'callbackUrl' => isset($input['callbackUrl']) ? $input['callbackUrl'] : '',
    'autoSweep' => false
);

$ch = curl_init($subaccountUrl);
curl_setopt_array($ch, array(
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => array(
        'Content-Type: application/json',
        'Accept: application/json',
        'Authorization: Bearer ' . $accessToken
    ),
    CURLOPT_POSTFIELDS => json_encode($body),
));
$response = curl_exec($ch);
if (curl_errno($ch)) {
    http_response_code(500);
    echo json_encode(array('error' => 'Subaccount request error', 'message' => curl_error($ch)));
    curl_close($ch);
    exit;
}
curl_close($ch);

$result = json_decode($response, true);
echo json_encode($result, JSON_PRETTY_PRINT);

?>
