<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech
include('header.php');
$page_title  = WEB_NAME . " | My Virtual Cards";
$page_title2 = "Virtual Cards";

// ── Feature gate ──────────────────────────────────────────────
if (empty($site_data['strowallet_enabled'])) {
    echo '<div class="max-w-2xl mx-auto" style="padding:48px;text-align:center;color:var(--text-muted)"><i class="fas fa-credit-card" style="font-size:2rem;margin-bottom:12px;display:block;opacity:.4"></i><p style="font-weight:600">Virtual Card service is currently unavailable.</p></div>';
    include('footer.php'); exit;
}

// ── Load user's cards ─────────────────────────────────────────
try {
    $cards_stmt = $pdo->prepare("SELECT * FROM virtual_cards WHERE user_id = :uid AND status != 'terminated' ORDER BY id DESC");
    $cards_stmt->execute(array('uid' => $user['id']));
    $cards = $cards_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) { $cards = array(); }

// ── Settings ──────────────────────────────────────────────────
$vcard_fund_rate    = (float)(isset($site_data['vcard_fund_rate'])    ? $site_data['vcard_fund_rate']    : 1600);
$vcard_withdraw_rate= (float)(isset($site_data['vcard_withdraw_rate']) ? $site_data['vcard_withdraw_rate'] : 1550);
$vcard_creation_fee = (float)(isset($site_data['vcard_creation_fee']) ? $site_data['vcard_creation_fee'] : 0);
$vcard_min_fund     = (float)(isset($site_data['vcard_min_fund'])     ? $site_data['vcard_min_fund']     : 5);
$vcard_min_balance  = (float)(isset($site_data['vcard_min_balance'])  ? $site_data['vcard_min_balance']  : 1);
$vcard_max_per_user = (int)(isset($site_data['vcard_max_per_user'])   ? $site_data['vcard_max_per_user'] : 3);
$can_create         = count($cards) < $vcard_max_per_user;

// Safe min — never less than $5 (StroWallet minimum)
if ($vcard_min_fund < 5) $vcard_min_fund = 5;

// Build card data array for JS (PHP 7.2 compat — no arrow functions)
$cards_js = array();
foreach ($cards as $c) {
    $cards_js[] = array(
        'card_id'  => $c['card_id'],
        'expiry'   => isset($c['expiry'])    ? $c['expiry']    : '',
        'card_pan' => isset($c['card_pan'])  ? $c['card_pan']  : '',
    );
}
?>
<title><?php echo htmlspecialchars($page_title); ?></title>

<style>
@keyframes fadeUp{from{opacity:0;transform:translateY(14px)}to{opacity:1;transform:translateY(0)}}
.anim{opacity:0;animation:fadeUp .45s ease-out forwards}
.anim-1{animation-delay:.05s}.anim-2{animation-delay:.12s}.anim-3{animation-delay:.19s}.anim-4{animation-delay:.26s}

.vcard-chip{width:36px;height:26px;border-radius:5px;background:linear-gradient(135deg,#f6c90e,#e8a800);display:inline-block;position:relative;overflow:hidden}
.vcard-chip::after{content:'';position:absolute;top:50%;left:0;right:0;height:1px;background:rgba(0,0,0,.2)}

.vc-card{
    background:linear-gradient(145deg,#2d0a5e 0%,#3b0f6b 35%,#4D148C 70%,#4D148C 100%);
    border:1px solid rgba(77,20,140,.15);border-radius:20px;padding:22px;
    position:relative;overflow:hidden;cursor:pointer;
    transition:transform .2s,box-shadow .2s;min-height:170px;
}
.vc-card:hover{transform:translateY(-2px);box-shadow:0 12px 32px rgba(77,20,140,.25)}
.vc-card::before{content:'';position:absolute;width:200px;height:200px;border-radius:50%;
    background:radial-gradient(circle,rgba(77,20,140,.25),transparent 70%);
    top:-60px;right:-60px;pointer-events:none}
.vc-card::after{content:'';position:absolute;inset:0;pointer-events:none;border-radius:20px;
    background:repeating-linear-gradient(45deg,transparent,transparent 40px,rgba(77,20,140,.025) 40px,rgba(77,20,140,.025) 41px)}
.vc-card.frozen{opacity:.75}
.frozen-overlay{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;
    font-size:1.1rem;font-weight:900;color:rgba(147,197,253,.9);letter-spacing:.2em;
    background:rgba(0,20,10,.5);border-radius:20px;z-index:5}

.action-btn{display:flex;flex-direction:column;align-items:center;gap:5px;
    background:var(--card-bg);border:1px solid var(--card-border);border-radius:14px;
    padding:12px 8px;cursor:pointer;transition:border-color .2s,background .2s;flex:1;
    color:var(--text-primary);font-size:.68rem;font-weight:600;min-width:60px}
.action-btn:hover{border-color:rgba(77,20,140,.35);background:rgba(77,20,140,.06)}
.action-btn i{font-size:1.1rem}

.txn-row{display:flex;align-items:center;gap:10px;padding:10px 0;border-bottom:1px solid var(--card-border)}
.txn-row:last-child{border-bottom:none}

.modal-overlay{position:fixed;inset:0;background:rgba(0,0,0,.7);z-index:9000;
    display:none;align-items:flex-end;justify-content:center;backdrop-filter:blur(4px)}
.modal-overlay.open{display:flex}
.modal-sheet{background:var(--card-bg);border-radius:24px 24px 0 0;width:100%;max-width:480px;
    padding:24px 20px 36px;animation:fadeUp .3s ease-out;max-height:90vh;overflow-y:auto}
.modal-handle{width:40px;height:4px;border-radius:2px;background:var(--card-border);margin:0 auto 20px;cursor:pointer}

.input-field{width:100%;background:var(--input-bg,rgba(255,255,255,.05));
    border:1.5px solid var(--card-border);border-radius:10px;padding:11px 14px;
    color:var(--text-primary);font-size:.88rem;outline:none;transition:border-color .2s;
    box-sizing:border-box;display:block;max-width:100%}
.input-field:focus{border-color:rgba(77,20,140,.5)}
/* Force date inputs to respect container width on all browsers */
input[type="date"].input-field{
    -webkit-appearance:none;appearance:none;min-width:0;width:100%;max-width:100%}
.input-label{font-size:.72rem;font-weight:600;color:var(--text-muted);margin-bottom:5px;display:block}

.btn-primary-vc{width:100%;padding:14px;border-radius:12px;font-weight:700;font-size:.88rem;
    background:linear-gradient(135deg,#4D148C,#6b23c2);color:white;border:none;cursor:pointer;
    box-shadow:0 4px 14px rgba(77,20,140,.35);transition:opacity .2s,transform .15s}
.btn-primary-vc:hover{opacity:.9;transform:translateY(-1px)}
.btn-primary-vc:disabled{opacity:.5;cursor:not-allowed;transform:none}

.details-blur{filter:blur(6px);user-select:none;transition:filter .35s ease}
.details-revealed{filter:none !important;user-select:text;transition:filter .35s ease}
</style>

<div class="max-w-2xl mx-auto" id="vcardApp">

<!-- ── Hero ─────────────────────────────────────────────────── -->
<div class="anim anim-1" style="background:linear-gradient(145deg,#2d0a5e 0%,#3b0f6b 35%,#4D148C 70%,#4D148C 100%);border:1px solid rgba(245,158,11,.15);border-radius:20px;padding:20px;margin-bottom:14px;position:relative;overflow:hidden">
    <div style="position:absolute;inset:0;pointer-events:none;background:repeating-linear-gradient(45deg,transparent,transparent 40px,rgba(77,20,140,.015) 40px,rgba(77,20,140,.015) 41px);border-radius:20px"></div>
    <div style="position:absolute;width:160px;height:160px;border-radius:50%;filter:blur(60px);background:radial-gradient(circle,rgba(77,20,140,.3),transparent);top:-40px;right:-40px;pointer-events:none"></div>
    <div style="position:relative;z-index:1;display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:14px">
        <div>
            <h2 style="font-size:1.1rem;font-weight:800;color:white;margin-bottom:4px;display:flex;align-items:center;gap:8px">
                <i class="fas fa-credit-card" style="color:#c4b5fd"></i>USD Virtual Cards
            </h2>
            <p style="color:rgba(255,255,255,.55);font-size:.78rem">Secure Visa cards for online payments worldwide.</p>
        </div>
        <?php if ($can_create): ?>
        <button onclick="openModal('createCardModal')" style="background:white;color:#4D148C;font-weight:700;font-size:.78rem;padding:10px 16px;border-radius:10px;border:none;cursor:pointer;display:inline-flex;align-items:center;gap:6px">
            <i class="fas fa-plus" style="font-size:.7rem"></i>New Card
        </button>
        <?php else: ?>
        <span style="background:rgba(255,255,255,.1);color:rgba(255,255,255,.5);font-size:.72rem;padding:8px 14px;border-radius:10px">Max <?php echo $vcard_max_per_user; ?> cards reached</span>
        <?php endif; ?>
    </div>
</div>

<?php if (empty($cards)): ?>
<!-- ── Empty state ─────────────────────────────────────────── -->
<div class="anim anim-2" style="background:var(--card-bg);border:1px solid var(--card-border);border-radius:16px;padding:48px;text-align:center">
    <div style="width:60px;height:60px;border-radius:50%;background:rgba(77,20,140,.07);display:flex;align-items:center;justify-content:center;margin:0 auto 16px">
        <i class="fas fa-credit-card" style="font-size:1.5rem;color:rgba(77,20,140,.5)"></i>
    </div>
    <h3 style="font-weight:700;font-size:.95rem;color:var(--text-primary);margin-bottom:8px">No Virtual Cards Yet</h3>
    <p style="font-size:.78rem;color:var(--text-muted);max-width:260px;margin:0 auto 20px">Create your first USD Visa card and start paying online globally.</p>
    <button onclick="openModal('createCardModal')" style="display:inline-flex;align-items:center;gap:8px;padding:12px 24px;background:linear-gradient(135deg,#4D148C,#6b23c2);color:white;font-weight:700;font-size:.82rem;border-radius:12px;border:none;cursor:pointer;box-shadow:0 4px 14px rgba(77,20,140,.3)">
        <i class="fas fa-credit-card"></i>Create Virtual Card
    </button>
</div>

<?php else: ?>
<!-- ── Cards list ─────────────────────────────────────────── -->
<?php foreach ($cards as $idx => $card):
    $frozen     = (!empty($card['is_frozen']) || $card['status'] === 'frozen');
    $card_colors = array(
        'linear-gradient(145deg,#2d0a5e 0%,#3b0f6b 35%,#4D148C 70%,#4D148C 100%)',
        'linear-gradient(145deg,#012a1a 0%,#033d28 35%,#065f46 70%,#6b23c2 100%)',
        'linear-gradient(145deg,#2d0a5e 0%,#034a30 40%,#4D148C 75%,#4D148C 100%)',
    );
    $card_color = $card_colors[$idx % 3];
    $card_id_esc = addslashes($card['card_id']);
    $card_name_esc = addslashes($card['name_on_card']);
    $card_balance = (float)$card['balance'];
?>
<div class="anim anim-<?php echo min($idx + 2, 4); ?>" style="margin-bottom:14px">

    <!-- Card Visual -->
    <div class="vc-card <?php echo $frozen ? 'frozen' : ''; ?>"
         style="background:<?php echo $card_color; ?>;margin-bottom:10px"
         onclick="toggleCardDetails(<?php echo $idx; ?>)">
        <?php if ($frozen): ?><div class="frozen-overlay">&#10052; FROZEN</div><?php endif; ?>
        <div style="position:absolute;width:120px;height:120px;border-radius:50%;filter:blur(40px);background:radial-gradient(circle,rgba(110,231,183,.18),transparent);bottom:-30px;left:-20px;pointer-events:none;z-index:1"></div>
        <div style="position:relative;z-index:2;display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:16px">
            <div class="vcard-chip"></div>
            <div style="font-size:.65rem;color:rgba(255,255,255,.5);text-align:right">
                <div style="font-weight:700;color:rgba(255,255,255,.8)"><?php echo htmlspecialchars(strtoupper(isset($card['card_type']) ? $card['card_type'] : 'VISA')); ?></div>
                <div style="color:<?php echo $frozen ? '#93c5fd' : '#c4b5fd'; ?>"><?php echo $frozen ? '&#10052; Frozen' : '&#9679; Active'; ?></div>
            </div>
        </div>
        <div id="cardPan_<?php echo $idx; ?>" class="details-blur" style="font-family:monospace;font-size:1.05rem;font-weight:700;color:white;letter-spacing:.15em;margin-bottom:14px;position:relative;z-index:2">
            <?php
            $pan = isset($card['card_pan']) && $card['card_pan'] ? $card['card_pan'] : '****************';
            $clean = str_replace(' ', '', $pan);
            if (strlen($clean) >= 12) {
                echo implode(' ', str_split($clean, 4));
            } else {
                echo '**** **** **** ' . substr($clean, -4);
            }
            ?>
        </div>
        <div style="display:flex;justify-content:space-between;align-items:flex-end;position:relative;z-index:2">
            <div>
                <div style="font-size:.58rem;color:rgba(255,255,255,.45);margin-bottom:2px">CARD HOLDER</div>
                <div style="font-size:.78rem;font-weight:700;color:white"><?php echo htmlspecialchars(strtoupper($card['name_on_card'])); ?></div>
            </div>
            <div style="text-align:center">
                <div style="font-size:.58rem;color:rgba(255,255,255,.45);margin-bottom:2px">EXPIRES</div>
                <div id="cardExp_<?php echo $idx; ?>" class="details-blur" style="font-size:.78rem;font-weight:700;color:white"><?php echo htmlspecialchars(isset($card['expiry']) ? $card['expiry'] : '**/**'); ?></div>
            </div>
            <div style="text-align:right">
                <div style="font-size:.58rem;color:rgba(255,255,255,.45);margin-bottom:2px">BALANCE</div>
                <div style="font-size:1rem;font-weight:800;color:#c4b5fd" id="cardBal_<?php echo $idx; ?>">$<?php echo number_format($card_balance, 2); ?></div>
            </div>
        </div>
        <div id="cardHint_<?php echo $idx; ?>" style="position:absolute;bottom:10px;left:50%;transform:translateX(-50%);font-size:.55rem;color:rgba(255,255,255,.25);z-index:2;white-space:nowrap">tap to reveal details</div>
    </div>

    <!-- Revealed Details Panel -->
    <div id="cardDetails_<?php echo $idx; ?>" style="display:none;background:var(--card-bg);border:1px solid var(--card-border);border-radius:14px;padding:14px;margin-bottom:10px">
        <!-- Card Number — full width single line -->
        <div style="text-align:center;margin-bottom:10px;padding-bottom:10px;border-bottom:1px solid var(--card-border)">
            <div style="font-size:.6rem;color:var(--text-muted);font-weight:600;margin-bottom:4px;letter-spacing:.05em">CARD NUMBER</div>
            <div style="font-family:monospace;font-size:.95rem;font-weight:700;color:var(--text-primary);letter-spacing:.12em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis" id="fullPan_<?php echo $idx; ?>">
                <i class="fas fa-spinner fa-spin" style="color:var(--text-muted);font-size:.9rem"></i>
            </div>
        </div>
        <!-- CVV and Expiry — side by side -->
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;text-align:center;margin-bottom:10px">
            <div>
                <div style="font-size:.6rem;color:var(--text-muted);font-weight:600;margin-bottom:3px;letter-spacing:.05em">CVV</div>
                <div style="font-family:monospace;font-size:.88rem;font-weight:700;color:var(--text-primary)" id="fullCvv_<?php echo $idx; ?>">
                    <i class="fas fa-spinner fa-spin" style="color:var(--text-muted);font-size:.9rem"></i>
                </div>
            </div>
            <div>
                <div style="font-size:.6rem;color:var(--text-muted);font-weight:600;margin-bottom:3px;letter-spacing:.05em">EXPIRY</div>
                <div style="font-family:monospace;font-size:.88rem;font-weight:700;color:var(--text-primary)" id="fullExp_<?php echo $idx; ?>">
                    <i class="fas fa-spinner fa-spin" style="color:var(--text-muted);font-size:.9rem"></i>
                </div>
            </div>
        </div>
        <div style="text-align:center">
            <button onclick="copyCardNumber(<?php echo $idx; ?>)" style="padding:5px 14px;border-radius:7px;background:rgba(77,20,140,.1);border:1px solid rgba(77,20,140,.2);color:#4D148C;font-size:.7rem;cursor:pointer">
                <i class="fa-regular fa-copy"></i> Copy Number
            </button>
        </div>
        <div id="billingAddr_<?php echo $idx; ?>" style="display:none"></div>
    </div>

    <!-- Action Buttons -->
    <div style="display:flex;gap:8px;margin-bottom:10px">
        <button class="action-btn" onclick="toggleCardDetails(<?php echo $idx; ?>)" style="color:#4D148C">
            <i class="fas fa-eye" style="color:#4D148C"></i>Details
        </button>
        <button class="action-btn" onclick="openFundModal(<?php echo $idx; ?>, '<?php echo $card_id_esc; ?>')" style="color:#4D148C">
            <i class="fas fa-plus-circle" style="color:#4D148C"></i>Add Money
        </button>
        <button class="action-btn"
                onclick="toggleFreezeCard(<?php echo $idx; ?>, '<?php echo $card_id_esc; ?>', <?php echo $frozen ? 1 : 0; ?>)"
                id="freezeBtn_<?php echo $idx; ?>"
                style="color:<?php echo $frozen ? '#4D148C' : '#4D148C'; ?>">
            <i class="fas <?php echo $frozen ? 'fa-sun' : 'fa-snowflake'; ?>"
               id="freezeIcon_<?php echo $idx; ?>"
               style="color:<?php echo $frozen ? '#4D148C' : '#4D148C'; ?>"></i>
            <span id="freezeLabel_<?php echo $idx; ?>"><?php echo $frozen ? 'Unfreeze' : 'Freeze'; ?></span>
        </button>
        <button class="action-btn" onclick="openMoreMenu(<?php echo $idx; ?>, '<?php echo $card_id_esc; ?>', '<?php echo $card_name_esc; ?>', <?php echo $card_balance; ?>)" style="color:#4D148C">
            <i class="fas fa-ellipsis" style="color:#4D148C"></i>More
        </button>
    </div>

    <!-- Transaction History -->
    <div style="background:var(--card-bg);border:1px solid var(--card-border);border-radius:14px;overflow:hidden">
        <button onclick="toggleTxns(<?php echo $idx; ?>, '<?php echo $card_id_esc; ?>')"
                style="width:100%;padding:12px 14px;background:none;border:none;cursor:pointer;display:flex;align-items:center;justify-content:space-between;color:var(--text-primary)">
            <span style="font-size:.8rem;font-weight:700">
                <i class="fas fa-list-ul" style="margin-right:6px;color:#4D148C;font-size:.75rem"></i>Transaction History
            </span>
            <i class="fas fa-chevron-down" style="font-size:.65rem;color:var(--text-muted);transition:transform .2s" id="txnChevron_<?php echo $idx; ?>"></i>
        </button>
        <div id="txnList_<?php echo $idx; ?>" style="display:none;padding:0 14px 12px"></div>
    </div>

</div>
<?php endforeach; ?>
<?php endif; ?>
</div>

<!-- ════════════════════════════════════════════
     MODALS
════════════════════════════════════════════ -->

<!-- ── Create Card Modal ─────────────────────── -->
<div class="modal-overlay" id="createCardModal">
  <div class="modal-sheet">
    <div class="modal-handle" onclick="closeModal('createCardModal')"></div>
    <h3 style="font-weight:800;font-size:1rem;margin-bottom:4px;color:var(--text-primary)">
        <i class="fas fa-credit-card" style="color:#4D148C;margin-right:8px"></i>Create Virtual Card
    </h3>
    <p style="font-size:.73rem;color:var(--text-muted);margin-bottom:16px">
        Fill in all details below. A Visa USD card will be issued to you instantly.
    </p>

    <?php if ($vcard_creation_fee > 0): ?>
    <div style="background:rgba(77,20,140,.06);border:1px solid rgba(77,20,140,.15);border-radius:10px;padding:10px 14px;margin-bottom:14px;font-size:.73rem;color:#4D148C">
        <i class="fas fa-info-circle" style="margin-right:5px"></i>
        Card creation fee: <strong>&#8358;<?php echo number_format($vcard_creation_fee, 2); ?></strong>
    </div>
    <?php endif; ?>

    <!-- Card Name -->
    <div style="margin-bottom:12px">
        <label class="input-label">Card Name <span style="color:#ef4444">*</span></label>
        <input type="text" class="input-field" id="cc_name" placeholder="e.g. Your Name" maxlength="40">
    </div>

    <!-- First & Last Name -->
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:12px">
        <div>
            <label class="input-label">First Name <span style="color:#ef4444">*</span></label>
            <input type="text" class="input-field" id="cc_first_name" placeholder="John">
        </div>
        <div>
            <label class="input-label">Last Name <span style="color:#ef4444">*</span></label>
            <input type="text" class="input-field" id="cc_last_name" placeholder="Doe">
        </div>
    </div>
    
    <!-- DOB -->
    <div style="margin-bottom:12px">
        <label class="input-label">Date of Birth <span style="color:#ef4444">*</span></label>
        <input type="date" class="input-field" id="cc_dob"
               max="<?php echo date('Y-m-d', strtotime('-18 years')); ?>"
               style="width:100%;max-width:100%;box-sizing:border-box;display:block;-webkit-appearance:none;appearance:none;min-width:0">
    </div>
    
    <!-- Phone -->
    <div style="margin-bottom:12px">
        <label class="input-label">Phone Number <span style="color:#ef4444">*</span></label>
        <input type="tel" class="input-field" id="cc_phone" placeholder="08012345678">
    </div>

    <!-- ID Type + ID Number -->
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:12px">
        <div>
            <label class="input-label">ID Type <span style="color:#ef4444">*</span></label>
            <select class="input-field" id="cc_id_type">
                <option value="">Select</option>
                <option value="national_id">National ID</option>
                <option value="passport">Passport</option>
                <option value="drivers_license">Driver's License</option>
            </select>
        </div>
        <div>
            <label class="input-label">ID Number <span style="color:#ef4444">*</span></label>
            <input type="text" class="input-field" id="cc_id_number" placeholder="ID Number">
        </div>
    </div>

    <!-- Address Line 1 -->
    <div style="margin-bottom:12px">
        <label class="input-label">Address Line 1 <span style="color:#ef4444">*</span></label>
        <input type="text" class="input-field" id="cc_line1" placeholder="12 Broad Street">
    </div>

    <!-- City + State -->
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:12px">
        <div>
            <label class="input-label">City <span style="color:#ef4444">*</span></label>
            <input type="text" class="input-field" id="cc_city" placeholder="Lagos">
        </div>
        <div>
            <label class="input-label">State <span style="color:#ef4444">*</span></label>
            <input type="text" class="input-field" id="cc_state" placeholder="Lagos State">
        </div>
    </div>

    <!-- Postal Code + Country -->
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:12px">
        <div>
            <label class="input-label">Postal Code <span style="color:#ef4444">*</span></label>
            <input type="text" class="input-field" id="cc_postal_code" placeholder="100001">
        </div>
        <div>
            <label class="input-label">Country <span style="color:#ef4444">*</span></label>
            <select class="input-field" id="cc_country">
                <option value="">Select</option>
                <option value="NGA" selected>Nigeria (NGA)</option>
                <option value="ALB">Albania (ALB)</option>
                <option value="DZA">Algeria (DZA)</option>
                <option value="AGO">Angola (AGO)</option>
                <option value="ARG">Argentina (ARG)</option>
                <option value="ARM">Armenia (ARM)</option>
                <option value="AUS">Australia (AUS)</option>
                <option value="AUT">Austria (AUT)</option>
                <option value="AZE">Azerbaijan (AZE)</option>
                <option value="BHR">Bahrain (BHR)</option>
                <option value="BGD">Bangladesh (BGD)</option>
                <option value="BLR">Belarus (BLR)</option>
                <option value="BEL">Belgium (BEL)</option>
                <option value="BEN">Benin (BEN)</option>
                <option value="BWA">Botswana (BWA)</option>
                <option value="BRA">Brazil (BRA)</option>
                <option value="BGR">Bulgaria (BGR)</option>
                <option value="CMR">Cameroon (CMR)</option>
                <option value="CAN">Canada (CAN)</option>
                <option value="TCD">Chad (TCD)</option>
                <option value="CHL">Chile (CHL)</option>
                <option value="CHN">China (CHN)</option>
                <option value="COL">Colombia (COL)</option>
                <option value="COG">Congo (COG)</option>
                <option value="CRI">Costa Rica (CRI)</option>
                <option value="HRV">Croatia (HRV)</option>
                <option value="CYP">Cyprus (CYP)</option>
                <option value="CZE">Czech Republic (CZE)</option>
                <option value="DNK">Denmark (DNK)</option>
                <option value="EGY">Egypt (EGY)</option>
                <option value="ETH">Ethiopia (ETH)</option>
                <option value="FIN">Finland (FIN)</option>
                <option value="FRA">France (FRA)</option>
                <option value="GAB">Gabon (GAB)</option>
                <option value="GMB">Gambia (GMB)</option>
                <option value="DEU">Germany (DEU)</option>
                <option value="GHA">Ghana (GHA)</option>
                <option value="GRC">Greece (GRC)</option>
                <option value="HTI">Haiti (HTI)</option>
                <option value="HUN">Hungary (HUN)</option>
                <option value="IND">India (IND)</option>
                <option value="IDN">Indonesia (IDN)</option>
                <option value="IRL">Ireland (IRL)</option>
                <option value="ISR">Israel (ISR)</option>
                <option value="ITA">Italy (ITA)</option>
                <option value="JPN">Japan (JPN)</option>
                <option value="KEN">Kenya (KEN)</option>
                <option value="LBN">Lebanon (LBN)</option>
                <option value="LBY">Libya (LBY)</option>
                <option value="MYS">Malaysia (MYS)</option>
                <option value="MEX">Mexico (MEX)</option>
                <option value="MAR">Morocco (MAR)</option>
                <option value="NAM">Namibia (NAM)</option>
                <option value="NLD">Netherlands (NLD)</option>
                <option value="NZL">New Zealand (NZL)</option>
                <option value="NPL">Nepal (NPL)</option>
                <option value="PAK">Pakistan (PAK)</option>
                <option value="PER">Peru (PER)</option>
                <option value="PHL">Philippines (PHL)</option>
                <option value="POL">Poland (POL)</option>
                <option value="PRT">Portugal (PRT)</option>
                <option value="QAT">Qatar (QAT)</option>
                <option value="ROU">Romania (ROU)</option>
                <option value="SAU">Saudi Arabia (SAU)</option>
                <option value="SEN">Senegal (SEN)</option>
                <option value="SGP">Singapore (SGP)</option>
                <option value="ZAF">South Africa (ZAF)</option>
                <option value="KOR">South Korea (KOR)</option>
                <option value="ESP">Spain (ESP)</option>
                <option value="SWE">Sweden (SWE)</option>
                <option value="CHE">Switzerland (CHE)</option>
                <option value="TZA">Tanzania (TZA)</option>
                <option value="THA">Thailand (THA)</option>
                <option value="TUN">Tunisia (TUN)</option>
                <option value="TUR">Turkey (TUR)</option>
                <option value="UGA">Uganda (UGA)</option>
                <option value="UKR">Ukraine (UKR)</option>
                <option value="ARE">United Arab Emirates (ARE)</option>
                <option value="GBR">United Kingdom (GBR)</option>
                <option value="USA">United States (USA)</option>
                <option value="VNM">Vietnam (VNM)</option>
                <option value="ZMB">Zambia (ZMB)</option>
                <option value="ZWE">Zimbabwe (ZWE)</option>
            </select>
        </div>
    </div>

    <!-- Funding Amount -->
    <div style="margin-bottom:18px">
        <label class="input-label">Funding Amount (USD) &mdash; min $<?php echo number_format($vcard_min_fund, 2); ?> <span style="color:#ef4444">*</span></label>
        <div style="position:relative">
            <span style="position:absolute;left:12px;top:50%;transform:translateY(-50%);font-weight:700;color:var(--text-muted)">$</span>
            <input type="number" class="input-field" id="cc_amount"
                   min="<?php echo $vcard_min_fund; ?>" step="0.01"
                   placeholder="<?php echo number_format($vcard_min_fund, 2); ?>"
                   style="padding-left:28px;width:100%;box-sizing:border-box;display:block"
                   oninput="updateCreatePreview()">
        </div>
        <p id="cc_ngn_preview" style="font-size:.7rem;color:var(--text-muted);margin-top:5px"></p>
    </div>

    <button class="btn-primary-vc" id="createCardBtn" onclick="submitCreateCard()">
        <i class="fas fa-credit-card" style="margin-right:8px"></i>Create My Card
    </button>
    <button onclick="closeModal('createCardModal')"
            style="width:100%;padding:12px;border-radius:12px;font-weight:600;font-size:.85rem;background:transparent;color:var(--text-muted);border:1.5px solid var(--card-border);cursor:pointer;margin-top:8px">
        Cancel
    </button>
  </div>
</div>

<!-- ── Fund Card Modal ───────────────────────── -->
<div class="modal-overlay" id="fundCardModal">
  <div class="modal-sheet">
    <div class="modal-handle" onclick="closeModal('fundCardModal')"></div>
    <h3 style="font-weight:800;font-size:1rem;margin-bottom:4px;color:var(--text-primary)">
        <i class="fas fa-plus-circle" style="color:#4D148C;margin-right:8px"></i>Add Money to Card
    </h3>
    <p style="font-size:.75rem;color:var(--text-muted);margin-bottom:18px">
        Funds will be deducted from your wallet (NGN) and added to your card (USD).
    </p>
    <input type="hidden" id="fund_card_id">
    <div style="margin-bottom:14px">
        <label class="input-label">Amount (USD)</label>
        <div style="position:relative">
            <span style="position:absolute;left:12px;top:50%;transform:translateY(-50%);font-weight:700;color:var(--text-muted)">$</span>
            <input type="number" class="input-field" id="fund_amount"
                   min="<?php echo $vcard_min_fund; ?>" step="0.01"
                   placeholder="<?php echo number_format($vcard_min_fund, 2); ?>"
                   style="padding-left:28px" oninput="updateFundPreview()">
        </div>
        <p id="fund_ngn_preview" style="font-size:.7rem;color:var(--text-muted);margin-top:5px"></p>
    </div>
    <div style="background:rgba(77,20,140,.06);border:1px solid rgba(77,20,140,.15);border-radius:10px;padding:10px 14px;margin-bottom:16px;font-size:.75rem;color:#4D148C">
        <i class="fas fa-exchange-alt" style="margin-right:5px"></i>
        Rate: $1 = &#8358;<?php echo number_format($vcard_fund_rate, 2); ?>
    </div>
    <button class="btn-primary-vc" id="fundCardBtn" onclick="submitFundCard()">
        <i class="fas fa-plus" style="margin-right:8px"></i>Fund Card
    </button>
    <button onclick="closeModal('fundCardModal')"
            style="width:100%;padding:12px;border-radius:12px;font-weight:600;font-size:.85rem;background:transparent;color:var(--text-muted);border:1.5px solid var(--card-border);cursor:pointer;margin-top:8px">
        Cancel
    </button>
  </div>
</div>

<!-- ── More Menu Modal ───────────────────────── -->
<div class="modal-overlay" id="moreMenuModal">
  <div class="modal-sheet">
    <div class="modal-handle" onclick="closeModal('moreMenuModal')"></div>
    <h3 style="font-weight:800;font-size:.95rem;margin-bottom:16px;color:var(--text-primary)" id="moreMenuTitle">Card Options</h3>
    <input type="hidden" id="more_card_id">
    <input type="hidden" id="more_card_balance">

    <button onclick="openWithdrawModal()" style="width:100%;padding:14px 16px;border-radius:12px;background:var(--card-bg);border:1px solid var(--card-border);color:var(--text-primary);font-size:.85rem;font-weight:600;cursor:pointer;display:flex;align-items:center;gap:12px;margin-bottom:8px;text-align:left">
        <div style="width:36px;height:36px;border-radius:9px;background:rgba(77,20,140,.1);display:flex;align-items:center;justify-content:center;flex-shrink:0">
            <i class="fas fa-wallet" style="color:#4D148C"></i>
        </div>
        <div><div style="font-weight:700">Withdraw Funds</div><div style="font-size:.7rem;color:var(--text-muted)">Move card balance to your wallet</div></div>
    </button>

    <button onclick="openStatementModal()" style="width:100%;padding:14px 16px;border-radius:12px;background:var(--card-bg);border:1px solid var(--card-border);color:var(--text-primary);font-size:.85rem;font-weight:600;cursor:pointer;display:flex;align-items:center;gap:12px;margin-bottom:8px;text-align:left">
        <div style="width:36px;height:36px;border-radius:9px;background:rgba(77,20,140,.1);display:flex;align-items:center;justify-content:center;flex-shrink:0">
            <i class="fas fa-file-invoice" style="color:#4D148C"></i>
        </div>
        <div><div style="font-weight:700">Get Card Statement</div><div style="font-size:.7rem;color:var(--text-muted)">Download transaction statement</div></div>
    </button>

    <button onclick="confirmDeleteCard()" style="width:100%;padding:14px 16px;border-radius:12px;background:rgba(239,68,68,.06);border:1px solid rgba(239,68,68,.15);color:#ef4444;font-size:.85rem;font-weight:600;cursor:pointer;display:flex;align-items:center;gap:12px;text-align:left">
        <div style="width:36px;height:36px;border-radius:9px;background:rgba(239,68,68,.1);display:flex;align-items:center;justify-content:center;flex-shrink:0">
            <i class="fas fa-trash" style="color:#ef4444"></i>
        </div>
        <div><div style="font-weight:700">Delete Card</div><div style="font-size:.7rem;color:rgba(239,68,68,.7)">Permanently terminate this card</div></div>
    </button>

    <button onclick="closeModal('moreMenuModal')"
            style="width:100%;padding:12px;border-radius:12px;font-weight:600;font-size:.85rem;background:transparent;color:var(--text-muted);border:1.5px solid var(--card-border);cursor:pointer;margin-top:12px">
        Cancel
    </button>
  </div>
</div>

<!-- ── Withdraw Modal ─────────────────────────── -->
<div class="modal-overlay" id="withdrawModal">
  <div class="modal-sheet">
    <div class="modal-handle" onclick="closeModal('withdrawModal')"></div>
    <h3 style="font-weight:800;font-size:1rem;margin-bottom:4px;color:var(--text-primary)">
        <i class="fas fa-wallet" style="color:#4D148C;margin-right:8px"></i>Withdraw Funds
    </h3>
    <p style="font-size:.75rem;color:var(--text-muted);margin-bottom:18px">Convert your card balance (USD) to your wallet (NGN).</p>
    <div style="margin-bottom:14px">
        <label class="input-label">Amount to Withdraw (USD)</label>
        <div style="position:relative">
            <span style="position:absolute;left:12px;top:50%;transform:translateY(-50%);font-weight:700;color:var(--text-muted)">$</span>
            <input type="number" class="input-field" id="wd_amount"
                   min="1" step="0.01" placeholder="Enter amount"
                   style="padding-left:28px" oninput="updateWdPreview()">
        </div>
        <p id="wd_ngn_preview" style="font-size:.7rem;color:var(--text-muted);margin-top:5px"></p>
    </div>
    <div style="background:rgba(245,158,11,.06);border:1px solid rgba(245,158,11,.15);border-radius:10px;padding:10px 14px;margin-bottom:16px;font-size:.75rem;color:#d97706">
        <i class="fas fa-info-circle" style="margin-right:5px"></i>
        Rate: $1 = &#8358;<?php echo number_format($vcard_withdraw_rate, 2); ?> &middot;
        Balance after withdrawal should be at least: $<?php echo number_format($vcard_min_balance, 2); ?>
    </div>
    <button class="btn-primary-vc" id="withdrawBtn" onclick="submitWithdraw()"
            style="background:linear-gradient(135deg,#6b23c2,#4D148C)">
        <i class="fas fa-wallet" style="margin-right:8px"></i>Withdraw to Wallet
    </button>
    <button onclick="closeModal('withdrawModal')"
            style="width:100%;padding:12px;border-radius:12px;font-weight:600;font-size:.85rem;background:transparent;color:var(--text-muted);border:1.5px solid var(--card-border);cursor:pointer;margin-top:8px">
        Cancel
    </button>
  </div>
</div>

<!-- ── Statement Modal ───────────────────────── -->
<div class="modal-overlay" id="statementModal">
  <div class="modal-sheet">
    <div class="modal-handle" onclick="closeModal('statementModal')"></div>
    <h3 style="font-weight:800;font-size:1rem;margin-bottom:4px;color:var(--text-primary)">
        <i class="fas fa-file-invoice" style="color:#4D148C;margin-right:8px"></i>Card Statement
    </h3>
    <p style="font-size:.75rem;color:var(--text-muted);margin-bottom:18px">Select a date range for your statement.</p>
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-bottom:14px">
        <div>
            <label class="input-label">From</label>
            <input type="date" class="input-field" id="stmt_from" style="width:100%;box-sizing:border-box;display:block">
        </div>
        <div>
            <label class="input-label">To</label>
            <input type="date" class="input-field" id="stmt_to" style="width:100%;box-sizing:border-box;display:block">
        </div>
    </div>
    <div id="stmtResult" style="display:none;margin-bottom:14px"></div>
    <button class="btn-primary-vc" id="stmtBtn" onclick="fetchStatement()">
        <i class="fas fa-download" style="margin-right:8px"></i>Get Statement
    </button>
    <button onclick="closeModal('statementModal')"
            style="width:100%;padding:12px;border-radius:12px;font-weight:600;font-size:.85rem;background:transparent;color:var(--text-muted);border:1.5px solid var(--card-border);cursor:pointer;margin-top:8px">
        Cancel
    </button>
  </div>
</div>

<script>
// ── Constants from PHP ────────────────────────────────────────
var FUND_RATE    = <?php echo (float)$vcard_fund_rate; ?>;
var WD_RATE      = <?php echo (float)$vcard_withdraw_rate; ?>;
var MIN_BALANCE  = <?php echo (float)$vcard_min_balance; ?>;
var MIN_FUND     = <?php echo (float)$vcard_min_fund; ?>;
var CREATION_FEE = <?php echo (float)$vcard_creation_fee; ?>;
var CARDS_DATA   = <?php echo json_encode($cards_js); ?>;

// ── State ─────────────────────────────────────────────────────
var activeMoreIdx      = null;
var activeMoreCardId   = '';
var activeMoreBalance  = 0;
var activeFundCardId   = '';
var revealedCards      = {};
var txnLoaded          = {};

// ── Modal helpers ─────────────────────────────────────────────
function openModal(id)  { document.getElementById(id).classList.add('open'); }
function closeModal(id) { document.getElementById(id).classList.remove('open'); }

document.querySelectorAll('.modal-overlay').forEach(function(o) {
    o.addEventListener('click', function(e) { if (e.target === o) o.classList.remove('open'); });
});

// ── Card details reveal ───────────────────────────────────────
function toggleCardDetails(idx) {
    var box = document.getElementById('cardDetails_' + idx);
    if (box.style.display === 'none') {
        box.style.display = 'block';
        // Always re-fetch — card may have moved from processing to active
        fetchCardDetails(idx);
    } else {
        box.style.display = 'none';
        // Re-blur card face when details are hidden
        var facePanEl = document.getElementById('cardPan_' + idx);
        var faceExpEl = document.getElementById('cardExp_' + idx);
        var hintEl    = document.getElementById('cardHint_' + idx);
        if (facePanEl) { facePanEl.classList.add('details-blur'); facePanEl.classList.remove('details-revealed'); }
        if (faceExpEl) { faceExpEl.classList.add('details-blur'); faceExpEl.classList.remove('details-revealed'); }
        if (hintEl)    { hintEl.textContent = 'tap to reveal details'; hintEl.style.color = 'rgba(255,255,255,.25)'; }
    }
}

function fetchCardDetails(idx) {
    var c = CARDS_DATA[idx];
    if (!c) return;

    var panEl  = document.getElementById('fullPan_' + idx);
    var cvvEl  = document.getElementById('fullCvv_' + idx);
    var expEl  = document.getElementById('fullExp_' + idx);
    var balEl  = document.getElementById('cardBal_' + idx);

    // Card face elements (blurred until revealed)
    var facePanEl  = document.getElementById('cardPan_' + idx);
    var faceExpEl  = document.getElementById('cardExp_' + idx);
    var hintEl     = document.getElementById('cardHint_' + idx);

    panEl.innerHTML = '<i class="fas fa-spinner fa-spin" style="color:var(--text-muted);font-size:.9rem"></i>';
    cvvEl.innerHTML = '<i class="fas fa-spinner fa-spin" style="color:var(--text-muted);font-size:.9rem"></i>';
    expEl.innerHTML = '<i class="fas fa-spinner fa-spin" style="color:var(--text-muted);font-size:.9rem"></i>';

    apiPost('ajax/vcard-handler.php', {action: 'get_card_details', card_id: c.card_id})
        .then(function(r) {
            if (r.status !== '1') {
                panEl.textContent = r.msg || 'Could not load card details.';
                return;
            }

            var d      = r.card;
            var status = (d.card_status || '').toLowerCase();
            var pan    = d.card_number || '';
            var cvv    = d.cvv        || '';
            var expiry = d.expiry     || '';
            var bal    = parseFloat(d.balance || 0);

            // Update balance on card face
            if (balEl && bal >= 0) {
                balEl.textContent = '$' + bal.toFixed(2);
            }

            // ── Card still processing ─────────────────────────
            if (status === 'processing' && !pan) {
                panEl.innerHTML = '<span style="color:#d97706;font-size:.72rem">'
                    + '<i class="fas fa-clock" style="margin-right:4px"></i>'
                    + 'Card is being processed.<br>Check back in a few minutes.</span>';
                cvvEl.textContent = '\u2014';
                expEl.textContent = '\u2014';
                var refreshDiv = document.getElementById('detailsRefresh_' + idx);
                if (!refreshDiv) {
                    refreshDiv = document.createElement('div');
                    refreshDiv.id = 'detailsRefresh_' + idx;
                    refreshDiv.style.cssText = 'text-align:center;margin-top:10px';
                    refreshDiv.innerHTML = '<button onclick="fetchCardDetails(' + idx + ')" '
                        + 'style="padding:6px 16px;border-radius:8px;background:rgba(245,158,11,.1);'
                        + 'border:1px solid rgba(245,158,11,.3);color:#d97706;font-size:.72rem;cursor:pointer">'
                        + '<i class="fas fa-rotate-right" style="margin-right:5px"></i>Refresh Details</button>';
                    var detailBox = document.getElementById('cardDetails_' + idx);
                    if (detailBox) detailBox.appendChild(refreshDiv);
                }
                return;
            }

            // ── Card active — fill detail panel ───────────────
            panEl.textContent = pan    ? pan    : 'Not available';
            cvvEl.textContent = cvv    ? cvv    : '\u2014';
            expEl.textContent = expiry ? expiry : '\u2014';

            // Remove refresh button if previously shown
            var refreshDiv = document.getElementById('detailsRefresh_' + idx);
            if (refreshDiv && refreshDiv.parentNode) refreshDiv.parentNode.removeChild(refreshDiv);

            // ── Unblur card face and update with real values ──
            if (pan && facePanEl) {
                // Format PAN into groups of 4
                var clean  = pan.replace(/\s/g, '');
                var groups = [];
                for (var i = 0; i < clean.length; i += 4) groups.push(clean.substr(i, 4));
                facePanEl.textContent = groups.join(' ');
                // Remove blur, add revealed
                facePanEl.classList.remove('details-blur');
                facePanEl.classList.add('details-revealed');
            }
            if (expiry && faceExpEl) {
                faceExpEl.textContent = expiry;
                faceExpEl.classList.remove('details-blur');
                faceExpEl.classList.add('details-revealed');
            }
            // Update hint text
            if (hintEl) {
                hintEl.textContent = 'tap to hide details';
                hintEl.style.color = 'rgba(255,255,255,.45)';
            }

            // ── Billing address — StroWallet's fixed US address ──
            var billingEl = document.getElementById('billingAddr_' + idx);
            if (billingEl && pan) {
                billingEl.style.display = 'block';
                var rows = ''
                    + '<div style="display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid var(--card-border)"><span style="font-size:.68rem;color:var(--text-muted)">Address</span><span style="font-size:.72rem;font-weight:600;color:var(--text-primary);text-align:right;max-width:65%">3401 N. Miami, Ave. Ste 230</span></div>'
                    + '<div style="display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid var(--card-border)"><span style="font-size:.68rem;color:var(--text-muted)">City</span><span style="font-size:.72rem;font-weight:600;color:var(--text-primary)">Miami</span></div>'
                    + '<div style="display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid var(--card-border)"><span style="font-size:.68rem;color:var(--text-muted)">State</span><span style="font-size:.72rem;font-weight:600;color:var(--text-primary)">Florida</span></div>'
                    + '<div style="display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid var(--card-border)"><span style="font-size:.68rem;color:var(--text-muted)">Postal Code</span><span style="font-size:.72rem;font-weight:600;color:var(--text-primary)">33127</span></div>'
                    + '<div style="display:flex;justify-content:space-between;padding:6px 0"><span style="font-size:.68rem;color:var(--text-muted)">Country</span><span style="font-size:.72rem;font-weight:600;color:var(--text-primary)">United States</span></div>';
                billingEl.innerHTML = '<div style="margin-top:12px;padding-top:12px;border-top:1.5px solid var(--card-border)">'
                    + '<p style="font-size:.65rem;font-weight:700;color:var(--text-muted);margin-bottom:4px;text-transform:uppercase;letter-spacing:.05em">Billing Address</p>'
                    + rows
                    + '</div>';
            }

            revealedCards[idx] = true;
        });
}

function copyCardNumber(idx) {
    var txt = document.getElementById('fullPan_' + idx).textContent.replace(/\s/g, '');
    // Don't copy placeholder text or processing messages
    if (!txt || txt.length < 13 || txt.indexOf('processing') !== -1 || txt.indexOf('Fetch') !== -1 || txt.indexOf('available') !== -1) {
        toast('Card number not yet available', '#d97706');
        return;
    }
    if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(txt).then(function() { toast('Card number copied!', '#4D148C'); });
    } else {
        var ta = document.createElement('textarea');
        ta.value = txt;
        document.body.appendChild(ta);
        ta.select();
        document.execCommand('copy');
        document.body.removeChild(ta);
        toast('Card number copied!', '#4D148C');
    }
}

// ── Transaction history ───────────────────────────────────────
function toggleTxns(idx, cardId) {
    var box     = document.getElementById('txnList_' + idx);
    var chevron = document.getElementById('txnChevron_' + idx);
    if (box.style.display === 'none') {
        box.style.display = 'block';
        chevron.style.transform = 'rotate(180deg)';
        if (!txnLoaded[idx]) loadTxns(idx, cardId);
    } else {
        box.style.display = 'none';
        chevron.style.transform = '';
    }
}

function loadTxns(idx, cardId) {
    var box = document.getElementById('txnList_' + idx);
    box.innerHTML = '<div style="text-align:center;padding:16px;font-size:.75rem;color:var(--text-muted)"><i class="fas fa-spinner fa-spin"></i> Loading\u2026</div>';

    apiPost('ajax/vcard-handler.php', {action: 'get_transactions', card_id: cardId})
        .then(function(r) {
            if (r.status === '1' && r.transactions && r.transactions.length) {
                var html = '';
                for (var i = 0; i < r.transactions.length; i++) {
                    var t        = r.transactions[i];
                    // Normalized fields from handler: type, description, amount, status, date, method
                    var isCredit = (t.type === 'credit');
                    var amt      = Math.abs(parseFloat(t.amount || 0));
                    var sign     = isCredit ? '+' : '-';
                    var col      = isCredit ? '#4D148C' : '#ef4444';
                    var desc     = t.description || t.method || 'Transaction';
                    var date     = t.date || '';
                    var stColor  = t.status === 'success'  ? '#4D148C'
                                 : t.status === 'failed'   ? '#ef4444'
                                 : '#d97706';
                    var stLabel  = t.status ? t.status.charAt(0).toUpperCase() + t.status.slice(1) : '';
                    html += '<div class="txn-row" style="border-left:3px solid ' + col + ';padding-left:10px;margin-left:0">';
                    html += '<div style="flex:1;min-width:0">';
                    html += '<p style="font-size:.78rem;font-weight:600;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis">' + escHtml(desc) + '</p>';
                    html += '<p style="font-size:.65rem;color:var(--text-muted)">' + escHtml(date);
                    if (stLabel) html += ' &nbsp;<span style="color:' + stColor + ';font-weight:600">' + escHtml(stLabel) + '</span>';
                    html += '</p></div>';
                    html += '<div style="font-weight:800;font-size:.88rem;color:' + col + ';font-family:monospace;flex-shrink:0;padding-left:8px">' + sign + '$' + amt.toFixed(2) + '</div>';
                    html += '</div>';
                }
                box.innerHTML = html;
            } else {
                box.innerHTML = '<p style="text-align:center;padding:14px;font-size:.75rem;color:var(--text-muted)">No transactions found.</p>';
            }
            txnLoaded[idx] = true;
        });
}

// ── Fund card ─────────────────────────────────────────────────
function openFundModal(idx, cardId) {
    activeFundCardId = cardId;
    document.getElementById('fund_card_id').value = cardId;
    document.getElementById('fund_amount').value = '';
    document.getElementById('fund_ngn_preview').textContent = '';
    openModal('fundCardModal');
}
function updateFundPreview() {
    var amt = parseFloat(document.getElementById('fund_amount').value) || 0;
    var ngn = amt * FUND_RATE;
    document.getElementById('fund_ngn_preview').textContent = amt > 0
        ? '\u2248 \u20a6' + ngn.toLocaleString('en-NG', {minimumFractionDigits: 2}) + ' will be deducted from your wallet'
        : '';
}
function submitFundCard() {
    var cardId = document.getElementById('fund_card_id').value;
    var amount = parseFloat(document.getElementById('fund_amount').value);
    if (!amount || amount < MIN_FUND) { toast('Minimum top-up is $' + MIN_FUND, '#ef4444'); return; }
    setBtnLoading('fundCardBtn', true, 'Funding\u2026');
    apiPost('ajax/vcard-handler.php', {action: 'fund_card', card_id: cardId, amount: amount})
        .then(function(r) {
            setBtnLoading('fundCardBtn', false, '<i class="fas fa-plus" style="margin-right:8px"></i>Fund Card');
            if (r.status === '1') { toast(r.msg || 'Card funded!', '#4D148C'); closeModal('fundCardModal'); setTimeout(function(){ location.reload(); }, 1500); }
            else toast(r.msg || 'Failed', '#ef4444');
        });
}

// ── Freeze/Unfreeze ───────────────────────────────────────────
function toggleFreezeCard(idx, cardId, frozen) {
    var action = frozen ? 'unfreeze' : 'freeze';
    if (!confirm((frozen ? 'Unfreeze' : 'Freeze') + ' this card?')) return;
    apiPost('ajax/vcard-handler.php', {action: 'freeze_card', card_id: cardId, freeze_action: action})
        .then(function(r) {
            if (r.status === '1') { toast(r.msg || 'Done!', '#4D148C'); setTimeout(function(){ location.reload(); }, 1200); }
            else toast(r.msg || 'Failed', '#ef4444');
        });
}

// ── More menu ─────────────────────────────────────────────────
function openMoreMenu(idx, cardId, name, balance) {
    activeMoreIdx     = idx;
    activeMoreCardId  = cardId;
    activeMoreBalance = balance;
    document.getElementById('more_card_id').value      = cardId;
    document.getElementById('more_card_balance').value = balance;
    document.getElementById('moreMenuTitle').textContent = '\u25cf ' + name;
    openModal('moreMenuModal');
}

// ── Withdraw ──────────────────────────────────────────────────
function openWithdrawModal() {
    closeModal('moreMenuModal');
    document.getElementById('wd_amount').value = '';
    document.getElementById('wd_ngn_preview').textContent = '';
    openModal('withdrawModal');
}
function updateWdPreview() {
    var amt = parseFloat(document.getElementById('wd_amount').value) || 0;
    var ngn = amt * WD_RATE;
    document.getElementById('wd_ngn_preview').textContent = amt > 0
        ? '\u2248 \u20a6' + ngn.toLocaleString('en-NG', {minimumFractionDigits: 2}) + ' will be added to your wallet'
        : '';
}
function submitWithdraw() {
    var cardId = activeMoreCardId;
    var amount = parseFloat(document.getElementById('wd_amount').value);
    if (!amount || amount <= 0) { toast('Enter a valid amount', '#ef4444'); return; }
    if (activeMoreBalance - amount < MIN_BALANCE) {
        toast('Card must retain at least $' + MIN_BALANCE + ' balance', '#ef4444'); return;
    }
    setBtnLoading('withdrawBtn', true, 'Processing\u2026');
    apiPost('ajax/vcard-handler.php', {action: 'withdraw_card', card_id: cardId, amount: amount})
        .then(function(r) {
            setBtnLoading('withdrawBtn', false, '<i class="fas fa-wallet" style="margin-right:8px"></i>Withdraw to Wallet');
            if (r.status === '1') { toast(r.msg || 'Withdrawn!', '#4D148C'); closeModal('withdrawModal'); setTimeout(function(){ location.reload(); }, 1500); }
            else toast(r.msg || 'Failed', '#ef4444');
        });
}

// ── Statement ─────────────────────────────────────────────────
function openStatementModal() {
    closeModal('moreMenuModal');
    document.getElementById('stmtResult').style.display = 'none';
    var now = new Date();
    var y   = now.getFullYear();
    var m   = String(now.getMonth() + 1).padStart(2, '0');
    var last = new Date(y, now.getMonth() + 1, 0).getDate();
    document.getElementById('stmt_from').value = y + '-' + m + '-01';
    document.getElementById('stmt_to').value   = y + '-' + m + '-' + String(last).padStart(2, '0');
    openModal('statementModal');
}
function fetchStatement() {
    var cardId = activeMoreCardId;
    var from   = document.getElementById('stmt_from').value;
    var to     = document.getElementById('stmt_to').value;
    setBtnLoading('stmtBtn', true, 'Fetching\u2026');
    apiPost('ajax/vcard-handler.php', {action: 'card_statement', card_id: cardId, from: from, to: to})
        .then(function(r) {
            setBtnLoading('stmtBtn', false, '<i class="fas fa-download" style="margin-right:8px"></i>Get Statement');
            var res = document.getElementById('stmtResult');
            res.style.display = 'block';
            if (r.status === '1') {
                if (r.url) {
                    res.innerHTML = '<a href="' + escHtml(r.url) + '" target="_blank" style="display:inline-flex;align-items:center;gap:6px;padding:10px 16px;background:rgba(77,20,140,.1);border:1px solid rgba(77,20,140,.2);border-radius:10px;color:#4D148C;font-size:.8rem;font-weight:700;text-decoration:none"><i class="fas fa-external-link"></i>Download Statement</a>';
                } else {
                    res.innerHTML = '<p style="font-size:.75rem;color:var(--text-muted)">' + escHtml(r.msg || 'Statement ready.') + '</p>';
                }
            } else {
                res.innerHTML = '<p style="font-size:.75rem;color:#ef4444">' + escHtml(r.msg || 'Failed to get statement.') + '</p>';
            }
        });
}

// ── Delete card ───────────────────────────────────────────────
function confirmDeleteCard() {
    closeModal('moreMenuModal');
    if (!confirm('\u26a0\ufe0f This will permanently terminate your card. Any remaining balance will be withdrawn first. Continue?')) return;
    apiPost('ajax/vcard-handler.php', {action: 'delete_card', card_id: activeMoreCardId})
        .then(function(r) {
            if (r.status === '1') { toast('Card deleted.', '#4D148C'); setTimeout(function(){ location.reload(); }, 1500); }
            else toast(r.msg || 'Failed to delete card', '#ef4444');
        });
}

// ── Create card ───────────────────────────────────────────────
function updateCreatePreview() {
    var amt       = parseFloat(document.getElementById('cc_amount').value) || 0;
    var total_ngn = (amt * FUND_RATE) + CREATION_FEE;
    var el        = document.getElementById('cc_ngn_preview');
    el.textContent = amt > 0
        ? '\u2248 \u20a6' + total_ngn.toLocaleString('en-NG', {minimumFractionDigits: 2})
          + ' will be deducted from your wallet'
          + (CREATION_FEE > 0 ? ' (incl. \u20a6' + CREATION_FEE.toFixed(2) + ' creation fee)' : '')
        : '';
}

function submitCreateCard() {
    var name        = document.getElementById('cc_name').value.trim();
    var first_name  = document.getElementById('cc_first_name').value.trim();
    var last_name   = document.getElementById('cc_last_name').value.trim();
    var dob         = document.getElementById('cc_dob').value;
    var phone       = document.getElementById('cc_phone').value.trim();
    var id_type     = document.getElementById('cc_id_type').value;
    var id_number   = document.getElementById('cc_id_number').value.trim();
    var line1       = document.getElementById('cc_line1').value.trim();
    var city        = document.getElementById('cc_city').value.trim();
    var state       = document.getElementById('cc_state').value.trim();
    var postal_code = document.getElementById('cc_postal_code').value.trim();
    var country     = document.getElementById('cc_country').value;
    var amount      = parseFloat(document.getElementById('cc_amount').value);

    // Validate all required fields
    if (!name        || name.length < 2)   { toast('Enter a card name',               '#ef4444'); return; }
    if (!first_name)                        { toast('Enter your first name',            '#ef4444'); return; }
    if (!last_name)                         { toast('Enter your last name',             '#ef4444'); return; }
    if (!dob)                               { toast('Enter your date of birth',         '#ef4444'); return; }
    if (!phone)                             { toast('Enter your phone number',          '#ef4444'); return; }
    if (!id_type)                           { toast('Select an ID type',                '#ef4444'); return; }
    if (!id_number)                         { toast('Enter your ID number',             '#ef4444'); return; }
    if (!line1)                             { toast('Enter your address',               '#ef4444'); return; }
    if (!city)                              { toast('Enter your city',                  '#ef4444'); return; }
    if (!state)                             { toast('Enter your state',                 '#ef4444'); return; }
    if (!postal_code)                       { toast('Enter your postal code',           '#ef4444'); return; }
    if (!country)                           { toast('Select your country',              '#ef4444'); return; }
    if (!amount || amount < MIN_FUND)       { toast('Minimum $' + MIN_FUND.toFixed(2), '#ef4444'); return; }

    setBtnLoading('createCardBtn', true, 'Creating Card\u2026');
    apiPost('ajax/vcard-handler.php', {
        action:       'create_card',
        name:         name,
        first_name:   first_name,
        last_name:    last_name,
        dob:          dob,
        phone:        phone,
        id_type:      id_type,
        id_number:    id_number,
        line1:        line1,
        city:         city,
        state:        state,
        postal_code:  postal_code,
        country:      country,
        amount:       amount,
    }).then(function(r) {
        setBtnLoading('createCardBtn', false, '<i class="fas fa-credit-card" style="margin-right:8px"></i>Create My Card');
        if (r.status === '1') {
            toast('Card created successfully!', '#4D148C');
            closeModal('createCardModal');
            setTimeout(function() { location.reload(); }, 1800);
        } else {
            if (r.debug_log) console.error('[StroWallet Debug Log]\n' + r.debug_log);
            if (r.debug_raw) console.error('[StroWallet Raw Response]', r.debug_raw);
            toast(r.msg || 'Failed to create card', '#ef4444');
        }
    });
}

// ── Utilities ─────────────────────────────────────────────────
function apiPost(url, data) {
    var fd = new FormData();
    for (var k in data) {
        if (data.hasOwnProperty(k)) fd.append(k, data[k]);
    }
    return fetch(url, {method: 'POST', body: fd})
        .then(function(r) { return r.json(); })
        .catch(function() { return {status: '0', msg: 'Network error. Please try again.'}; });
}

function setBtnLoading(id, loading, label) {
    var btn = document.getElementById(id);
    if (!btn) return;
    btn.disabled   = loading;
    btn.innerHTML  = loading ? '<i class="fas fa-spinner fa-spin" style="margin-right:8px"></i>' + label : label;
}

function toast(msg, color) {
    color = color || '#4D148C';
    var el = document.createElement('div');
    el.style.cssText = 'position:fixed;top:16px;left:50%;transform:translateX(-50%);z-index:99999;'
        + 'padding:10px 18px;border-radius:12px;font-size:.82rem;font-weight:700;color:white;'
        + 'background:' + color + ';box-shadow:0 4px 18px rgba(0,0,0,.25);'
        + 'white-space:normal;word-break:break-word;'
        + 'width:auto;max-width:calc(100vw - 32px);min-width:0;'
        + 'text-align:center;line-height:1.4;transition:opacity .4s;'
        + 'box-sizing:border-box;';
    el.textContent = msg;
    document.body.appendChild(el);
    setTimeout(function() { el.style.opacity = '0'; }, 2500);
    setTimeout(function() { if (el.parentNode) el.parentNode.removeChild(el); }, 2900);
}

function escHtml(str) {
    var d = document.createElement('div');
    d.appendChild(document.createTextNode(str || ''));
    return d.innerHTML;
}
</script>

<?php include('footer.php'); ?>