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

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

$success_message = '';
$error_message = '';

// Get card ID from URL and validate it
$card_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$card_id) {
    header("Location: cards.php");
    exit();
}

// Security Check: Fetch the card details ONLY if it belongs to the logged-in user
// MOVED THIS SECTION UP
$stmt = $db->prepare("SELECT * FROM cards WHERE id = ? AND user_id = ?");
$stmt->execute([$card_id, $_SESSION['user_id']]);
$card = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$card) {
    $_SESSION['error_message'] = "Card not found or permission denied.";
    header("Location: cards.php");
    exit();
}

// Fetch user details
$user_stmt = $db->prepare("SELECT id, currency, first_name, last_name FROM users WHERE id = ?");
$user_stmt->execute([$_SESSION['user_id']]);
$user = $user_stmt->fetch(PDO::FETCH_ASSOC);

// Default currency if not set
$default_currency = 'USD';
$user_currency = isset($user['currency']) ? $user['currency'] : $default_currency;

// --- HANDLE SETTINGS UPDATE ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_card_settings'])) {
    $daily_limit = filter_input(INPUT_POST, 'daily_spending_limit', FILTER_VALIDATE_FLOAT);
    $monthly_limit = filter_input(INPUT_POST, 'monthly_spending_limit', FILTER_VALIDATE_FLOAT);
    $online_payments = isset($_POST['online_payments_enabled']) ? 1 : 0;

    if ($daily_limit === false || $monthly_limit === false) {
        $error_message = "Invalid limit amount. Please enter a valid number.";
    } else {
        try {
            $stmt = $db->prepare("UPDATE cards SET daily_spending_limit = ?, monthly_spending_limit = ?, online_payments_enabled = ? WHERE id = ? AND user_id = ?");
            $stmt->execute([$daily_limit, $monthly_limit, $online_payments, $card_id, $_SESSION['user_id']]);
            $success_message = "Card settings have been updated successfully.";
        } catch (PDOException $e) {
            $error_message = "An error occurred while updating settings.";
            error_log("Card Settings Update Error: " . $e->getMessage());
        }
    }
}

// --- HANDLE CARD FUNDING ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['fund_card'])) {
    $amount = filter_input(INPUT_POST, 'fund_amount', FILTER_VALIDATE_FLOAT);
    $source_account = filter_input(INPUT_POST, 'source_account', FILTER_SANITIZE_STRING);
    
    // Use the source_account as the currency instead of relying on user's default currency
    $currency = $source_account;
    
    if ($amount <= 0) {
        $error_message = "Please enter a valid amount greater than zero.";
    } else {
        try {
            $db->beginTransaction();
            
            // Check if user has sufficient balance
            $balance_stmt = $db->prepare("SELECT balance FROM account_balances WHERE user_id = ? AND currency = ? FOR UPDATE");
            $balance_stmt->execute([$_SESSION['user_id'], $currency]);
            $balance_data = $balance_stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$balance_data || $balance_data['balance'] < $amount) {
                throw new Exception("Insufficient funds in your account.");
            }
            
            // Deduct from account balance
            $update_balance = $db->prepare("UPDATE account_balances SET balance = balance - ? WHERE user_id = ? AND currency = ?");
            $update_balance->execute([$amount, $_SESSION['user_id'], $currency]);
            
            // Create transaction record for the debit
            $reference = 'CARD_FUND_' . time();
            $card_last_four = substr($card['card_number'], -4); // Card number is now available
            $debit_stmt = $db->prepare("
                INSERT INTO transactions 
                (user_id, type, amount, currency, description, reference, status, transaction_type) 
                VALUES 
                (?, 'debit', ?, ?, ?, ?, 'completed', 'card_funding')
            ");
            $debit_stmt->execute([
                $_SESSION['user_id'], 
                $amount, 
                $currency, 
                "Fund card ending in " . $card_last_four, 
                $reference,
            ]);
            
            // Check if card_transactions table exists
            try {
                // Add record to card_transactions table
                $card_tx_stmt = $db->prepare("
                    INSERT INTO card_transactions 
                    (card_id, user_id, amount, transaction_type, description, reference, status) 
                    VALUES 
                    (?, ?, ?, 'funding', ?, ?, 'completed')
                ");
                $card_tx_stmt->execute([
                    $card_id,
                    $_SESSION['user_id'],
                    $amount,
                    "Card funding from account",
                    $reference
                ]);
            } catch (PDOException $e) {
                // If table doesn't exist, log the error but continue
                error_log("Card_transactions table error: " . $e->getMessage());
            }
            
            $db->commit();
            $success_message = "Card has been funded successfully with " . $currency . " " . number_format($amount, 2);
        } catch (Exception $e) {
            $db->rollBack();
            $error_message = $e->getMessage();
            error_log("Card Funding Error: " . $e->getMessage());
        }
    }
}

// Rest of your code...


// --- HANDLE EXTERNAL CARD LINKING ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['link_external_card'])) {
    $card_number = preg_replace('/\D/', '', $_POST['card_number']);
    $card_holder = filter_input(INPUT_POST, 'card_holder_name', FILTER_SANITIZE_STRING);
    $expiry_month = filter_input(INPUT_POST, 'expiry_month', FILTER_VALIDATE_INT);
    $expiry_year = filter_input(INPUT_POST, 'expiry_year', FILTER_VALIDATE_INT);
    $cvv = filter_input(INPUT_POST, 'cvv', FILTER_SANITIZE_STRING);
    $card_type = filter_input(INPUT_POST, 'card_type', FILTER_SANITIZE_STRING);
    
    // Validate inputs
    $errors = [];
    if (strlen($card_number) < 13 || strlen($card_number) > 19) {
        $errors[] = "Invalid card number.";
    }
    if (empty($card_holder)) {
        $errors[] = "Card holder name is required.";
    }
    if ($expiry_month < 1 || $expiry_month > 12) {
        $errors[] = "Invalid expiry month.";
    }
    if ($expiry_year < date('Y')) {
        $errors[] = "Card has expired.";
    }
    if (strlen($cvv) < 3 || strlen($cvv) > 4) {
        $errors[] = "Invalid CVV.";
    }
    if (!in_array($card_type, ['visa', 'mastercard', 'amex'])) {
        $errors[] = "Invalid card type.";
    }
    
    if (empty($errors)) {
        try {
            // Check if external_cards table exists
            try {
                // Check if card already exists
                $check_stmt = $db->prepare("SELECT id FROM external_cards WHERE card_number = ? AND user_id = ?");
                $check_stmt->execute([encrypt_card_number($card_number), $_SESSION['user_id']]);
                if ($check_stmt->rowCount() > 0) {
                    $error_message = "This card is already linked to your account.";
                } else {
                    // Insert the new external card
                    $insert_stmt = $db->prepare("
                        INSERT INTO external_cards 
                        (user_id, card_number, card_holder_name, expiry_month, expiry_year, cvv, card_type, status) 
                        VALUES 
                        (?, ?, ?, ?, ?, ?, ?, 'active')
                    ");
                    $insert_stmt->execute([
                        $_SESSION['user_id'],
                        encrypt_card_number($card_number),
                        $card_holder,
                        $expiry_month,
                        $expiry_year,
                        encrypt_cvv($cvv),
                        $card_type
                    ]);
                    
                    $success_message = "External card has been linked successfully.";
                }
            } catch (PDOException $e) {
                // If table doesn't exist
                $error_message = "External card linking is not available at this time.";
                error_log("External_cards table error: " . $e->getMessage());
            }
        } catch (Exception $e) {
            $error_message = "An error occurred while linking the card.";
            error_log("External Card Linking Error: " . $e->getMessage());
        }
    } else {
        $error_message = implode("<br>", $errors);
    }
}

// Security Check: Fetch the card details ONLY if it belongs to the logged-in user
$stmt = $db->prepare("SELECT * FROM cards WHERE id = ? AND user_id = ?");
$stmt->execute([$card_id, $_SESSION['user_id']]);
$card = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$card) {
    $_SESSION['error_message'] = "Card not found or permission denied.";
    header("Location: cards.php");
    exit();
}

// Fetch card-specific transactions
try {
    $trans_stmt = $db->prepare("
        SELECT t.* 
        FROM transactions t
        JOIN card_transactions ct ON t.reference = ct.reference
        WHERE ct.card_id = ? AND t.user_id = ?
        ORDER BY t.created_at DESC 
        LIMIT 5
    ");
    $trans_stmt->execute([$card_id, $_SESSION['user_id']]);
    $transactions = $trans_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    // If card_transactions table doesn't exist or join fails
    $transactions = [];
    error_log("Card transactions query error: " . $e->getMessage());
}

function formatCardNumber($number) {
    return implode(' ', str_split($number, 4));
}

// Helper functions for card encryption (implement these properly in production)
function encrypt_card_number($number) {
    // In production, use proper encryption
    return 'XXXXXXXXXXXX' . substr($number, -4);
}

function encrypt_cvv($cvv) {
    // In production, use proper encryption
    return '***';
}

// Get user accounts for funding options
$accounts_stmt = $db->prepare("SELECT currency, balance FROM account_balances WHERE user_id = ?");
$accounts_stmt->execute([$_SESSION['user_id']]);
$accounts = $accounts_stmt->fetchAll(PDO::FETCH_ASSOC);

// If no accounts found, create a default one for display purposes
if (empty($accounts)) {
    $accounts = [['currency' => $user_currency, 'balance' => 0]];
}

include 'includes/header.php';
include 'includes/sidebar.php';
?>

<style>
/* Redesigned Card Details Page Styles */
:root {
    --primary-color: #4f46e5;
    --primary-light: #eef2ff;
    --visa-color: #1a1f71;
    --mastercard-color: #000000;
    --amex-color: #006fcf;
    --border-color: #e2e8f0;
    --success-color: #10b981;
    --warning-color: #f59e0b;
}
.main-content { background-color: #f8fafc; }

/* Card Visual Styles */
.credit-card-display { perspective: 1000px; }
.credit-card-inner {
    width: 100%; max-width: 400px; margin: auto;
    transition: transform 0.8s; transform-style: preserve-3d;
    /* *** THIS IS THE FIX: Changed from 63% to 56.25% for a wider aspect ratio *** */
    padding-bottom: 56.25%; 
}
.credit-card-display.is-flipped .credit-card-inner { transform: rotateY(180deg); }
.credit-card-front, .credit-card-back {
    position: absolute; width: 100%; height: 100%;
    -webkit-backface-visibility: hidden; backface-visibility: hidden;
    border-radius: 1rem; padding: 1.5rem; color: white;
    box-shadow: 0 20px 30px rgba(0,0,0,0.15);
    display: flex; flex-direction: column; justify-content: space-between;
}
.credit-card-front.visa { background: linear-gradient(135deg, #1a1f71, #5b65d9); }
.credit-card-front.mastercard { background: linear-gradient(135deg, #000000, #4a4a4a); }
.credit-card-front.amex { background: linear-gradient(135deg, #006fcf, #65a9e0); }
.credit-card-back { background-color: #d1d5db; transform: rotateY(180deg); color: #1f2937; }
.card-chip { width: 40px; height: 30px; background: linear-gradient(135deg, #ffd700, #ffaa00); border-radius: 4px; }
.card-logo { font-size: 2.5rem; }
.card-number { font-family: 'Courier New', monospace; font-size: 1.5rem; letter-spacing: 2px; }
.card-details { font-size: 0.9rem; text-transform: uppercase; }
.card-back .magnetic-stripe { height: 40px; background-color: #1f2937; margin: 1rem -1.5rem; }
.card-back .signature-panel { text-align: right; margin-top: 1rem; }
.card-back .cvv-box { background-color: white; color: #1f2937; padding: 0.5rem; border-radius: 4px; display: inline-block; font-family: 'Courier New', monospace; font-weight: bold; }

/* Stat Cards */
.stat-card {
    background-color: white;
    border: 1px solid var(--border-color);
    border-radius: 1rem;
    padding: 1.5rem;
    text-align: center;
}
.stat-card-icon { font-size: 2rem; margin-bottom: 0.5rem; }
.stat-card-label { font-size: 0.875rem; color: #64748b; margin-bottom: 0.5rem; }
.stat-card-value { font-size: 1.25rem; font-weight: 600; }
.progress-bar-container { height: 8px; background-color: #e2e8f0; border-radius: 999px; overflow: hidden; margin-top: 0.5rem; }
.progress-bar-fill { height: 100%; background-color: var(--primary-color); border-radius: 999px; }

/* Tab Styles */
.nav-pills .nav-link { border-radius: 0.75rem; font-weight: 500; }
.nav-pills .nav-link.active { background-color: var(--primary-color); }
.form-check-input:checked { background-color: var(--primary-color); border-color: var(--primary-color); }

/* Modal styles */
.modal-content {
    border-radius: 1rem;
    border: none;
    box-shadow: 0 10px 25px rgba(0,0,0,0.1);
}
.modal-header {
    border-bottom: 1px solid var(--border-color);
    background-color: var(--primary-light);
    border-radius: 1rem 1rem 0 0;
}
.modal-footer {
    border-top: 1px solid var(--border-color);
}
</style>

<div class="main-content">
    <div class="container py-4">
        <div class="d-flex align-items-center mb-4">
            <a href="cards.php" class="btn btn-light me-3" style="border-radius: 50%; width: 40px; height: 40px; display: grid; place-content: center;"><i class='bx bx-arrow-back'></i></a>
            <div>
                <h1 class="h3 mb-0">Card Details</h1>
                <p class="text-muted mb-0">Manage your <?php echo ucfirst($card['card_type']); ?> card ending in <?php echo substr($card['card_number'], -4); ?></p>
            </div>
        </div>

        <?php if (!empty($success_message)): ?>
            <div class="alert alert-success"><?php echo $success_message; ?></div>
        <?php endif; ?>
        <?php if (!empty($error_message)): ?>
            <div class="alert alert-danger"><?php echo $error_message; ?></div>
        <?php endif; ?>

        <!-- Card Display -->
        <div class="credit-card-display mb-5" id="cardDisplay">
            <div class="credit-card-inner">
                <div class="credit-card-front <?php echo htmlspecialchars($card['card_type']); ?>">
                    <div class="d-flex justify-content-between align-items-start">
                        <div class="card-chip"></div>
                        <div class="card-logo">
                            <?php if ($card['card_type'] == 'visa'): ?><i class='bx bxl-visa'></i>
                            <?php elseif ($card['card_type'] == 'mastercard'): ?><i class='bx bxl-mastercard'></i>
                            <?php else: ?><i class='bx bxl-american-express'></i><?php endif; ?>
                        </div>
                    </div>
                    <div class="card-number"><?php echo formatCardNumber($card['card_number']); ?></div>
                    <div class="d-flex justify-content-between card-details">
                        <div><small>Card Holder</small><div><?php echo htmlspecialchars($card['card_holder_name']); ?></div></div>
                        <div><small>Expires</small><div><?php echo sprintf('%02d', $card['expiry_month']) . '/' . substr($card['expiry_year'], -2); ?></div></div>
                    </div>
                </div>
                <div class="credit-card-back">
                    <div class="magnetic-stripe"></div>
                    <div class="signature-panel">
                        <small>CVV</small>
                        <div class="cvv-box"><?php echo htmlspecialchars($card['cvv']); ?></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Stats Row - FIXED to show only limits -->
        <div class="row mb-5">
            <div class="col-md-4">
                <div class="stat-card">
                    <div class="stat-card-icon" style="color: <?php echo $card['status'] == 'active' ? 'var(--success-color)' : 'var(--warning-color)'; ?>;"><i class='bx bx-check-shield'></i></div>
                    <div class="stat-card-label">Card Status</div>
                    <div class="stat-card-value"><?php echo ucfirst($card['status']); ?></div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stat-card">
                    <div class="stat-card-icon text-primary"><i class='bx bx-sun'></i></div>
                    <div class="stat-card-label">Daily Spending Limit</div>
                    <div class="stat-card-value"><?php echo htmlspecialchars($user_currency); ?> <?php echo number_format($card['daily_spending_limit'], 2); ?></div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="stat-card">
                    <div class="stat-card-icon text-primary"><i class='bx bx-calendar'></i></div>
                    <div class="stat-card-label">Monthly Spending Limit</div>
                    <div class="stat-card-value"><?php echo htmlspecialchars($user_currency); ?> <?php echo number_format($card['monthly_spending_limit'], 2); ?></div>
                </div>
            </div>
        </div>

        <!-- Action Buttons -->
        <div class="d-flex justify-content-center gap-3 mb-5">
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#fundCardModal">
                <i class='bx bx-wallet me-1'></i> Fund Card
            </button>
          
        </div>

        <!-- Tabs for Settings and Transactions -->
        <div class="card">
            <div class="card-header">
                <ul class="nav nav-pills card-header-pills" id="pills-tab" role="tablist">
                    <li class="nav-item" role="presentation"><button class="nav-link active" id="pills-settings-tab" data-bs-toggle="pill" data-bs-target="#pills-settings" type="button">Settings</button></li>
                    <li class="nav-item" role="presentation"><button class="nav-link" id="pills-transactions-tab" data-bs-toggle="pill" data-bs-target="#pills-transactions" type="button">Transactions</button></li>
                    <li class="nav-item" role="presentation"><button class="nav-link" id="pills-statements-tab" data-bs-toggle="pill" data-bs-target="#pills-statements" type="button">Statements</button></li>
                </ul>
            </div>
            <div class="card-body">
                <div class="tab-content" id="pills-tabContent">
                    <div class="tab-pane fade show active" id="pills-settings" role="tabpanel">
                        <h5 class="mb-4">Card Controls & Limits</h5>
                        <form method="POST" action="card-details.php?id=<?php echo $card_id; ?>">
                            <ul class="list-group mb-4">
                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                    <div>
                                        <h6 class="mb-0">Online Payments</h6>
                                        <small class="text-muted">Allow or block payments on websites.</small>
                                    </div>
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" name="online_payments_enabled" role="switch" <?php echo ($card['online_payments_enabled']) ? 'checked' : ''; ?>>
                                    </div>
                                </li>
                            </ul>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="daily_spending_limit" class="form-label">Daily Spending Limit</label>
                                    <div class="input-group">
                                        <span class="input-group-text"><?php echo htmlspecialchars($user_currency); ?></span>
                                        <input type="number" class="form-control" name="daily_spending_limit" value="<?php echo htmlspecialchars($card['daily_spending_limit']); ?>" step="100">
                                    </div>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="monthly_spending_limit" class="form-label">Monthly Spending Limit</label>
                                    <div class="input-group">
                                        <span class="input-group-text"><?php echo htmlspecialchars($user_currency); ?></span>
                                        <input type="number" class="form-control" name="monthly_spending_limit" value="<?php echo htmlspecialchars($card['monthly_spending_limit']); ?>" step="500">
                                    </div>
                                </div>
                            </div>
                            <div class="text-end mt-3">
                                <button type="submit" name="update_card_settings" class="btn btn-primary">Save Settings</button>
                            </div>
                        </form>
                    </div>
                    <div class="tab-pane fade" id="pills-transactions" role="tabpanel">
                        <h5 class="mb-4">Card Transactions</h5>
                        <?php if (empty($transactions)): ?>
                            <div class="text-center py-5">
                                <i class='bx bx-receipt' style="font-size: 3rem; color: #d1d5db;"></i>
                                <p class="text-muted mt-3">No card transactions to display.</p>
                                <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#fundCardModal">
                                    Fund Your Card
                                </button>
                            </div>
                        <?php else: ?>
                            <ul class="list-group list-group-flush">
                                <?php foreach ($transactions as $tx): ?>
                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                        <div>
                                            <div class="fw-bold"><?php echo htmlspecialchars($tx['description']); ?></div>
                                            <small class="text-muted"><?php echo date('M d, Y', strtotime($tx['created_at'])); ?></small>
                                        </div>
                                        <div class="fw-bold text-<?php echo $tx['type'] == 'credit' ? 'success' : 'danger'; ?>">
                                            <?php echo $tx['type'] == 'credit' ? '+' : '-'; ?><?php echo htmlspecialchars($tx['currency']); ?> <?php echo number_format($tx['amount'], 2); ?>
                                        </div>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        <?php endif; ?>
                    </div>
                    <div class="tab-pane fade" id="pills-statements" role="tabpanel">
                        <h5 class="mb-4">Monthly Statements</h5>
                        <p class="text-muted text-center">This feature is coming soon.</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Fund Card Modal -->
<div class="modal fade" id="fundCardModal" tabindex="-1" aria-labelledby="fundCardModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="fundCardModalLabel">Fund Your Card</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="card-details.php?id=<?php echo $card_id; ?>">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="source_account" class="form-label">Source Account</label>
                        <select class="form-select" id="source_account" name="source_account" required onchange="updateCurrencySymbol(this.value)">
                            <?php foreach ($accounts as $account): ?>
                                <option value="<?php echo htmlspecialchars($account['currency']); ?>">
                                    <?php echo htmlspecialchars($account['currency']); ?> Account - Balance: <?php echo number_format($account['balance'], 2); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="fund_amount" class="form-label">Amount</label>
                        <div class="input-group">
                            <span class="input-group-text" id="currency-symbol"><?php echo !empty($accounts) ? htmlspecialchars($accounts[0]['currency']) : $user_currency; ?></span>
                            <input type="number" class="form-control" id="fund_amount" name="fund_amount" min="1" step="0.01" required>
                        </div>
                    </div>
                    <div class="alert alert-info">
                        <i class='bx bx-info-circle me-2'></i>
                        Funds will be immediately available on your card for spending.
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="fund_card" class="btn btn-primary">Fund Card</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Link External Card Modal -->
<div class="modal fade" id="linkCardModal" tabindex="-1" aria-labelledby="linkCardModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="linkCardModalLabel">Link External Card</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST" action="card-details.php?id=<?php echo $card_id; ?>">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="card_type" class="form-label">Card Type</label>
                        <select class="form-select" id="card_type" name="card_type" required>
                            <option value="visa">Visa</option>
                            <option value="mastercard">Mastercard</option>
                            <option value="amex">American Express</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="card_number" class="form-label">Card Number</label>
                        <input type="text" class="form-control" id="card_number" name="card_number" required maxlength="19" placeholder="XXXX XXXX XXXX XXXX">
                    </div>
                    <div class="mb-3">
                        <label for="card_holder_name" class="form-label">Card Holder Name</label>
                        <input type="text" class="form-control" id="card_holder_name" name="card_holder_name" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="expiry_month" class="form-label">Expiry Month</label>
                            <select class="form-select" id="expiry_month" name="expiry_month" required>
                                                               <?php for ($i = 1; $i <= 12; $i++): ?>
                                    <option value="<?php echo $i; ?>"><?php echo sprintf('%02d', $i); ?></option>
                                <?php endfor; ?>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="expiry_year" class="form-label">Expiry Year</label>
                            <select class="form-select" id="expiry_year" name="expiry_year" required>
                                <?php for ($i = date('Y'); $i <= date('Y') + 10; $i++): ?>
                                    <option value="<?php echo $i; ?>"><?php echo $i; ?></option>
                                <?php endfor; ?>
                            </select>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="cvv" class="form-label">CVV</label>
                        <input type="password" class="form-control" id="cvv" name="cvv" required maxlength="4" placeholder="XXX">
                    </div>
                    <div class="alert alert-info">
                        <i class='bx bx-shield-quarter me-2'></i>
                        Your card details are encrypted and stored securely. We comply with PCI DSS standards.
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="link_external_card" class="btn btn-primary">Link Card</button>
                </div>
            </form>
        </div>
    </div>
</div>

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

<script>
// Card flip animation
document.getElementById('cardDisplay').addEventListener('click', function() {
    this.classList.toggle('is-flipped');
});

// Format card number input with spaces
document.getElementById('card_number')?.addEventListener('input', function(e) {
    let value = e.target.value.replace(/\D/g, '');
    let formattedValue = '';
    
    for (let i = 0; i < value.length; i++) {
        if (i > 0 && i % 4 === 0) {
            formattedValue += ' ';
        }
        formattedValue += value[i];
    }
    
    e.target.value = formattedValue;
});

// Validate fund amount
document.getElementById('fund_amount')?.addEventListener('input', function(e) {
    if (parseFloat(e.target.value) <= 0) {
        e.target.setCustomValidity('Amount must be greater than zero');
    } else {
        e.target.setCustomValidity('');
    }
});

// Update currency symbol when source account changes
function updateCurrencySymbol(currency) {
    document.getElementById('currency-symbol').textContent = currency;
}
</script>

