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

$page = 'cards';
$database = new Database();
$db = $database->getConnection();

// Get cards with user information
$stmt = $db->prepare("
    SELECT c.*, u.first_name, u.last_name, u.email, u.account_number 
    FROM cards c
    JOIN users u ON c.user_id = u.id
    ORDER BY c.created_at DESC
");
$stmt->execute();
$cards = $stmt->fetchAll(PDO::FETCH_ASSOC);

include 'includes/header.php';
?>

<div class="content-wrapper">
    <div class="container-fluid">
        <!-- Page Header -->
        <div class="page-header">
            <div class="row align-items-center">
                <div class="col">
                    <h1 class="page-header-title text-primary">
                        <i class="fas fa-credit-card mr-2"></i> Card Management
                    </h1>
                    <p class="text-muted">Manage customer cards, issue new cards, and control card status</p>
                </div>
                <div class="col-auto">
                    <button type="button" class="btn btn-primary btn-lg shadow-sm" data-toggle="modal" data-target="#createCardModal">
                        <i class="fas fa-plus fa-sm text-white-50 mr-1"></i> Issue New Card
                    </button>
                </div>
            </div>
        </div>

        <!-- Card Statistics -->
        <div class="row mb-4">
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card border-left-primary shadow h-100 py-2 dashboard-card">
                    <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-primary text-uppercase mb-1">Total Cards</div>
                                <div class="h3 mb-0 font-weight-bold text-gray-800 counter-value"><?php echo count($cards); ?></div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-credit-card fa-2x text-primary-light"></i>
                            </div>
                        </div>
                        <div class="mt-3">
                            <div class="progress" style="height: 5px;">
                                <div class="progress-bar bg-primary" role="progressbar" style="width: 100%;" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card border-left-success shadow h-100 py-2 dashboard-card">
                    <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-success text-uppercase mb-1">Active Cards</div>
                                <div class="h3 mb-0 font-weight-bold text-gray-800 counter-value">
                                    <?php 
                                    $activeCards = array_filter($cards, function($card) {
                                        return $card['status'] == 'active';
                                    });
                                    echo count($activeCards);
                                    ?>
                                </div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-check-circle fa-2x text-success-light"></i>
                            </div>
                        </div>
                        <div class="mt-3">
                            <div class="progress" style="height: 5px;">
                                <div class="progress-bar bg-success" role="progressbar" 
                                    style="width: <?php echo count($cards) > 0 ? (count($activeCards) / count($cards) * 100) : 0; ?>%;" 
                                    aria-valuenow="<?php echo count($cards) > 0 ? (count($activeCards) / count($cards) * 100) : 0; ?>" 
                                    aria-valuemin="0" 
                                    aria-valuemax="100"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card border-left-warning shadow h-100 py-2 dashboard-card">
                    <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-warning text-uppercase mb-1">Frozen Cards</div>
                                <div class="h3 mb-0 font-weight-bold text-gray-800 counter-value">
                                    <?php 
                                    $frozenCards = array_filter($cards, function($card) {
                                        return $card['status'] == 'frozen';
                                    });
                                    echo count($frozenCards);
                                    ?>
                                </div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-lock fa-2x text-warning-light"></i>
                            </div>
                        </div>
                        <div class="mt-3">
                            <div class="progress" style="height: 5px;">
                                <div class="progress-bar bg-warning" role="progressbar" 
                                    style="width: <?php echo count($cards) > 0 ? (count($frozenCards) / count($cards) * 100) : 0; ?>%;" 
                                    aria-valuenow="<?php echo count($cards) > 0 ? (count($frozenCards) / count($cards) * 100) : 0; ?>" 
                                    aria-valuemin="0" 
                                    aria-valuemax="100"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card border-left-info shadow h-100 py-2 dashboard-card">
                    <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-info text-uppercase mb-1">Card Types</div>
                                <div class="h3 mb-0 font-weight-bold text-gray-800 counter-value">
                                    <?php 
                                    $cardTypes = array_unique(array_column($cards, 'card_type'));
                                    echo count($cardTypes);
                                    ?>
                                </div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-list fa-2x text-info-light"></i>
                            </div>
                        </div>
                        <div class="mt-3">
                            <div class="progress" style="height: 5px;">
                                <div class="progress-bar bg-info" role="progressbar" style="width: 100%;" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Card Distribution Chart -->
        <div class="row mb-4">
            <div class="col-xl-8 col-lg-7">
                <div class="card shadow mb-4">
                    <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                        <h6 class="m-0 font-weight-bold text-primary">Card Distribution by Type</h6>
                    </div>
                    <div class="card-body">
                        <div class="chart-area">
                            <canvas id="cardDistributionChart" height="300"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xl-4 col-lg-5">
                <div class="card shadow mb-4">
                    <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                        <h6 class="m-0 font-weight-bold text-primary">Card Status Distribution</h6>
                    </div>
                    <div class="card-body">
                        <div class="chart-pie pt-4 pb-2">
                            <canvas id="cardStatusChart"></canvas>
                        </div>
                        <div class="mt-4 text-center small">
                            <span class="mr-2">
                                <i class="fas fa-circle text-success"></i> Active
                            </span>
                            <span class="mr-2">
                                <i class="fas fa-circle text-warning"></i> Frozen
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Cards Table -->
        <div class="card shadow mb-4">
            <div class="card-header py-3 d-flex justify-content-between align-items-center">
                <h6 class="m-0 font-weight-bold text-primary">All Customer Cards</h6>
                <div class="btn-group">
                    <button type="button" class="btn btn-outline-primary btn-sm dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        <i class="fas fa-filter fa-sm"></i> Filter
                    </button>
                    <div class="dropdown-menu dropdown-menu-right">
                        <a class="dropdown-item filter-status" href="#" data-status="all">All Cards</a>
                        <a class="dropdown-item filter-status" href="#" data-status="active">Active Cards</a>
                        <a class="dropdown-item filter-status" href="#" data-status="frozen">Frozen Cards</a>
                        <div class="dropdown-divider"></div>
                        <a class="dropdown-item filter-type" href="#" data-type="all">All Types</a>
                        <?php 
                        foreach ($cardTypes as $type) {
                            echo '<a class="dropdown-item filter-type" href="#" data-type="' . htmlspecialchars($type) . '">' . htmlspecialchars($type) . '</a>';
                        }
                        ?>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-hover" id="cardsTable" width="100%" cellspacing="0">
                        <thead class="thead-light">
                            <tr>
                                <th>ID</th>
                                <th>Customer</th>
                                <th>Card Number</th>
                                <th>Card Type</th>
                                <th>Expiry Date</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($cards as $card): ?>
                                <tr class="card-row" data-status="<?php echo $card['status']; ?>" data-type="<?php echo $card['card_type']; ?>">
                                    <td><?php echo $card['id']; ?></td>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <div class="avatar avatar-sm mr-2 bg-primary text-white">
                                                <?php echo strtoupper(substr($card['first_name'], 0, 1) . substr($card['last_name'], 0, 1)); ?>
                                            </div>
                                            <div>
                                                <a href="user_details.php?id=<?php echo $card['user_id']; ?>" class="font-weight-bold text-primary">
                                                    <?php echo htmlspecialchars($card['first_name'] . ' ' . $card['last_name']); ?>
                                                </a>
                                                <div class="small text-muted"><?php echo htmlspecialchars($card['account_number']); ?></div>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <?php 
                                            $cardBrand = '';
                                            $cardIcon = '';
                                            
                                            switch ($card['card_type']) {
                                                case 'Visa':
                                                    $cardBrand = 'visa';
                                                    $cardIcon = 'fab fa-cc-visa text-primary';
                                                    break;
                                                case 'Mastercard':
                                                    $cardBrand = 'mastercard';
                                                    $cardIcon = 'fab fa-cc-mastercard text-danger';
                                                    break;
                                                case 'American Express':
                                                    $cardBrand = 'amex';
                                                    $cardIcon = 'fab fa-cc-amex text-info';
                                                    break;
                                                case 'Discover':
                                                    $cardBrand = 'discover';
                                                    $cardIcon = 'fab fa-cc-discover text-warning';
                                                    break;
                                                default:
                                                    $cardBrand = 'default';
                                                    $cardIcon = 'fas fa-credit-card text-secondary';
                                            }
                                            ?>
                                            <i class="<?php echo $cardIcon; ?> fa-lg mr-2"></i>
                                            <span class="card-number">
                                                <?php 
                                                $cardNumber = htmlspecialchars($card['card_number']);
                                                // Display only last 4 digits for security
                                                echo str_replace(substr($cardNumber, 0, -4), str_repeat('•', strlen($cardNumber) - 4), $cardNumber);
                                                ?>
                                            </span>
                                        </div>
                                    </td>
                                    <td>
                                        <span class="badge badge-pill card-type-badge card-type-<?php echo strtolower(str_replace(' ', '-', $card['card_type'])); ?>">
                                            <?php echo htmlspecialchars($card['card_type']); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php 
                                        // Fix for undefined array key "expiry_date"
                                        echo isset($card['expiry_date']) ? htmlspecialchars($card['expiry_date']) : 'N/A'; 
                                        ?>
                                    </td>
                                    <td>
                                        <span class="badge badge-pill badge-<?php echo $card['status'] == 'active' ? 'soft-success' : 'soft-warning'; ?> px-3 py-2">
                                            <i class="fas fa-<?php echo $card['status'] == 'active' ? 'check-circle' : 'lock'; ?> mr-1"></i>
                                            <?php echo ucfirst($card['status']); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <div class="btn-group">
                                            <button class="btn btn-sm btn-<?php echo $card['status'] == 'active' ? 'warning' : 'success'; ?> toggle-status" 
                                                    data-id="<?php echo $card['id']; ?>" 
                                                    data-status="<?php echo $card['status']; ?>"
                                                    data-toggle="tooltip" 
                                                    title="<?php echo $card['status'] == 'active' ? 'Freeze Card' : 'Activate Card'; ?>">
                                                <i class="fas fa-<?php echo $card['status'] == 'active' ? 'lock' : 'unlock'; ?>"></i>
                                            </button>
                                            <button class="btn btn-sm btn-info view-card" 
                                                    data-id="<?php echo $card['id']; ?>"
                                                    data-toggle="tooltip" 
                                                    title="View Card Details">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                            <button class="btn btn-sm btn-danger delete-card" 
                                                    data-id="<?php echo $card['id']; ?>"
                                                    data-toggle="tooltip" 
                                                    title="Delete Card">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Create Card Modal -->
<div class="modal fade" id="createCardModal" tabindex="-1" role="dialog" aria-labelledby="createCardModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="createCardModalLabel">
                    <i class="fas fa-credit-card mr-2"></i> Issue New Card
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <form id="createCardForm">
                <div class="modal-body">
                    <div class="form-group">
                        <label for="user_id">Select Customer <span class="text-danger">*</span></label>
                        <select class="form-control select2" id="user_id" name="user_id" required>
                            <option value="">-- Select Customer --</option>
                            <?php
                            $stmt = $db->query("SELECT id, first_name, last_name, account_number FROM users ORDER BY first_name, last_name");
                            $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
                            foreach ($users as $user) {
                                echo '<option value="' . $user['id'] . '">' . htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) . ' (' . $user['account_number'] . ')</option>';
                            }
                            ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="card_type">Card Type <span class="text-danger">*</span></label>
                        <select class="form-control" id="card_type" name="card_type" required>
                            <option value="Visa">Visa</option>
                            <option value="Mastercard">Mastercard</option>
                            <option value="American Express">American Express</option>
                            <option value="Discover">Discover</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="daily_limit">Daily Transaction Limit <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <div class="input-group-prepend">
                                <span class="input-group-text">$</span>
                            </div>
                            <input type="number" class="form-control" id="daily_limit" name="daily_limit" value="5000" min="100" max="50000" required>
                        </div>
                        <small class="form-text text-muted">Set the maximum daily transaction limit for this card.</small>
                    </div>
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle mr-1"></i> Card number, expiry date, and CVV will be automatically generated.
                    </div>
                    <div class="card-preview mt-3">
                        <div class="credit-card" id="cardPreview">
                            <div class="credit-card-brand"></div>
                            <div class="chip-icon"><i class="fas fa-microchip"></i></div>
                            <div class="card-number-preview">•••• •••• •••• ••••</div>
                            <div class="card-details">
                                <div class="card-holder">
                                    <div class="label">Card Holder</div>
                                    <div class="value" id="cardHolderPreview">CUSTOMER NAME</div>
                                </div>
                                <div class="expiry">
                                    <div class="label">Expires</div>
                                    <div class="value" id="expiryPreview">MM/YY</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-credit-card mr-1"></i> Issue Card
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- View Card Modal -->
<div class="modal fade" id="viewCardModal" tabindex="-1" role="dialog" aria-labelledby="viewCardModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header bg-info text-white">
                <h5 class="modal-title" id="viewCardModalLabel">
                    <i class="fas fa-credit-card mr-2"></i> Card Details
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="text-center mb-4">
                    <div class="credit-card" id="viewCardPreview">
                        <div class="credit-card-brand"></div>
                        <div class="chip-icon"><i class="fas fa-microchip"></i></div>
                        <div class="card-number-preview" id="viewCardNumber">•••• •••• •••• ••••</div>
                        <div class="card-details">
                            <div class="card-holder">
                                <div class="label">Card Holder</div>
                                <div class="value" id="viewCardHolder">CUSTOMER NAME</div>
                            </div>
                            <div class="expiry">
                                <div class="label">Expires</div>
                                <div class="value" id="viewExpiry">MM/YY</div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="font-weight-bold">Card Number</label>
                            <div class="input-group">
                                <input type="text" class="form-control" id="fullCardNumber" readonly>
                                <div class="input-group-append">
                                    <button class="btn btn-outline-secondary" type="button" id="toggleCardNumber">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="font-weight-bold">CVV</label>
                            <div class="input-group">
                                <input type="text" class="form-control" id="cardCvv" readonly>
                                <div class="input-group-append">
                                    <button class="btn btn-outline-secondary" type="button" id="toggleCvv">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="font-weight-bold">Daily Limit</label>
                            <input type="text" class="form-control" id="viewDailyLimit" readonly>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="font-weight-bold">Status</label>
                            <input type="text" class="form-control" id="viewStatus" readonly>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="font-weight-bold">Created Date</label>
                            <input type="text" class="form-control" id="viewCreatedDate" readonly>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="font-weight-bold">Last Updated</label>
                            <input type="text" class="form-control" id="viewUpdatedDate" readonly>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="viewCardToggleStatus">
                    <i class="fas fa-lock"></i> <span id="viewCardToggleStatusText">Freeze Card</span>
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Confirmation Modal for Card Status Toggle -->
<div class="modal fade" id="toggleStatusModal" tabindex="-1" role="dialog" aria-labelledby="toggleStatusModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header" id="toggleStatusHeader">
                <h5 class="modal-title" id="toggleStatusModalLabel">Confirm Status Change</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="text-center mb-4">
                    <div class="avatar avatar-lg mx-auto mb-3" id="toggleStatusIcon">
                        <i class="fas fa-lock fa-2x"></i>
                    </div>
                    <h5 id="toggleStatusTitle">Freeze Card</h5>
                    <p class="text-muted" id="toggleStatusMessage">Are you sure you want to freeze this card?</p>
                </div>
                <div class="form-group">
                    <label for="status_note">Note (Optional)</label>
                    <textarea class="form-control" id="status_note" rows="3" placeholder="Add a note about this status change..."></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn" id="confirmToggleStatus">Confirm</button>
            </div>
        </div>
    </div>
</div>

<!-- Confirmation Modal for Card Deletion -->
<div class="modal fade" id="deleteCardModal" tabindex="-1" role="dialog" aria-labelledby="deleteCardModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title" id="deleteCardModalLabel">
                    <i class="fas fa-trash-alt mr-2"></i> Delete Card
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="text-center mb-4">
                    <div class="avatar avatar-lg bg-danger text-white mx-auto mb-3">
                        <i class="fas fa-exclamation-triangle fa-2x"></i>
                    </div>
                    <h5>Are you sure?</h5>
                    <p class="text-muted">This action cannot be undone. The card will be permanently deleted from the system.</p>
                </div>
                <div class="form-group">
                    <label for="delete_reason">Reason for Deletion <span class="text-danger">*</span></label>
                    <textarea class="form-control" id="delete_reason" rows="3" required placeholder="Please provide a reason for deleting this card..."></textarea>
                    <div class="invalid-feedback">Please provide a reason for deletion.</div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteCard">
                    <i class="fas fa-trash-alt mr-1"></i> Delete Card
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Add custom CSS for enhanced visuals -->
<style>
/* Custom Badge Styles */
.badge-soft-success {
    color: #10b981;
    background-color: rgba(16, 185, 129, 0.1);
}

.badge-soft-warning {
    color: #f59e0b;
    background-color: rgba(245, 158, 11, 0.1);
}

.badge-soft-info {
    color: #0ea5e9;
    background-color: rgba(14, 165, 233, 0.1);
}

.badge-soft-danger {
    color: #ef4444;
    background-color: rgba(239, 68, 68, 0.1);
}

/* Avatar Styles */
.avatar {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 36px;
    height: 36px;
    border-radius: 50%;
    font-weight: 600;
}

.avatar-sm {
    width: 32px;
    height: 32px;
    font-size: 0.75rem;
}

.avatar-lg {
    width: 64px;
    height: 64px;
    font-size: 1.5rem;
}

/* Card Hover Effects */
.dashboard-card {
    transition: all 0.3s ease;
}

.dashboard-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15) !important;
}

/* Card Type Badge */
.card-type-badge {
    padding: 0.35em 0.65em;
    font-weight: 500;
}

.card-type-visa {
    background-color: rgba(79, 70, 229, 0.1);
    color: #4f46e5;
}

.card-type-mastercard {
    background-color: rgba(239, 68, 68, 0.1);
    color: #ef4444;
}

.card-type-american-express {
    background-color: rgba(14, 165, 233, 0.1);
    color: #0ea5e9;
}

.card-type-discover {
    background-color: rgba(245, 158, 11, 0.1);
    color: #f59e0b;
}

/* Table Hover Effect */
#cardsTable tbody tr {
    transition: all 0.2s ease;
}

#cardsTable tbody tr:hover {
    background-color: #f8f9ff !important;
}

/* Custom Colors */
.text-primary-light {
    color: #818cf8;
}

.text-success-light {
    color: #34d399;
}

.text-warning-light {
    color: #fbbf24;
}

.text-info-light {
    color: #38bdf8;
}

/* Page Header */
.page-header {
    padding: 1.5rem 0;
    margin-bottom: 1.5rem;
    border-bottom: 1px solid #e5e7eb;
}

.page-header-title {
    font-size: 1.75rem;
    font-weight: 700;
    margin-bottom: 0.25rem;
}

/* Progress Bar Animation */
.progress-bar {
    transition: width 1s ease;
}

/* Counter Animation */
.counter-value {
    display: inline-block;
}

/* Credit Card Preview */
.credit-card {
    width: 100%;
    height: 200px;
    border-radius: 16px;
    background: linear-gradient(135deg, #4f46e5, #818cf8);
    color: white;
    padding: 20px;
    position: relative;
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    transition: all 0.3s ease;
}

.credit-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
}

.credit-card.visa {
    background: linear-gradient(135deg, #4f46e5, #818cf8);
}

.credit-card.mastercard {
    background: linear-gradient(135deg, #ef4444, #f87171);
}

.credit-card.amex {
    background: linear-gradient(135deg, #0ea5e9, #38bdf8);
}

.credit-card.discover {
    background: linear-gradient(135deg, #f59e0b, #fbbf24);
}

.credit-card-brand {
    position: absolute;
    top: 20px;
    right: 20px;
    font-size: 24px;
}

.chip-icon {
    margin-bottom: 30px;
    font-size: 24px;
    color: rgba(255, 255, 255, 0.8);
}

.card-number-preview {
    font-size: 20px;
    letter-spacing: 2px;
    margin-bottom: 30px;
    font-family: monospace;
}

.card-details {
    display: flex;
    justify-content: space-between;
}

.card-holder, .expiry {
    text-transform: uppercase;
}

.label {
    font-size: 10px;
    opacity: 0.7;
    margin-bottom: 5px;
}

.value {
    font-size: 14px;
    letter-spacing: 1px;
}

/* Select2 Customization */
.select2-container--default .select2-selection--single {
    height: calc(1.5em + 0.75rem + 2px);
    padding: 0.375rem 0.75rem;
    font-size: 1rem;
    font-weight: 400;
    line-height: 1.5;
    color: #495057;
    background-color: #fff;
    background-clip: padding-box;
    border: 1px solid #ced4da;
    border-radius: 0.25rem;
}

.select2-container--default .select2-selection--single .select2-selection__rendered {
    line-height: 1.5;
    padding-left: 0;
    padding-right: 0;
}

.select2-container--default .select2-selection--single .select2-selection__arrow {
    height: calc(1.5em + 0.75rem);
}

/* Pulse Animation for Buttons */
@keyframes pulse-animation {
    0% {
        box-shadow: 0 0 0 0 rgba(79, 70, 229, 0.7);
    }
    70% {
        box-shadow: 0 0 0 10px rgba(79, 70, 229, 0);
    }
    100% {
        box-shadow: 0 0 0 0 rgba(79, 70, 229, 0);
    }
}

.pulse-animation {
    animation: pulse-animation 0.5s ease-out;
}
</style>

<?php include 'includes/footer.php'; ?>

<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/countup.js@2.0.7/dist/countUp.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>
$(document).ready(function() {
    // Initialize Select2
    $('.select2').select2({
        theme: 'bootstrap4',
        placeholder: 'Select a customer',
        width: '100%'
    });

    // Initialize DataTable with enhanced features
    var cardsTable = $('#cardsTable').DataTable({
        order: [[0, 'desc']], // Sort by ID by default
        responsive: true,
        pageLength: 10,
        lengthMenu: [[5, 10, 25, 50, -1], [5, 10, 25, 50, "All"]],
        language: {
            search: "<i class='fas fa-search'></i>",
            searchPlaceholder: "Search cards...",
            lengthMenu: "Show _MENU_ cards per page",
            info: "Showing _START_ to _END_ of _TOTAL_ cards",
            infoEmpty: "Showing 0 to 0 of 0 cards",
            infoFiltered: "(filtered from _MAX_ total cards)"
        },
        dom: '<"top"lf>rt<"bottom"ip><"clear">',
        initComplete: function() {
            // Add custom filter buttons styling
            $('.dataTables_length select').addClass('custom-select custom-select-sm');
            $('.dataTables_filter input').addClass('form-control-sm');
        }
    });

    // Initialize tooltips
    $('[data-toggle="tooltip"]').tooltip();

    // Filter by status
    $('.filter-status').click(function(e) {
        e.preventDefault();
        const status = $(this).data('status');
        
        if (status === 'all') {
            cardsTable.column(5).search('').draw();
        } else {
            cardsTable.column(5).search(status).draw();
        }
    });

    // Filter by card type
    $('.filter-type').click(function(e) {
        e.preventDefault();
        const type = $(this).data('type');
        
        if (type === 'all') {
            cardsTable.column(3).search('').draw();
        } else {
            cardsTable.column(3).search(type).draw();
        }
    });

    // Variables to store the card ID for modals
    let currentCardId = null;
    let currentCardStatus = null;
    let currentCardDetails = null;

    // Toggle card status
    $('.toggle-status').click(function() {
        currentCardId = $(this).data('id');
        currentCardStatus = $(this).data('status');
        const newStatus = currentCardStatus === 'active' ? 'frozen' : 'active';
        
        // Update modal UI based on the action
        if (newStatus === 'frozen') {
            $('#toggleStatusHeader').addClass('bg-warning text-white').removeClass('bg-success');
            $('#toggleStatusIcon').addClass('bg-warning text-white').removeClass('bg-success');
            $('#toggleStatusIcon i').removeClass('fa-unlock').addClass('fa-lock');
            $('#toggleStatusTitle').text('Freeze Card');
            $('#toggleStatusMessage').text('Are you sure you want to freeze this card? This will prevent any transactions from being processed.');
            $('#confirmToggleStatus').addClass('btn-warning').removeClass('btn-success').text('Freeze Card');
        } else {
            $('#toggleStatusHeader').addClass('bg-success text-white').removeClass('bg-warning');
            $('#toggleStatusIcon').addClass('bg-success text-white').removeClass('bg-warning');
            $('#toggleStatusIcon i').removeClass('fa-lock').addClass('fa-unlock');
            $('#toggleStatusTitle').text('Activate Card');
            $('#toggleStatusMessage').text('Are you sure you want to activate this card? This will allow transactions to be processed.');
            $('#confirmToggleStatus').addClass('btn-success').removeClass('btn-warning').text('Activate Card');
        }
        
        $('#toggleStatusModal').modal('show');
    });

    // Confirm toggle status
    $('#confirmToggleStatus').click(function() {
        const newStatus = currentCardStatus === 'active' ? 'frozen' : 'active';
        const note = $('#status_note').val();
        
        $.ajax({
            url: 'ajax/card_actions.php',
            type: 'POST',
            data: {
                action: 'toggle_status',
                card_id: currentCardId,
                status: newStatus,
                note: note
            },
            dataType: 'json',
            beforeSend: function() {
                // Show loading state
                $('#confirmToggleStatus').html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Processing...');
                $('#confirmToggleStatus').prop('disabled', true);
            },
            success: function(response) {
                if (response.success) {
                    $('#toggleStatusModal').modal('hide');
                    
                    Swal.fire({
                        title: 'Success!',
                        text: `Card has been ${newStatus === 'active' ? 'activated' : 'frozen'}.`,
                        icon: 'success',
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#10b981'
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        title: 'Error!',
                        text: response.message || 'An error occurred while processing your request.',
                        icon: 'error',
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#ef4444'
                    });
                    
                    // Reset button state
                    $('#confirmToggleStatus').html(newStatus === 'active' ? 'Activate Card' : 'Freeze Card');
                    $('#confirmToggleStatus').prop('disabled', false);
                }
            },
            error: function() {
                Swal.fire({
                    title: 'Error!',
                    text: 'An error occurred while processing your request.',
                    icon: 'error',
                    confirmButtonText: 'OK',
                    confirmButtonColor: '#ef4444'
                });
                
                // Reset button state
                $('#confirmToggleStatus').html(newStatus === 'active' ? 'Activate Card' : 'Freeze Card');
                $('#confirmToggleStatus').prop('disabled', false);
            }
        });
    });

    // View card details
    $('.view-card').click(function() {
        currentCardId = $(this).data('id');
        
        // Get card details via AJAX
        $.ajax({
            url: 'ajax/card_actions.php',
            type: 'POST',
            data: {
                action: 'get_details',
                card_id: currentCardId
            },
            dataType: 'json',
            beforeSend: function() {
                // Show loading state
                $(this).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>');
                $(this).prop('disabled', true);
            },
            success: function(response) {
                if (response.success) {
                    currentCardDetails = response.card;
                    
                    // Update card preview
                    updateCardPreview('#viewCardPreview', currentCardDetails.card_type);
                    $('#viewCardNumber').text(maskCardNumber(currentCardDetails.card_number));
                    $('#viewCardHolder').text(currentCardDetails.card_holder.toUpperCase());
                    $('#viewExpiry').text(currentCardDetails.expiry_date || 'MM/YY');
                    
                    // Update form fields
                    $('#fullCardNumber').val(maskCardNumber(currentCardDetails.card_number));
                    $('#cardCvv').val('•••');
                    $('#viewDailyLimit').val('$' + parseFloat(currentCardDetails.daily_limit).toLocaleString());
                    $('#viewStatus').val(currentCardDetails.status.charAt(0).toUpperCase() + currentCardDetails.status.slice(1));
                    $('#viewCreatedDate').val(formatDate(currentCardDetails.created_at));
                    $('#viewUpdatedDate').val(formatDate(currentCardDetails.updated_at || currentCardDetails.created_at));
                    
                    // Update toggle status button
                    if (currentCardDetails.status === 'active') {
                        $('#viewCardToggleStatus').removeClass('btn-success').addClass('btn-warning');
                        $('#viewCardToggleStatus i').removeClass('fa-unlock').addClass('fa-lock');
                        $('#viewCardToggleStatusText').text('Freeze Card');
                    } else {
                        $('#viewCardToggleStatus').removeClass('btn-warning').addClass('btn-success');
                        $('#viewCardToggleStatus i').removeClass('fa-lock').addClass('fa-unlock');
                        $('#viewCardToggleStatusText').text('Activate Card');
                    }
                    
                    $('#viewCardModal').modal('show');
                } else {
                    Swal.fire({
                        title: 'Error!',
                        text: response.message || 'An error occurred while retrieving card details.',
                        icon: 'error',
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#ef4444'
                    });
                }
                
                // Reset button state
                $(this).html('<i class="fas fa-eye"></i>');
                $(this).prop('disabled', false);
            },
            error: function() {
                Swal.fire({
                    title: 'Error!',
                    text: 'An error occurred while retrieving card details.',
                    icon: 'error',
                    confirmButtonText: 'OK',
                    confirmButtonColor: '#ef4444'
                });
                
                // Reset button state
                $(this).html('<i class="fas fa-eye"></i>');
                $(this).prop('disabled', false);
            }
        });
    });

    // Toggle card number visibility
    $('#toggleCardNumber').click(function() {
        const $cardNumber = $('#fullCardNumber');
        const $icon = $(this).find('i');
        
        if ($cardNumber.val().includes('•')) {
            $cardNumber.val(currentCardDetails.card_number);
            $icon.removeClass('fa-eye').addClass('fa-eye-slash');
        } else {
            $cardNumber.val(maskCardNumber(currentCardDetails.card_number));
            $icon.removeClass('fa-eye-slash').addClass('fa-eye');
        }
    });

    // Toggle CVV visibility
    $('#toggleCvv').click(function() {
        const $cvv = $('#cardCvv');
        const $icon = $(this).find('i');
        
        if ($cvv.val() === '•••') {
            $cvv.val(currentCardDetails.cvv);
            $icon.removeClass('fa-eye').addClass('fa-eye-slash');
        } else {
            $cvv.val('•••');
            $icon.removeClass('fa-eye-slash').addClass('fa-eye');
        }
    });

    // View card toggle status button
    $('#viewCardToggleStatus').click(function() {
        $('#viewCardModal').modal('hide');
        
        // Trigger the toggle status modal
        currentCardStatus = currentCardDetails.status;
        const newStatus = currentCardStatus === 'active' ? 'frozen' : 'active';
        
        // Update modal UI based on the action
        if (newStatus === 'frozen') {
            $('#toggleStatusHeader').addClass('bg-warning text-white').removeClass('bg-success');
            $('#toggleStatusIcon').addClass('bg-warning text-white').removeClass('bg-success');
            $('#toggleStatusIcon i').removeClass('fa-unlock').addClass('fa-lock');
            $('#toggleStatusTitle').text('Freeze Card');
            $('#toggleStatusMessage').text('Are you sure you want to freeze this card? This will prevent any transactions from being processed.');
            $('#confirmToggleStatus').addClass('btn-warning').removeClass('btn-success').text('Freeze Card');
        } else {
            $('#toggleStatusHeader').addClass('bg-success text-white').removeClass('bg-warning');
            $('#toggleStatusIcon').addClass('bg-success text-white').removeClass('bg-warning');
            $('#toggleStatusIcon i').removeClass('fa-lock').addClass('fa-unlock');
            $('#toggleStatusTitle').text('Activate Card');
            $('#toggleStatusMessage').text('Are you sure you want to activate this card? This will allow transactions to be processed.');
            $('#confirmToggleStatus').addClass('btn-success').removeClass('btn-warning').text('Activate Card');
        }
        
        $('#toggleStatusModal').modal('show');
    });

    // Delete card
    $('.delete-card').click(function() {
        currentCardId = $(this).data('id');
        $('#deleteCardModal').modal('show');
    });

    // Confirm delete card
    $('#confirmDeleteCard').click(function() {
        const reason = $('#delete_reason').val();
        
        if (!reason.trim()) {
            $('#delete_reason').addClass('is-invalid');
            return;
        }
        
        $.ajax({
            url: 'ajax/card_actions.php',
            type: 'POST',
            data: {
                action: 'delete',
                card_id: currentCardId,
                reason: reason
            },
            dataType: 'json',
            beforeSend: function() {
                // Show loading state
                $('#confirmDeleteCard').html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Processing...');
                $('#confirmDeleteCard').prop('disabled', true);
            },
            success: function(response) {
                if (response.success) {
                    $('#deleteCardModal').modal('hide');
                    
                    Swal.fire({
                        title: 'Success!',
                        text: 'Card has been deleted.',
                        icon: 'success',
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#10b981'
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        title: 'Error!',
                        text: response.message || 'An error occurred while processing your request.',
                        icon: 'error',
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#ef4444'
                    });
                    
                    // Reset button state
                    $('#confirmDeleteCard').html('<i class="fas fa-trash-alt mr-1"></i> Delete Card');
                    $('#confirmDeleteCard').prop('disabled', false);
                }
            },
            error: function() {
                Swal.fire({
                    title: 'Error!',
                    text: 'An error occurred while processing your request.',
                    icon: 'error',
                    confirmButtonText: 'OK',
                    confirmButtonColor: '#ef4444'
                });
                
                // Reset button state
                $('#confirmDeleteCard').html('<i class="fas fa-trash-alt mr-1"></i> Delete Card');
                $('#confirmDeleteCard').prop('disabled', false);
            }
        });
    });

    // Create card form submission
    $('#createCardForm').submit(function(e) {
        e.preventDefault();
        
        const userId = $('#user_id').val();
        const cardType = $('#card_type').val();
        const dailyLimit = $('#daily_limit').val();
        
        if (!userId) {
            Swal.fire({
                title: 'Error!',
                text: 'Please select a customer.',
                icon: 'error',
                confirmButtonText: 'OK',
                confirmButtonColor: '#ef4444'
            });
            return;
        }
        
        $.ajax({
            url: 'ajax/card_actions.php',
            type: 'POST',
            data: {
                action: 'create',
                user_id: userId,
                card_type: cardType,
                daily_limit: dailyLimit
            },
            dataType: 'json',
            beforeSend: function() {
                // Show loading state
                $('#createCardForm button[type="submit"]').html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Processing...');
                $('#createCardForm button[type="submit"]').prop('disabled', true);
            },
            success: function(response) {
                if (response.success) {
                    $('#createCardModal').modal('hide');
                    
                    Swal.fire({
                        title: 'Success!',
                        text: 'Card has been created successfully.',
                        icon: 'success',
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#10b981'
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        title: 'Error!',
                        text: response.message || 'An error occurred while processing your request.',
                        icon: 'error',
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#ef4444'
                    });
                    
                    // Reset button state
                    $('#createCardForm button[type="submit"]').html('<i class="fas fa-credit-card mr-1"></i> Issue Card');
                    $('#createCardForm button[type="submit"]').prop('disabled', false);
                }
            },
            error: function() {
                Swal.fire({
                    title: 'Error!',
                    text: 'An error occurred while processing your request.',
                    icon: 'error',
                    confirmButtonText: 'OK',
                    confirmButtonColor: '#ef4444'
                });
                
                // Reset button state
                $('#createCardForm button[type="submit"]').html('<i class="fas fa-credit-card mr-1"></i> Issue Card');
                $('#createCardForm button[type="submit"]').prop('disabled', false);
            }
        });
    });

    // Initialize animated counters
    $('.counter-value').each(function() {
        const $this = $(this);
        const countTo = parseFloat($this.text().replace(/,/g, ''));
        
        const countUp = new CountUp($this[0], 0, countTo, 0, 2.5, {
            useEasing: true,
            useGrouping: true,
            separator: ',',
            decimal: '.'
        });
        
        if (!countUp.error) {
            countUp.start();
        } else {
            console.error(countUp.error);
        }
    });

    // Card Status Distribution Chart
    const statusCtx = document.getElementById('cardStatusChart');
    if (statusCtx) {
        new Chart(statusCtx, {
            type: 'doughnut',
            data: {
                labels: ['Active', 'Frozen'],
                datasets: [{
                    data: [
                        <?php echo count($activeCards); ?>,
                        <?php echo count($frozenCards); ?>
                    ],
                    backgroundColor: [
                        '#10b981', // success
                        '#f59e0b'  // warning
                    ],
                    borderWidth: 0,
                    hoverOffset: 10
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutoutPercentage: 70,
                legend: {
                    display: false
                },
                tooltips: {
                    callbacks: {
                        label: function(tooltipItem, data) {
                            const dataset = data.datasets[tooltipItem.datasetIndex];
                            const total = dataset.data.reduce((previousValue, currentValue) => previousValue + currentValue);
                            const currentValue = dataset.data[tooltipItem.index];
                            const percentage = Math.round((currentValue/total) * 100);
                            return data.labels[tooltipItem.index] + ': ' + currentValue + ' (' + percentage + '%)';
                        }
                    }
                },
                animation: {
                    animateScale: true,
                    animateRotate: true,
                    duration: 2000,
                    easing: 'easeOutQuart'
                }
            }
        });
    }

    // Card Distribution by Type Chart
    const distributionCtx = document.getElementById('cardDistributionChart');
    if (distributionCtx) {
        // Count cards by type
        const cardsByType = {};
        <?php foreach ($cardTypes as $type): ?>
            cardsByType['<?php echo $type; ?>'] = <?php 
                echo count(array_filter($cards, function($card) use ($type) {
                    return $card['card_type'] == $type;
                }));
            ?>;
        <?php endforeach; ?>

        // Define colors for each card type
        const typeColors = {
            'Visa': '#4f46e5',
            'Mastercard': '#ef4444',
            'American Express': '#0ea5e9',
            'Discover': '#f59e0b'
        };

        new Chart(distributionCtx, {
            type: 'bar',
            data: {
                labels: Object.keys(cardsByType),
                datasets: [
                    {
                        label: 'Number of Cards',
                        backgroundColor: Object.keys(cardsByType).map(type => typeColors[type] || '#6b7280'),
                        borderColor: Object.keys(cardsByType).map(type => typeColors[type] || '#6b7280'),
                        borderWidth: 1,
                        data: Object.values(cardsByType)
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    xAxes: [{
                        gridLines: {
                            display: false
                        }
                    }],
                    yAxes: [{
                        ticks: {
                            beginAtZero: true,
                            stepSize: 1
                        }
                    }]
                },
                tooltips: {
                    mode: 'index',
                    intersect: false
                },
                animation: {
                    duration: 2000,
                    easing: 'easeOutQuart'
                }
            }
        });
    }

    // Input validation for deletion reason
    $('#delete_reason').on('input', function() {
        if ($(this).val().trim()) {
            $(this).removeClass('is-invalid');
        } else {
            $(this).addClass('is-invalid');
        }
    });

    // Add hover effect to table rows
    $('#cardsTable tbody tr').hover(
        function() {
            $(this).addClass('shadow-sm');
        },
        function() {
            $(this).removeClass('shadow-sm');
        }
    );

    // Add visual feedback when clicking action buttons
    $('.btn').on('click', function() {
        const $btn = $(this);
        $btn.addClass('pulse-animation');
        setTimeout(() => {
            $btn.removeClass('pulse-animation');
        }, 500);
    });

    // Update card preview based on card type
    $('#card_type').on('change', function() {
        const cardType = $(this).val();
        updateCardPreview('#cardPreview', cardType);
    });

    // Update card preview when customer is selected
    $('#user_id').on('change', function() {
        const selectedOption = $(this).find('option:selected');
        const customerName = selectedOption.text().split(' (')[0];
        $('#cardHolderPreview').text(customerName.toUpperCase());
        
        // Generate random expiry date (MM/YY format, 3 years from now)
        const now = new Date();
        const expiryMonth = String(now.getMonth() + 1).padStart(2, '0');
        const expiryYear = String((now.getFullYear() + 3) % 100).padStart(2, '0');
        $('#expiryPreview').text(`${expiryMonth}/${expiryYear}`);
    });

    // Helper function to update card preview
    function updateCardPreview(selector, cardType) {
        const $cardPreview = $(selector);
        $cardPreview.removeClass('visa mastercard amex discover');
        
        let brandIcon = '';
        switch (cardType) {
            case 'Visa':
                $cardPreview.addClass('visa');
                brandIcon = '<i class="fab fa-cc-visa"></i>';
                break;
            case 'Mastercard':
                $cardPreview.addClass('mastercard');
                brandIcon = '<i class="fab fa-cc-mastercard"></i>';
                break;
            case 'American Express':
                $cardPreview.addClass('amex');
                brandIcon = '<i class="fab fa-cc-amex"></i>';
                break;
            case 'Discover':
                $cardPreview.addClass('discover');
                brandIcon = '<i class="fab fa-cc-discover"></i>';
                break;
        }
        
        $cardPreview.find('.credit-card-brand').html(brandIcon);
    }

    // Helper function to mask card number
    function maskCardNumber(cardNumber) {
        if (!cardNumber) return '•••• •••• •••• ••••';
        
        // Remove any spaces or non-digit characters
        const digitsOnly = cardNumber.replace(/\D/g, '');
        
              // Keep only the last 4 digits visible
        const maskedPart = digitsOnly.slice(0, -4).replace(/./g, '•');
        const lastFour = digitsOnly.slice(-4);
        
        // Format the masked card number with spaces
        let formattedNumber = '';
        if (digitsOnly.length === 15) { // American Express
            formattedNumber = maskedPart.slice(0, 4) + ' ' + maskedPart.slice(4, 10) + ' ' + lastFour;
        } else {
            formattedNumber = maskedPart.slice(0, 4) + ' ' + maskedPart.slice(4, 8) + ' ' + maskedPart.slice(8, 12) + ' ' + lastFour;
        }
        
        return formattedNumber;
    }

    // Helper function to format date
    function formatDate(dateString) {
        if (!dateString) return 'N/A';
        
        const date = new Date(dateString);
        return date.toLocaleDateString('en-US', {
            year: 'numeric',
            month: 'short',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        });
    }

    // Initialize card preview on page load
    updateCardPreview('#cardPreview', $('#card_type').val());
});
</script>



