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

// Load settings
$cfg = $pdo->query("SELECT * FROM settings WHERE id = 1 LIMIT 1")->fetch(PDO::FETCH_ASSOC);

// Pagination for card orders
$per_page   = 20;
$cur_page   = max(1, (int)(isset($_GET['page']) ? $_GET['page'] : 1));
$offset     = ($cur_page - 1) * $per_page;
$search     = trim(isset($_GET['q']) ? $_GET['q'] : '');
$filter_st  = trim(isset($_GET['status']) ? $_GET['status'] : '');

$where  = array();
$params = array();
if ($search !== '') {
    $where[]         = "(u.full_name LIKE :q OR u.email LIKE :q2 OR vc.card_id LIKE :q3)";
    $params[':q']    = "%{$search}%";
    $params[':q2']   = "%{$search}%";
    $params[':q3']   = "%{$search}%";
}
if ($filter_st !== '') {
    $where[]          = "vc.status = :st";
    $params[':st']    = $filter_st;
}
$sql_where = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

// ── Card queries — executed directly (same pattern as working admin pages) ──
$db_error = '';

$tot_stmt = $pdo->prepare(
    "SELECT COUNT(*) FROM virtual_cards vc
     LEFT JOIN users u ON u.id = vc.user_id
     {$sql_where}"
);
$tot_stmt->execute($params);
$total_rows  = (int)$tot_stmt->fetchColumn();
$total_pages = max(1, ceil($total_rows / $per_page));

$cards_stmt = $pdo->prepare(
    "SELECT vc.*, u.full_name AS user_name, u.email AS user_email
     FROM virtual_cards vc
     LEFT JOIN users u ON u.id = vc.user_id
     {$sql_where}
     ORDER BY vc.id DESC
     LIMIT " . (int)$per_page . " OFFSET " . (int)$offset
);
$cards_stmt->execute($params);
$all_cards = $cards_stmt->fetchAll(PDO::FETCH_ASSOC);

// Stats
$stats = $pdo->query("SELECT
    COUNT(*) as total_cards,
    SUM(CASE WHEN status='active' THEN 1 ELSE 0 END) as active_cards,
    SUM(CASE WHEN status='frozen' THEN 1 ELSE 0 END) as frozen_cards,
    SUM(CASE WHEN status='terminated' THEN 1 ELSE 0 END) as terminated_cards,
    SUM(balance) as total_balance_usd,
    COUNT(DISTINCT user_id) as unique_users
    FROM virtual_cards")->fetch(PDO::FETCH_ASSOC);

if (!$stats) {
    $stats = array('total_cards'=>0,'active_cards'=>0,'frozen_cards'=>0,'terminated_cards'=>0,'total_balance_usd'=>0,'unique_users'=>0);
}

// Txn volume
$txn_stats_row = $pdo->query("SELECT
    SUM(CASE WHEN type='fund' THEN amount_usd ELSE 0 END) as total_funded,
    SUM(CASE WHEN type='spend' THEN amount_usd ELSE 0 END) as total_spent,
    SUM(CASE WHEN type='withdraw' THEN amount_usd ELSE 0 END) as total_withdrawn
    FROM virtual_card_transactions")->fetch(PDO::FETCH_ASSOC);

$txn_stats = $txn_stats_row ? $txn_stats_row : array('total_funded'=>0,'total_spent'=>0,'total_withdrawn'=>0);
?>
<title><?php echo htmlspecialchars($page_title); ?></title>

<div class="container-fluid" id="container-wrapper">
  <div class="d-sm-flex align-items-center justify-content-between mb-4">
    <h1 class="h3 mb-0 text-gray-800">💳 Virtual Cards – StroWallet</h1>
    <ol class="breadcrumb">
      <li class="breadcrumb-item"><a href="dashboard">Home</a></li>
      <li class="breadcrumb-item active">Virtual Cards</li>
    </ol>
  </div>

  <!-- ══════════════════════════════════════════
       STROWALLET API SETTINGS
  ══════════════════════════════════════════ -->
  <div class="card shadow mb-4">
    <div class="card-header py-3 d-flex align-items-center justify-content-between"
         style="background:linear-gradient(135deg,#064e3b,#047857);color:#fff;">
      <h6 class="m-0 font-weight-bold"><i class="fas fa-key mr-2"></i>StroWallet API Settings</h6>
      <button class="btn btn-sm btn-light" type="button" data-toggle="collapse" data-target="#stroSettingsBody">
        <i class="fas fa-chevron-down"></i>
      </button>
    </div>
    <div class="collapse show" id="stroSettingsBody">
      <div class="card-body">
        <form id="stroSettingsForm">
          <div class="row">
            <div class="col-md-6">
              <div class="form-group">
                <label><strong>Public Key</strong></label>
                <input type="text" class="form-control" name="strowallet_public_key"
                  value="<?php echo htmlspecialchars(isset($cfg['strowallet_public_key']) ? $cfg['strowallet_public_key'] : ''); ?>" placeholder="pub_...">
              </div>
            </div>
            <div class="col-md-6">
              <div class="form-group">
                <label><strong>Secret Key</strong></label>
                <div class="input-group">
                  <input type="password" class="form-control" name="strowallet_secret_key" id="stro_secret"
                    value="<?php echo htmlspecialchars(isset($cfg['strowallet_secret_key']) ? $cfg['strowallet_secret_key'] : ''); ?>" placeholder="sec_...">
                  <div class="input-group-append">
                    <button class="btn btn-outline-secondary" type="button" onclick="toggleVis('stro_secret',this)"><i class="fas fa-eye"></i></button>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-md-3">
              <div class="form-group">
                <label><strong>Mode (Sandbox / Live)</strong></label>
                <select class="form-control" name="strowallet_sandbox">
                  <option value="1" <?php echo (isset($cfg['strowallet_sandbox']) ? $cfg['strowallet_sandbox'] : 1) == 1 ? 'selected' : ''; ?>>🧪 Sandbox (Testing)</option>
                  <option value="0" <?php echo (isset($cfg['strowallet_sandbox']) ? $cfg['strowallet_sandbox'] : 1) == 0 ? 'selected' : ''; ?>>🚀 Live (Production)</option>
                </select>
                <small class="text-muted">Use Sandbox while testing. Switch to Live when ready.</small>
              </div>
            </div>
            <div class="col-md-3">
              <div class="form-group">
                <label><strong>Enable Virtual Cards</strong></label>
                <select class="form-control" name="strowallet_enabled">
                  <option value="1" <?php echo !empty($cfg['strowallet_enabled']) ? 'selected' : ''; ?>>✅ Enabled</option>
                  <option value="0" <?php echo empty($cfg['strowallet_enabled']) ? 'selected' : ''; ?>>❌ Disabled</option>
                </select>
              </div>
            </div>
            <div class="col-md-3">
              <div class="form-group">
                <label><strong>Card Creation Fee (₦)</strong></label>
                <div class="input-group">
                  <div class="input-group-prepend"><span class="input-group-text">₦</span></div>
                  <input type="number" step="0.01" min="0" class="form-control" name="vcard_creation_fee"
                    value="<?php echo htmlspecialchars(isset($cfg['vcard_creation_fee']) ? $cfg['vcard_creation_fee'] : '0'); ?>">
                </div>
              </div>
            </div>
            <div class="col-md-3">
              <div class="form-group">
                <label><strong>Funding Rate (₦ per $1)</strong></label>
                <div class="input-group">
                  <div class="input-group-prepend"><span class="input-group-text">₦</span></div>
                  <input type="number" step="0.01" min="1" class="form-control" name="vcard_fund_rate"
                    value="<?php echo htmlspecialchars(isset($cfg['vcard_fund_rate']) ? $cfg['vcard_fund_rate'] : '1600'); ?>">
                </div>
                <small class="text-muted">Rate applied when user FUNDS card</small>
              </div>
            </div>
            <div class="col-md-3">
              <div class="form-group">
                <label><strong>Withdrawal Rate (₦ per $1)</strong></label>
                <div class="input-group">
                  <div class="input-group-prepend"><span class="input-group-text">₦</span></div>
                  <input type="number" step="0.01" min="1" class="form-control" name="vcard_withdraw_rate"
                    value="<?php echo htmlspecialchars(isset($cfg['vcard_withdraw_rate']) ? $cfg['vcard_withdraw_rate'] : '1550'); ?>">
                </div>
                <small class="text-muted">Rate applied when user WITHDRAWS from card</small>
              </div>
            </div>
            <div class="col-md-3">
              <div class="form-group">
                <label><strong>Min. Balance on Card ($)</strong></label>
                <div class="input-group">
                  <div class="input-group-prepend"><span class="input-group-text">$</span></div>
                  <input type="number" step="0.01" min="0" class="form-control" name="vcard_min_balance"
                    value="<?php echo htmlspecialchars(isset($cfg['vcard_min_balance']) ? $cfg['vcard_min_balance'] : '1'); ?>">
                </div>
                <small class="text-muted">Minimum USD that must stay on card during withdrawal</small>
              </div>
            </div>
            <div class="col-md-3">
              <div class="form-group">
                <label><strong>Min. Top-up ($)</strong></label>
                <div class="input-group">
                  <div class="input-group-prepend"><span class="input-group-text">$</span></div>
                  <input type="number" step="0.01" min="0" class="form-control" name="vcard_min_fund"
                    value="<?php echo htmlspecialchars(isset($cfg['vcard_min_fund']) ? $cfg['vcard_min_fund'] : '5'); ?>">
                </div>
              </div>
            </div>
            <div class="col-md-3">
              <div class="form-group">
                <label><strong>Max Cards Per User</strong></label>
                <input type="number" min="1" max="10" class="form-control" name="vcard_max_per_user"
                  value="<?php echo htmlspecialchars(isset($cfg['vcard_max_per_user']) ? $cfg['vcard_max_per_user'] : '3'); ?>">
              </div>
            </div>
          </div>
          <button type="button" class="btn btn-primary" id="saveStroBtn" onclick="saveStroSettings()">
            <i class="fas fa-save mr-1"></i>Save Settings
          </button>
          <button type="button" class="btn btn-outline-secondary ml-2" onclick="testStroConnection()">
            <i class="fas fa-plug mr-1"></i>Test Connection
          </button>
          <span id="stroSaveMsg" class="ml-3"></span>
        </form>
      </div>
    </div>
  </div>

  <!-- ══════════════════════════════════════════
       STATS
  ══════════════════════════════════════════ -->
  <div class="row mb-4">
    <?php foreach ([
        ['fas fa-credit-card','primary',  $stats['total_cards'],                        'Total Cards'],
        ['fas fa-check-circle','success', $stats['active_cards'],                       'Active'],
        ['fas fa-snowflake','warning',    $stats['frozen_cards'],                       'Frozen'],
        ['fas fa-users','info',           $stats['unique_users'],                       'Users with Cards'],
        ['fas fa-dollar-sign','success',  '$'.number_format(isset($stats['total_balance_usd']) ? $stats['total_balance_usd'] : 0,2),'Total Card Balance'],
        ['fas fa-arrow-up','primary',     '$'.number_format(isset($txn_stats['total_funded']) ? $txn_stats['total_funded'] : 0,2),'Total Funded'],
    ] as [$ic,$col,$val,$lbl]): ?>
    <div class="col-xl-2 col-md-4 mb-4">
      <div class="card border-left-<?php echo $col; ?> shadow h-100 py-2">
        <div class="card-body">
          <div class="row no-gutters align-items-center">
            <div class="col mr-2">
              <div class="text-xs font-weight-bold text-<?php echo $col; ?> text-uppercase mb-1"><?php echo $lbl; ?></div>
              <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $val; ?></div>
            </div>
            <div class="col-auto"><i class="<?php echo $ic; ?> fa-2x text-gray-300"></i></div>
          </div>
        </div>
      </div>
    </div>
    <?php endforeach; ?>
  </div>

  <!-- ══════════════════════════════════════════
       CARD TRANSACTIONS TAB
  ══════════════════════════════════════════ -->
  <div class="card shadow mb-4">
    <div class="card-header py-3 d-flex align-items-center justify-content-between"
         style="background:linear-gradient(135deg,#064e3b,#047857);color:#fff;">
      <h6 class="m-0 font-weight-bold"><i class="fas fa-credit-card mr-2"></i>Issued NFC Virtual Cards</h6>
      <span class="badge badge-light"><?php echo number_format($total_rows); ?> cards</span>
    </div>
    <div class="card-body">

      <!-- Search + Filter -->
      <form method="GET" class="mb-3">
        <div class="row">
          <div class="col-md-5">
            <input type="text" name="q" class="form-control" placeholder="Search user name, email, card ID…" value="<?php echo htmlspecialchars($search); ?>">
          </div>
          <div class="col-md-3">
            <select name="status" class="form-control">
              <option value="">All Statuses</option>
              <option value="active"     <?php echo $filter_st==='active'     ?'selected':''; ?>>Active</option>
              <option value="frozen"     <?php echo $filter_st==='frozen'     ?'selected':''; ?>>Frozen</option>
              <option value="terminated" <?php echo $filter_st==='terminated' ?'selected':''; ?>>Terminated</option>
            </select>
          </div>
          <div class="col-md-2">
            <button type="submit" class="btn btn-primary w-100"><i class="fas fa-search mr-1"></i>Search</button>
          </div>
          <?php if ($search || $filter_st): ?>
          <div class="col-md-2">
            <a href="virtual-cards" class="btn btn-secondary w-100">Clear</a>
          </div>
          <?php endif; ?>
        </div>
      </form>

      <div class="table-responsive">
        <table class="table table-bordered table-hover" style="font-size:.82rem">
          <thead class="thead-light">
            <tr>
              <th>#</th>
              <th>User</th>
              <th>Card ID</th>
              <th>Name on Card</th>
              <th>Balance (USD)</th>
              <th>Status</th>
              <th>Created</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
          <?php if (empty($all_cards)): ?>
            <tr><td colspan="8" class="text-center text-muted py-4">No virtual cards found.</td></tr>
          <?php else: ?>
            <?php foreach ($all_cards as $c):
                $status_val = isset($c['status']) ? $c['status'] : '';
                if ($status_val === 'active')          $badge = 'success';
                elseif ($status_val === 'frozen')      $badge = 'warning';
                elseif ($status_val === 'terminated')  $badge = 'danger';
                else                                   $badge = 'secondary';
            ?>
            <tr>
              <td><?php echo $c['id']; ?></td>
              <td>
                <strong><?php echo htmlspecialchars(isset($c['user_name']) ? $c['user_name'] : 'N/A'); ?></strong><br>
                <small class="text-muted"><?php echo htmlspecialchars(isset($c['user_email']) ? $c['user_email'] : ''); ?></small>
              </td>
              <td><code style="font-size:.75rem"><?php echo htmlspecialchars(substr($c['card_id'],0,20)); ?>…</code></td>
              <td><?php echo htmlspecialchars($c['name_on_card']); ?></td>
              <td><strong style="color:#047857">$<?php echo number_format($c['balance'],2); ?></strong></td>
              <td><span class="badge badge-<?php echo $badge; ?>"><?php echo ucfirst($c['status']); ?><?php echo $c['is_frozen'] ? ' ❄' : ''; ?></span></td>
              <td><?php echo date('d M Y', strtotime($c['created_at'])); ?></td>
              <td>
                <button class="btn btn-xs btn-info" onclick="viewCardDetails('<?php echo addslashes($c['card_id']); ?>', <?php echo $c['user_id']; ?>)" title="View Details">
                  <i class="fas fa-eye"></i>
                </button>
                <button class="btn btn-xs btn-<?php echo $c['is_frozen'] ? 'warning' : 'primary'; ?>"
                        onclick="adminFreezeCard('<?php echo addslashes($c['card_id']); ?>', <?php echo $c['is_frozen'] ? 1 : 0; ?>)"
                        title="<?php echo $c['is_frozen'] ? 'Unfreeze' : 'Freeze'; ?>">
                  <i class="fas <?php echo $c['is_frozen'] ? 'fa-sun' : 'fa-snowflake'; ?>"></i>
                </button>
                <button class="btn btn-xs btn-danger" onclick="adminDeleteCard('<?php echo addslashes($c['card_id']); ?>')" title="Delete Card">
                  <i class="fas fa-trash"></i>
                </button>
              </td>
            </tr>
            <?php endforeach; ?>
          <?php endif; ?>
          </tbody>
        </table>
      </div>

      <!-- Pagination -->
      <?php if ($total_pages > 1): ?>
      <nav>
        <ul class="pagination justify-content-center flex-wrap">
          <?php for ($i = 1; $i <= $total_pages; $i++): ?>
          <li class="page-item <?php echo $i === $cur_page ? 'active' : ''; ?>">
            <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, array('page'=>$i))); ?>"><?php echo $i; ?></a>
          </li>
          <?php endfor; ?>
        </ul>
      </nav>
      <?php endif; ?>
    </div>
  </div>

  <!-- ══════════════════════════════════════════
       QUICK LINK TO TRANSACTIONS PAGE
  ══════════════════════════════════════════ -->
  <div class="card shadow mb-4">
    <div class="card-body d-flex align-items-center justify-content-between flex-wrap" style="gap:.75rem;">
      <div class="d-flex align-items-center" style="gap:12px;">
        <div style="width:44px;height:44px;border-radius:10px;background:linear-gradient(135deg,#064e3b,#065f46);display:flex;align-items:center;justify-content:center;flex-shrink:0;">
          <i class="fas fa-list text-white"></i>
        </div>
        <div>
          <h6 class="mb-0 font-weight-bold text-gray-800">Card Transaction History</h6>
          <small class="text-muted">View all platform-level fund, spend, withdraw and fee transactions.</small>
        </div>
      </div>
      <a href="card-transactions" class="btn btn-success">
        <i class="fas fa-arrow-right mr-1"></i>View All Transactions
      </a>
    </div>
  </div>
</div>

<!-- Card Detail Modal -->
<div class="modal fade" id="cardDetailModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header" style="background:linear-gradient(135deg,#064e3b,#047857);color:#fff">
        <h5 class="modal-title"><i class="fas fa-credit-card mr-2"></i>Card Details</h5>
        <button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button>
      </div>
      <div class="modal-body" id="cardDetailBody">
        <div class="text-center py-4"><i class="fas fa-spinner fa-spin fa-2x"></i></div>
      </div>
    </div>
  </div>
</div>

<script>
function saveStroSettings() {
    var btn = document.getElementById('saveStroBtn');
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>Saving\u2026';

    var fd = new FormData(document.getElementById('stroSettingsForm'));
    fd.append('action', 'save_strowallet_settings');

    fetch('ajax/vcard_ajax.php', {method:'POST', body:fd})
        .then(function(r) { return r.json(); })
        .then(function(r) {
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-save mr-1"></i>Save Settings';
            var msg = document.getElementById('stroSaveMsg');
            msg.className = r.status === '1' ? 'text-success font-weight-bold' : 'text-danger font-weight-bold';
            msg.textContent = r.msg;
            setTimeout(function() { msg.textContent = ''; }, 4000);
        });
}

function testStroConnection() {
    var msg = document.getElementById('stroSaveMsg');
    msg.className = 'text-info';
    msg.textContent = 'Testing connection\u2026';

    var fd = new FormData();
    fd.append('action', 'test_strowallet_connection');

    fetch('ajax/vcard_ajax.php', {method:'POST', body:fd})
        .then(function(r) { return r.json(); })
        .then(function(r) {
            msg.className = r.status === '1' ? 'text-success font-weight-bold' : 'text-danger font-weight-bold';
            msg.textContent = r.msg;
        });
}

function viewCardDetails(cardId, userId) {
    $('#cardDetailModal').modal('show');
    document.getElementById('cardDetailBody').innerHTML = '<div class="text-center py-4"><i class="fas fa-spinner fa-spin fa-2x"></i></div>';

    var fd = new FormData();
    fd.append('action', 'admin_view_card');
    fd.append('card_id', cardId);
    fd.append('user_id', userId);

    fetch('ajax/vcard_ajax.php', {method:'POST', body:fd})
        .then(function(r) { return r.json(); })
        .then(function(r) {
            if (r.status === '1') {
                var d = r.card;
                // Card status from NFC API: card_status field
                var statusVal = d.card_status || d.status || 'N/A';
                // Card number — may be in card_number field from NFC
                var cardNum   = d.card_number || d.cardNumber || d.card_pan || 'N/A';
                var cvvVal    = d.cvv || d.cvv2 || 'N/A';
                var expiryVal = d.expiry || d.expiration || 'N/A';
                var balVal    = '$' + parseFloat(d.balance || 0).toFixed(2);
                var nameVal   = d.name_on_card || d.card_name || d.card_holder_name || 'N/A';
                var cardType  = d.card_type || d.card_brand || 'VISA';
                var cardId    = d.card_id || cardId;
                var createdAt = d.card_created_date || d.created_at || '';

                document.getElementById('cardDetailBody').innerHTML =
                    '<div class="row">'
                    + '<div class="col-md-6">'
                    + '<h6 class="font-weight-bold text-success mb-2"><i class="fas fa-credit-card mr-1"></i>Card Information</h6>'
                    + '<table class="table table-sm table-bordered">'
                    + '<tr><th width="45%">Card Number</th><td><code>' + cardNum + '</code></td></tr>'
                    + '<tr><th>CVV</th><td><code>' + cvvVal + '</code></td></tr>'
                    + '<tr><th>Expiry</th><td>' + expiryVal + '</td></tr>'
                    + '<tr><th>Balance</th><td><strong class="text-success">' + balVal + '</strong></td></tr>'
                    + '<tr><th>Status</th><td><span class="badge badge-' + (statusVal.toLowerCase()==='active'?'success':(statusVal.toLowerCase()==='frozen'?'warning':'secondary')) + '">' + statusVal + '</span></td></tr>'
                    + '<tr><th>Name on Card</th><td>' + nameVal + '</td></tr>'
                    + '<tr><th>Card Type</th><td>' + cardType.toUpperCase() + '</td></tr>'
                    + '</table></div>'
                    + '<div class="col-md-6">'
                    + '<h6 class="font-weight-bold text-success mb-2"><i class="fas fa-map-marker-alt mr-1"></i>Billing Address</h6>'
                    + '<table class="table table-sm table-bordered">'
                    + '<tr><th width="45%">Address</th><td>3401 N. Miami, Ave. Ste 230</td></tr>'
                    + '<tr><th>City</th><td>Miami</td></tr>'
                    + '<tr><th>State</th><td>Florida</td></tr>'
                    + '<tr><th>Postal Code</th><td>33127</td></tr>'
                    + '<tr><th>Country</th><td>United States</td></tr>'
                    + '</table>'
                    + '<h6 class="font-weight-bold text-success mb-2 mt-3"><i class="fas fa-info-circle mr-1"></i>Card Reference</h6>'
                    + '<table class="table table-sm table-bordered">'
                    + '<tr><th width="45%">Card ID</th><td><small><code>' + (d.card_id||cardId) + '</code></small></td></tr>'
                    + (d.reference ? '<tr><th>Reference</th><td><small>' + d.reference + '</small></td></tr>' : '')
                    + (createdAt ? '<tr><th>Created</th><td>' + createdAt + '</td></tr>' : '')
                    + '</table>'
                    + '</div></div>';
            } else {
                document.getElementById('cardDetailBody').innerHTML = '<div class="alert alert-danger">' + r.msg + '</div>';
            }
        });
}

function adminFreezeCard(cardId, isFrozen) {
    var action = isFrozen ? 'unfreeze' : 'freeze';
    if (!confirm((isFrozen ? 'Unfreeze' : 'Freeze') + ' this card?')) return;

    var fd = new FormData();
    fd.append('action', 'admin_freeze_card');
    fd.append('card_id', cardId);
    fd.append('freeze_action', action);

    fetch('ajax/vcard_ajax.php', {method:'POST', body:fd})
        .then(function(r) { return r.json(); })
        .then(function(r) {
            alert(r.msg);
            if (r.status === '1') location.reload();
        });
}

function adminDeleteCard(cardId) {
    if (!confirm('\u26a0\ufe0f Terminate this card permanently? This cannot be undone.')) return;
    var fd = new FormData();
    fd.append('action', 'admin_delete_card');
    fd.append('card_id', cardId);

    fetch('ajax/vcard_ajax.php', {method:'POST', body:fd})
        .then(function(r) { return r.json(); })
        .then(function(r) {
            alert(r.msg);
            if (r.status === '1') location.reload();
        });
}

function toggleVis(id, btn) {
    var el = document.getElementById(id);
    el.type = el.type === 'password' ? 'text' : 'password';
    btn.querySelector('i').className = el.type === 'password' ? 'fas fa-eye' : 'fas fa-eye-slash';
}
</script>

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