<?php
// GET ?action=vcard_list&api_key=KEY
// List user's virtual cards

$user_id = $GLOBALS['api_user_id'];

try {
    $stmt = $pdo->prepare(
        "SELECT id, card_id, card_name, card_number, cvv, expiry_month, expiry_year, 
                balance, currency, status, created_at
           FROM virtual_cards
          WHERE user_id = :uid
          ORDER BY created_at DESC"
    );
    $stmt->execute([':uid' => $user_id]);
    $cards = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    api_response(['status' => 'error', 'message' => 'Database error.'], 500);
}

$result = [];
foreach ($cards as $c) {
    $result[] = [
        'id'           => (int)$c['id'],
        'card_name'    => $c['card_name'] ?? '',
        'card_number'  => $c['card_number'] ?? '',
        'cvv'          => $c['cvv'] ?? '',
        'expiry'       => ($c['expiry_month'] ?? '') . '/' . ($c['expiry_year'] ?? ''),
        'balance'      => $c['balance'] ?? '0.00',
        'currency'     => $c['currency'] ?? 'USD',
        'status'       => $c['status'] ?? 'active',
        'created_at'   => $c['created_at'],
    ];
}

api_response([
    'status' => 'success',
    'count'  => count($result),
    'cards'  => $result,
]);
