<?php
session_start();
require_once 'config/database.php';

// Check if admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit();
}

$database = new Database();
$conn = $database->getConnection();

// Get admin info
$admin_id = $_SESSION['admin_id'];
$stmt = $conn->prepare("SELECT * FROM admins WHERE id = ?");
$stmt->execute([$admin_id]);
$current_admin = $stmt->fetch();

// Handle form submissions
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'create':
                $user_id = $_POST['user_id'];
                $card_type = $_POST['card_type'];
                $daily_limit = $_POST['daily_limit'];
                
                // Validate inputs
                if (empty($user_id) || empty($card_type) || empty($daily_limit)) {
                    $message = 'All fields are required.';
                    $message_type = 'error';
                } else {
                    // Check if user exists
                    $stmt = $conn->prepare("SELECT id FROM users WHERE id = ?");
                    $stmt->execute([$user_id]);
                    if (!$stmt->fetch()) {
                        $message = 'User not found.';
                        $message_type = 'error';
                    } else {
                        // Generate card details
                        $card_number = generateCardNumber($card_type);
                        $expiry_date = date('Y-m-d', strtotime('+3 years'));
                        $cvv = generateCVV();
                        
                        // Check if card number already exists
                        $stmt = $conn->prepare("SELECT id FROM virtual_cards WHERE card_number = ?");
                        $stmt->execute([$card_number]);
                        if ($stmt->fetch()) {
                            $message = 'Generated card number already exists. Please try again.';
                            $message_type = 'error';
                        } else {
                            // Create new virtual card
                            $stmt = $conn->prepare("INSERT INTO virtual_cards (user_id, card_number, card_type, expiry_date, cvv, daily_limit) VALUES (?, ?, ?, ?, ?, ?)");
                            if ($stmt->execute([$user_id, $card_number, $expiry_date, $card_type, $cvv, $daily_limit])) {
                                $message = 'Virtual card created successfully!';
                                $message_type = 'success';
                            } else {
                                $message = 'Failed to create virtual card.';
                                $message_type = 'error';
                            }
                        }
                    }
                }
                break;
                
            case 'update_status':
                $card_id = $_POST['card_id'];
                $new_status = $_POST['status'];
                $daily_limit = $_POST['daily_limit'] ?? null;
                
                $stmt = $conn->prepare("UPDATE virtual_cards SET status = ?, daily_limit = ? WHERE id = ?");
                if ($stmt->execute([$new_status, $daily_limit, $card_id])) {
                    $message = 'Virtual card updated successfully.';
                    $message_type = 'success';
                } else {
                    $message = 'Failed to update virtual card.';
                    $message_type = 'error';
                }
                break;
                
            case 'delete':
                $card_id = $_POST['card_id'];
                
                $stmt = $conn->prepare("DELETE FROM virtual_cards WHERE id = ?");
                if ($stmt->execute([$card_id])) {
                    $message = 'Virtual card deleted successfully.';
                    $message_type = 'success';
                } else {
                    $message = 'Failed to delete virtual card.';
                    $message_type = 'error';
                }
                break;
        }
    }
}

// Helper functions
function generateCardNumber($cardType) {
    $prefixes = [
        'Visa' => ['4'],
        'Mastercard' => ['51', '52', '53', '54', '55'],
        'American Express' => ['34', '37']
    ];
    
    $prefix = $prefixes[$cardType][array_rand($prefixes[$cardType])];
    $length = ($cardType === 'American Express') ? 15 : 16;
    
    $number = $prefix;
    $remainingLength = $length - strlen($prefix) - 1;
    
    for ($i = 0; $i < $remainingLength; $i++) {
        $number .= mt_rand(0, 9);
    }
    
    // Add check digit (simplified Luhn algorithm)
    $number .= calculateCheckDigit($number);
    
    return $number;
}

function calculateCheckDigit($number) {
    $sum = 0;
    $alternate = false;
    
    for ($i = strlen($number) - 1; $i >= 0; $i--) {
        $digit = intval($number[$i]);
        
        if ($alternate) {
            $digit *= 2;
            if ($digit > 9) {
                $digit = ($digit % 10) + 1;
            }
        }
        
        $sum += $digit;
        $alternate = !$alternate;
    }
    
    return (10 - ($sum % 10)) % 10;
}

function generateCVV() {
    return sprintf('%03d', mt_rand(0, 999));
}

// Get filter parameters
$status_filter = $_GET['status'] ?? '';
$type_filter = $_GET['type'] ?? '';
$search = $_GET['search'] ?? '';

// Build query
$where_conditions = [];
$params = [];

if (!empty($status_filter)) {
    $where_conditions[] = "vc.status = ?";
    $params[] = $status_filter;
}

if (!empty($type_filter)) {
    $where_conditions[] = "vc.card_type = ?";
    $params[] = $type_filter;
}

if (!empty($search)) {
    $where_conditions[] = "(u.firstname LIKE ? OR u.lastname LIKE ? OR u.email LIKE ? OR vc.card_number LIKE ?)";
    $search_param = "%$search%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
}

$where_clause = '';
if (!empty($where_conditions)) {
    $where_clause = 'WHERE ' . implode(' AND ', $where_conditions);
}

// Get virtual cards with user information
$query = "SELECT vc.*, u.firstname, u.lastname, u.email, u.account_number 
          FROM virtual_cards vc 
          LEFT JOIN users u ON vc.user_id = u.id 
          $where_clause
          ORDER BY vc.created_at DESC";

$stmt = $conn->prepare($query);
$stmt->execute($params);
$cards = $stmt->fetchAll();

// Get statistics
$stats_query = "SELECT 
    COUNT(*) as total_cards,
    SUM(CASE WHEN status = 'Active' THEN 1 ELSE 0 END) as active_cards,
    SUM(CASE WHEN status = 'Inactive' THEN 1 ELSE 0 END) as inactive_cards,
    SUM(CASE WHEN status = 'Blocked' THEN 1 ELSE 0 END) as blocked_cards,
    SUM(CASE WHEN card_type = 'Visa' THEN 1 ELSE 0 END) as visa_cards,
    SUM(CASE WHEN card_type = 'Mastercard' THEN 1 ELSE 0 END) as mastercard_cards,
    SUM(CASE WHEN card_type = 'American Express' THEN 1 ELSE 0 END) as amex_cards,
    SUM(daily_limit) as total_daily_limits
    FROM virtual_cards";

$stats_stmt = $conn->query($stats_query);
$stats = $stats_stmt->fetch();

// Get all users for the create form
$users_stmt = $conn->query("SELECT id, firstname, lastname, email FROM users ORDER BY firstname, lastname");
$users = $users_stmt->fetchAll();

$database->closeConnection();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TrustBeam Credit - Virtual Cards</title>
    <link rel="stylesheet" href="assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }
        
        .modal-content {
            background-color: #fff;
            margin: 2% auto;
            padding: 20px;
            border-radius: 8px;
            width: 90%;
            max-width: 600px;
            position: relative;
            max-height: 90vh;
            overflow-y: auto;
        }
        
        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }
        
        .close:hover {
            color: #000;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
        }
        
        .form-group input,
        .form-group select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        
        .btn-group {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 20px;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
            text-align: center;
        }
        
        .btn-primary {
            background-color: #007bff;
            color: white;
        }
        
        .btn-secondary {
            background-color: #6c757d;
            color: white;
        }
        
        .btn-success {
            background-color: #28a745;
            color: white;
        }
        
        .btn-warning {
            background-color: #ffc107;
            color: #212529;
        }
        
        .btn-danger {
            background-color: #dc3545;
            color: white;
        }
        
        .btn-info {
            background-color: #17a2b8;
            color: white;
        }
        
        .btn-sm {
            padding: 5px 10px;
            font-size: 12px;
        }
        
        .alert {
            padding: 10px;
            margin-bottom: 20px;
            border-radius: 4px;
        }
        
        .alert-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .alert-error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .stat-icon {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            color: white;
        }
        
        .stat-icon.active { background: linear-gradient(135deg, #28a745, #20c997); }
        .stat-icon.inactive { background: linear-gradient(135deg, #6c757d, #495057); }
        .stat-icon.blocked { background: linear-gradient(135deg, #dc3545, #fd7e14); }
        .stat-icon.total { background: linear-gradient(135deg, #17a2b8, #20c997); }
        .stat-icon.visa { background: linear-gradient(135deg, #1a1f71, #0066cc); }
        .stat-icon.mastercard { background: linear-gradient(135deg, #eb001b, #f79e1b); }
        .stat-icon.amex { background: linear-gradient(135deg, #006fcf, #006fcf); }
        
        .stat-content h3 {
            margin: 0;
            font-size: 24px;
            color: #333;
        }
        
        .stat-content p {
            margin: 5px 0 0 0;
            color: #666;
            font-size: 14px;
        }
        
        .table-container {
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .table-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
        }
        
        .table-header h3 {
            margin: 0;
            font-size: 24px;
        }
        
        .table-header p {
            margin: 5px 0 0 0;
            opacity: 0.9;
        }
        
        .filters {
            padding: 20px;
            border-bottom: 1px solid #eee;
            background: #f8f9fa;
        }
        
        .filters form {
            display: flex;
            gap: 15px;
            align-items: end;
            flex-wrap: wrap;
        }
        
        .filter-group {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }
        
        .filter-group label {
            font-size: 12px;
            font-weight: 600;
            color: #666;
        }
        
        .filter-group input,
        .filter-group select {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }
        
        th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #495057;
        }
        
        tr:hover {
            background-color: #f8f9fa;
        }
        
        .status-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }
        
        .status-active {
            background-color: #d4edda;
            color: #155724;
        }
        
        .status-inactive {
            background-color: #f8d7da;
            color: #721c24;
        }
        
        .status-blocked {
            background-color: #fff3cd;
            color: #856404;
        }
        
        .type-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }
        
        .type-visa {
            background-color: #1a1f71;
            color: white;
        }
        
        .type-mastercard {
            background-color: #eb001b;
            color: white;
        }
        
        .type-amex {
            background-color: #006fcf;
            color: white;
        }
        
        .action-buttons {
            display: flex;
            gap: 5px;
        }
        
        .card-number {
            font-family: 'Courier New', monospace;
            font-weight: 600;
            color: #333;
            letter-spacing: 1px;
        }
        
        .user-info {
            display: flex;
            flex-direction: column;
        }
        
        .user-name {
            font-weight: 600;
            color: #333;
        }
        
        .user-email {
            font-size: 12px;
            color: #666;
        }
        
        .limit {
            font-weight: 600;
            color: #28a745;
        }
        
        .expiry {
            font-size: 12px;
            color: #666;
        }
        
        @media (max-width: 768px) {
            .filters form {
                flex-direction: column;
                align-items: stretch;
            }
            
            .filter-group {
                width: 100%;
            }
            
            .stats-grid {
                grid-template-columns: 1fr;
            }
            
            .action-buttons {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div class="admin-container">
        <!-- Header -->
        <header class="admin-header">
            <div class="header-left">
                <h1 class="logo">TrustBeam Credit</h1>
                <button class="menu-toggle" id="menuToggle">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="search-bar">
                    <i class="fas fa-search"></i>
                    <input type="text" placeholder="Search...">
                </div>
            </div>
            <div class="header-right">
                <div class="admin-profile">
                    <span>Welcome, <?php echo htmlspecialchars($current_admin['username']); ?></span>
                    <div class="profile-dropdown">
                        <i class="fas fa-user"></i>
                        <div class="dropdown-content">
                            <a href="profile.php">Profile</a>
                            <a href="logout.php">Logout</a>
                        </div>
                    </div>
                </div>
            </div>
        </header>

        <!-- Sidebar -->
        <aside class="admin-sidebar" id="sidebar">
            <div class="sidebar-header">
                <h3>Admin Manager</h3>
                <p>Admin</p>
            </div>
            <nav class="sidebar-nav">
                <ul>
                    <li>
                        <a href="index.php">
                            <i class="fas fa-home"></i>
                            <span>Dashboard</span>
                        </a>
                    </li>
                    <li>
                        <a href="users.php">
                            <i class="fas fa-users"></i>
                            <span>Manage Users</span>
                        </a>
                    </li>
                    <li>
                        <a href="create-user.php">
                            <i class="fas fa-user-plus"></i>
                            <span>Create New User</span>
                        </a>
                    </li>
                    <li>
                        <a href="applications.php">
                            <i class="fas fa-user-friends"></i>
                            <span>New User Application(s)</span>
                        </a>
                    </li>
                    <li>
                        <a href="transactions.php">
                            <i class="fas fa-exchange-alt"></i>
                            <span>Transfer Transactions</span>
                        </a>
                    </li>
                    <li>
                        <a href="deposits.php">
                            <i class="fas fa-arrow-down"></i>
                            <span>Users Deposits</span>
                        </a>
                    </li>
                    <li class="has-submenu">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-cog"></i>
                            <span>Loan Applications</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="loans.php">View All</a></li>
                            <li><a href="loans.php?status=pending">Pending</a></li>
                            <li><a href="loans.php?status=approved">Approved</a></li>
                        </ul>
                    </li>
                    <li class="has-submenu active">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-credit-card"></i>
                            <span>Virtual Cards</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="cards.php" class="active">Manage Cards</a></li>
                            <li><a href="cards.php?status=active">Active</a></li>
                        </ul>
                    </li>
                    <li class="has-submenu">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-file-invoice-dollar"></i>
                            <span>IRS Refunds</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="refunds.php">View All</a></li>
                            <li><a href="refunds.php?status=pending">Pending</a></li>
                        </ul>
                    </li>
                    <li>
                        <a href="email.php">
                            <i class="fas fa-envelope"></i>
                            <span>Email Services</span>
                        </a>
                    </li>
                    <li class="has-submenu">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-user-shield"></i>
                            <span>Administrator(s)</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="admins.php">View All</a></li>
                            <li><a href="create-admin.php">Add New</a></li>
                        </ul>
                    </li>
                    <li class="has-submenu">
                        <a href="#" class="submenu-toggle">
                            <i class="fas fa-cog"></i>
                            <span>Settings</span>
                            <i class="fas fa-chevron-down"></i>
                        </a>
                        <ul class="submenu">
                            <li><a href="settings.php">General</a></li>
                            <li><a href="security.php">Security</a></li>
                        </ul>
                    </li>
                </ul>
            </nav>
        </aside>

        <!-- Main Content -->
        <main class="admin-main">
            <div class="dashboard-header">
                <h2>Virtual Cards Management</h2>
                <p>Manage virtual cards for users</p>
            </div>

            <!-- Messages -->
            <?php if ($message): ?>
                <div class="alert alert-<?php echo $message_type; ?>">
                    <?php echo htmlspecialchars($message); ?>
                </div>
            <?php endif; ?>

            <!-- Statistics Cards -->
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-icon total">
                        <i class="fas fa-credit-card"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($stats['total_cards']); ?></h3>
                        <p>Total Cards</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon active">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($stats['active_cards']); ?></h3>
                        <p>Active</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon inactive">
                        <i class="fas fa-pause-circle"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($stats['inactive_cards']); ?></h3>
                        <p>Inactive</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon blocked">
                        <i class="fas fa-ban"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($stats['blocked_cards']); ?></h3>
                        <p>Blocked</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon visa">
                        <i class="fab fa-cc-visa"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($stats['visa_cards']); ?></h3>
                        <p>Visa Cards</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon mastercard">
                        <i class="fab fa-cc-mastercard"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($stats['mastercard_cards']); ?></h3>
                        <p>Mastercard</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon amex">
                        <i class="fab fa-cc-amex"></i>
                    </div>
                    <div class="stat-content">
                        <h3><?php echo number_format($stats['amex_cards']); ?></h3>
                        <p>American Express</p>
                    </div>
                </div>
            </div>

            <!-- Virtual Cards Table -->
            <div class="table-container">
                <div class="table-header">
                    <h3><i class="fas fa-credit-card"></i> Virtual Cards</h3>
                    <p>Manage virtual cards for users</p>
                </div>
                
                <div class="filters">
                    <form method="GET" action="">
                        <div class="filter-group">
                            <label>Search</label>
                            <input type="text" name="search" placeholder="Search by name, email, or card number..." value="<?php echo htmlspecialchars($search); ?>">
                        </div>
                        <div class="filter-group">
                            <label>Status</label>
                            <select name="status">
                                <option value="">All Status</option>
                                <option value="Active" <?php echo $status_filter === 'Active' ? 'selected' : ''; ?>>Active</option>
                                <option value="Inactive" <?php echo $status_filter === 'Inactive' ? 'selected' : ''; ?>>Inactive</option>
                                <option value="Blocked" <?php echo $status_filter === 'Blocked' ? 'selected' : ''; ?>>Blocked</option>
                            </select>
                        </div>
                        <div class="filter-group">
                            <label>Card Type</label>
                            <select name="type">
                                <option value="">All Types</option>
                                <option value="Visa" <?php echo $type_filter === 'Visa' ? 'selected' : ''; ?>>Visa</option>
                                <option value="Mastercard" <?php echo $type_filter === 'Mastercard' ? 'selected' : ''; ?>>Mastercard</option>
                                <option value="American Express" <?php echo $type_filter === 'American Express' ? 'selected' : ''; ?>>American Express</option>
                            </select>
                        </div>
                        <div class="filter-group">
                            <label>&nbsp;</label>
                            <button type="submit" class="btn btn-primary">Filter</button>
                        </div>
                        <div class="filter-group">
                            <label>&nbsp;</label>
                            <a href="cards.php" class="btn btn-secondary">Clear</a>
                        </div>
                    </form>
                </div>

                <div style="padding: 20px; border-bottom: 1px solid #eee;">
                    <button class="btn btn-success" onclick="openCreateModal()">
                        <i class="fas fa-plus"></i> Create New Virtual Card
                    </button>
                </div>

                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Card Holder</th>
                            <th>Card Details</th>
                            <th>Type</th>
                            <th>Status</th>
                            <th>Daily Limit</th>
                            <th>Expiry Date</th>
                            <th>Created</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($cards)): ?>
                            <tr>
                                <td colspan="9" style="text-align: center; padding: 40px;">
                                    <i class="fas fa-credit-card" style="font-size: 48px; color: #ccc; margin-bottom: 15px;"></i>
                                    <p style="color: #666;">No virtual cards found.</p>
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($cards as $card): ?>
                                <tr>
                                    <td><?php echo $card['id']; ?></td>
                                    <td>
                                        <div class="user-info">
                                            <div class="user-name"><?php echo htmlspecialchars($card['firstname'] . ' ' . $card['lastname']); ?></div>
                                            <div class="user-email"><?php echo htmlspecialchars($card['email']); ?></div>
                                            <div style="font-size: 11px; color: #999;"><?php echo htmlspecialchars($card['account_number']); ?></div>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="card-number"><?php echo chunk_split($card['card_number'], 4, ' '); ?></div>
                                        <div style="font-size: 11px; color: #666;">CVV: <?php echo $card['cvv']; ?></div>
                                    </td>
                                    <td>
                                        <span class="type-badge type-<?php echo strtolower(str_replace(' ', '-', $card['card_type'])); ?>">
                                            <?php echo htmlspecialchars($card['card_type']); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="status-badge status-<?php echo strtolower($card['status']); ?>">
                                            <?php echo htmlspecialchars($card['status']); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <div class="limit">$<?php echo number_format($card['daily_limit'], 2); ?></div>
                                    </td>
                                    <td>
                                        <div class="expiry"><?php echo date('M Y', strtotime($card['expiry_date'])); ?></div>
                                        <div style="font-size: 10px; color: #999;"><?php echo $card['expiry_date']; ?></div>
                                    </td>
                                    <td><?php echo date('M j, Y', strtotime($card['created_at'])); ?></td>
                                    <td>
                                        <div class="action-buttons">
                                            <button class="btn btn-info btn-sm" onclick="viewCardDetails(<?php echo $card['id']; ?>)" title="View Details">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                            <button class="btn btn-warning btn-sm" onclick="openUpdateModal(<?php echo $card['id']; ?>, '<?php echo $card['status']; ?>', <?php echo $card['daily_limit']; ?>)" title="Update Card">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button class="btn btn-danger btn-sm" onclick="deleteCard(<?php echo $card['id']; ?>)" title="Delete Card">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </main>
    </div>

    <!-- Create Virtual Card Modal -->
    <div id="createModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeCreateModal()">&times;</span>
            <h3>Create New Virtual Card</h3>
            <form method="POST" action="">
                <input type="hidden" name="action" value="create">
                
                <div class="form-group">
                    <label for="user_id">Select User:</label>
                    <select id="user_id" name="user_id" required>
                        <option value="">Select User</option>
                        <?php foreach ($users as $user): ?>
                            <option value="<?php echo $user['id']; ?>">
                                <?php echo htmlspecialchars($user['firstname'] . ' ' . $user['lastname'] . ' (' . $user['email'] . ')'); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="card_type">Card Type:</label>
                    <select id="card_type" name="card_type" required>
                        <option value="">Select Card Type</option>
                        <option value="Visa">Visa</option>
                        <option value="Mastercard">Mastercard</option>
                        <option value="American Express">American Express</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="daily_limit">Daily Limit ($):</label>
                    <input type="number" id="daily_limit" name="daily_limit" step="0.01" min="0" max="100000" value="1000" required>
                </div>
                
                <div class="btn-group">
                    <button type="button" class="btn btn-secondary" onclick="closeCreateModal()">Cancel</button>
                    <button type="submit" class="btn btn-primary">Create Card</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Update Virtual Card Modal -->
    <div id="updateModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeUpdateModal()">&times;</span>
            <h3>Update Virtual Card</h3>
            <form method="POST" action="">
                <input type="hidden" name="action" value="update_status">
                <input type="hidden" id="cardId" name="card_id">
                
                <div class="form-group">
                    <label for="status">Status:</label>
                    <select id="status" name="status" required>
                        <option value="Active">Active</option>
                        <option value="Inactive">Inactive</option>
                        <option value="Blocked">Blocked</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="daily_limit">Daily Limit ($):</label>
                    <input type="number" id="daily_limit" name="daily_limit" step="0.01" min="0" max="100000" required>
                </div>
                
                <div class="btn-group">
                    <button type="button" class="btn btn-secondary" onclick="closeUpdateModal()">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Card</button>
                </div>
            </form>
        </div>
    </div>

    <!-- View Details Modal -->
    <div id="detailsModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeDetailsModal()">&times;</span>
            <h3>Virtual Card Details</h3>
            <div id="cardDetails">
                <!-- Details will be loaded here -->
            </div>
        </div>
    </div>

    <script src="assets/js/admin.js"></script>
    <script>
        function openCreateModal() {
            document.getElementById('createModal').style.display = 'block';
        }

        function closeCreateModal() {
            document.getElementById('createModal').style.display = 'none';
            document.querySelector('#createModal form').reset();
        }

        function openUpdateModal(cardId, status, dailyLimit) {
            document.getElementById('cardId').value = cardId;
            document.getElementById('status').value = status;
            document.getElementById('daily_limit').value = dailyLimit;
            document.getElementById('updateModal').style.display = 'block';
        }

        function closeUpdateModal() {
            document.getElementById('updateModal').style.display = 'none';
            document.querySelector('#updateModal form').reset();
        }

        function viewCardDetails(cardId) {
            // This would typically load card details via AJAX
            // For now, we'll show a simple message
            document.getElementById('cardDetails').innerHTML = `
                <p>Loading virtual card details for ID: ${cardId}</p>
                <p><em>This feature would load detailed information about the virtual card including:</em></p>
                <ul>
                    <li>Complete card information</li>
                    <li>Transaction history</li>
                    <li>Usage statistics</li>
                    <li>Security settings</li>
                    <li>Recent activity</li>
                </ul>
            `;
            document.getElementById('detailsModal').style.display = 'block';
        }

        function closeDetailsModal() {
            document.getElementById('detailsModal').style.display = 'none';
        }

        function deleteCard(cardId) {
            if (confirm('Are you sure you want to delete this virtual card? This action cannot be undone.')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="card_id" value="${cardId}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }

        // Close modals when clicking outside
        window.onclick = function(event) {
            const createModal = document.getElementById('createModal');
            const updateModal = document.getElementById('updateModal');
            const detailsModal = document.getElementById('detailsModal');
            
            if (event.target === createModal) {
                closeCreateModal();
            }
            if (event.target === updateModal) {
                closeUpdateModal();
            }
            if (event.target === detailsModal) {
                closeDetailsModal();
            }
        }
    </script>
</body>
</html>

