<?php
// POST action=vcard_create&api_key=KEY&currency=USD&amount=5
// Create a virtual card and fund it

$user_id = $GLOBALS['api_user_id'];
$currency = strtoupper(trim($_POST['currency'] ?? $_GET['currency'] ?? 'USD'));
$amount   = (float)($_POST['amount'] ?? $_GET['amount'] ?? 0);

if ($amount <= 0) {
    api_response(['status' => 'error', 'message' => 'Amount must be greater than 0.'], 400);
}

if (!in_array($currency, ['USD', 'NGN'])) {
    api_response(['status' => 'error', 'message' => 'Currency must be USD or NGN.'], 400);
}

// Check card creation fee
$card_fee = (float)($site_data['card_creation_fee'] ?? 0);
$total_ngn = $amount;

// If USD, convert to NGN for balance deduction
if ($currency === 'USD') {
    $usd_rate = (float)($site_data['usd_to_ngn'] ?? 1600);
    $total_ngn = round($amount * $usd_rate, 2) + $card_fee;
} else {
    $total_ngn = $amount + $card_fee;
}

// Check balance
try {
    $bal = (float)$pdo->query("SELECT main_balance FROM users WHERE id = {$user_id}")->fetchColumn();
} catch (PDOException $e) {
    api_response(['status' => 'error', 'message' => 'Balance error.'], 500);
}

if ($bal < $total_ngn) {
    api_response(['status' => 'error', 'message' => "Insufficient balance. Need ₦" . number_format($total_ngn, 2) . ", have ₦" . number_format($bal, 2)], 400);
}

// Check if Sudo/Strowallet is configured
$sudo_key = trim($site_data['sudo_api_key'] ?? '');
if (empty($sudo_key)) {
    api_response(['status' => 'error', 'message' => 'Virtual card provider not configured.'], 503);
}

// Deduct and record (actual card creation via Sudo/Strowallet depends on your provider setup)
try {
    $pdo->beginTransaction();

    $pdo->prepare("UPDATE users SET main_balance = main_balance - :total WHERE id = :uid")
        ->execute([':total' => $total_ngn, ':uid' => $user_id]);

    $ref = 'VCARD_API_' . date('YmdHis') . '_' . strtoupper(substr(uniqid(), -6));
    $pdo->prepare(
        "INSERT INTO transactions (user_id, transaction_ref, payment_gateway, transaction_type, amount, currency, status, metadata, created_at)
         VALUES (:uid, :ref, 'balance', 'virtual_card', :amount, 'NGN', 'processing', :meta, NOW())"
    )->execute([
        ':uid'    => $user_id,
        ':ref'    => $ref,
        ':amount' => $total_ngn,
        ':meta'   => json_encode(['fund_amount' => $amount, 'fund_currency' => $currency, 'fee' => $card_fee, 'via' => 'api']),
    ]);

    $pdo->commit();
} catch (PDOException $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    api_response(['status' => 'error', 'message' => 'Transaction failed.'], 500);
}

api_response([
    'status'   => 'success',
    'message'  => 'Virtual card creation initiated. Processing...',
    'charged'  => number_format($total_ngn, 2, '.', ''),
    'currency' => 'NGN',
    'ref'      => $ref,
]);
