<?php
session_start();
require_once '../includes/db.php';
require_once '../includes/functions.php';
require_once '../includes/session_manager.php';

redirectIfNotLoggedIn();

$userId = $_SESSION['user_id'];
$error = '';
$success = '';

// Get user account
$stmt = $pdo->prepare("SELECT account_id, account_number, balance FROM accounts WHERE user_id = ?");
$stmt->execute([$userId]);
$account = $stmt->fetch();

if (!$account) {
    die('Account not found.');
}

// Handle card actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $card_id = intval($_POST['card_id'] ?? 0);

    try {
        if ($action === 'request_card') {
            $card_type = $_POST['card_type'];
            $daily_limit = floatval($_POST['daily_limit']);
            $monthly_limit = floatval($_POST['monthly_limit']);
            $per_transaction_limit = floatval($_POST['per_transaction_limit']);
            $card_holder_name = strtoupper($_POST['card_holder_name']);

            $card_number = generateCardNumber();
            $expiry_date = date('Y-m-d', strtotime('+3 years'));
            $cvv = rand(100, 999);

            $stmt = $pdo->prepare("
                INSERT INTO virtual_cards (user_id, account_id, card_number, card_holder_name, expiry_date, cvv, card_type, daily_limit, monthly_limit, per_transaction_limit)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([$userId, $account['account_id'], $card_number, $card_holder_name, $expiry_date, $cvv, $card_type, $daily_limit, $monthly_limit, $per_transaction_limit]);

            $success = "Card created successfully!";

        } elseif ($action === 'block_card') {
            $stmt = $pdo->prepare("UPDATE virtual_cards SET card_status = 'blocked', blocked_at = NOW() WHERE card_id = ? AND user_id = ?");
            $stmt->execute([$card_id, $userId]);
            $success = "Card blocked successfully.";

        } elseif ($action === 'unblock_card') {
            $stmt = $pdo->prepare("UPDATE virtual_cards SET card_status = 'active', blocked_at = NULL WHERE card_id = ? AND user_id = ?");
            $stmt->execute([$card_id, $userId]);
            $success = "Card unblocked successfully.";

        } elseif ($action === 'update_limits') {
            $daily_limit = floatval($_POST['daily_limit']);
            $monthly_limit = floatval($_POST['monthly_limit']);
            $per_transaction_limit = floatval($_POST['per_transaction_limit']);

            $stmt = $pdo->prepare("UPDATE virtual_cards SET daily_limit = ?, monthly_limit = ?, per_transaction_limit = ? WHERE card_id = ? AND user_id = ?");
            $stmt->execute([$daily_limit, $monthly_limit, $per_transaction_limit, $card_id, $userId]);
            $success = "Card limits updated successfully.";
        }

    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}

// Fetch user's cards
$cards = $pdo->prepare("
    SELECT * FROM virtual_cards 
    WHERE user_id = ? 
    ORDER BY created_at DESC
");
$cards->execute([$userId]);
$cards = $cards->fetchAll();

// Fetch card transactions
$transactions = $pdo->prepare("
    SELECT ct.*, vc.card_number
    FROM card_transactions ct
    JOIN virtual_cards vc ON ct.card_id = vc.card_id
    WHERE ct.user_id = ?
    ORDER BY ct.transaction_date DESC
    LIMIT 20
");
$transactions->execute([$userId]);
$transactions = $transactions->fetchAll();

function generateCardNumber()
{
    $prefix = '4';
    $number = $prefix;
    for ($i = 0; $i < 15; $i++) {
        $number .= rand(0, 9);
    }
    return $number;
}

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

function maskCardNumber($number, $showFull = false)
{
    if ($showFull) {
        return formatCardNumber($number);
    }
    return '**** **** **** ' . substr($number, -4);
}

function getCardStatusBadge($status)
{
    if ($status === 'active') {
        return '<span class="status-badge active"><i class="fas fa-check-circle"></i> Active</span>';
    } elseif ($status === 'blocked') {
        return '<span class="status-badge blocked"><i class="fas fa-ban"></i> Blocked</span>';
    } else {
        return '<span class="status-badge expired"><i class="fas fa-clock"></i> ' . ucfirst($status) . '</span>';
    }
}

// Get user account information for sidebar
$stmt = $pdo->prepare("
    SELECT u.*, a.account_number, a.balance 
    FROM users u 
    JOIN accounts a ON u.user_id = a.user_id 
    WHERE u.user_id = ?
");
$stmt->execute([$userId]);
$user = $stmt->fetch();

if (!$user) {
    die('User account not found.');
}

$profilePic = $user['profile_picture'] ? '../uploads/' . $user['profile_picture'] : '../assets/images/default-avatars.png';
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title>My Cards - Oakshire Finance</title>
    <link
        href="https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,300;14..32,400;14..32,500;14..32,600;14..32,700;14..32,800&display=swap"
        rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        :root {
            --primary-navy: #0a2540;
            --primary-dark: #0a1c2f;
            --primary-blue: #1a4d8c;
            --success-green: #2e7d32;
            --error-red: #dc3545;
            --warning-orange: #f39c12;
            --gray-50: #f8f9fc;
            --gray-100: #f1f3f9;
            --gray-200: #e9ecef;
            --gray-300: #dee2e6;
            --gray-400: #ced4da;
            --gray-500: #adb5bd;
            --gray-600: #6c757d;
            --gray-700: #495057;
            --gray-800: #343a40;
            --gray-900: #212529;
            --white: #ffffff;
            --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.08);
            --shadow-md: 0 4px 12px rgba(0, 0, 0, 0.05);
            --shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.08);
            --shadow-hover: 0 12px 28px rgba(0, 0, 0, 0.12);
            --transition: all 0.3s ease;
        }

        body {
            font-family: 'Inter', system-ui, sans-serif;
            background: var(--gray-50);
            color: var(--gray-800);
            line-height: 1.5;
        }

        /* Layout */
        .dashboard-wrapper {
            display: flex;
            min-height: 100vh;
        }

        /* Sidebar */
        .sidebar {
            width: 280px;
            background: var(--white);
            border-right: 1px solid var(--gray-200);
            position: fixed;
            left: 0;
            top: 0;
            bottom: 0;
            overflow-y: auto;
            transition: transform 0.3s ease;
            z-index: 100;
        }

        .sidebar-header {
            padding: 24px;
            border-bottom: 1px solid var(--gray-200);
            text-align: center;
        }

        .logo {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
            text-decoration: none;
        }

        .logo-icon {
            width: 40px;
            height: 40px;
            background: var(--primary-navy);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .logo-icon i {
            font-size: 20px;
            color: white;
        }

        .logo-text {
            font-size: 22px;
            font-weight: 700;
            color: var(--primary-navy);
        }

        .profile-section {
            padding: 24px;
            text-align: center;
            border-bottom: 1px solid var(--gray-200);
        }

        .profile-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            margin: 0 auto 12px;
            background: linear-gradient(135deg, var(--primary-navy), var(--primary-blue));
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
        }

        .profile-avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .profile-section h5 {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 4px;
        }

        .profile-section p {
            font-size: 12px;
            color: var(--gray-500);
        }

        .nav-menu {
            padding: 16px;
        }

        .nav-item {
            margin-bottom: 4px;
        }

        .nav-link {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            border-radius: 12px;
            text-decoration: none;
            color: var(--gray-700);
            transition: var(--transition);
            font-weight: 500;
            font-size: 14px;
        }

        .nav-link i {
            width: 20px;
            font-size: 18px;
        }

        .nav-link:hover {
            background: var(--gray-100);
            color: var(--primary-blue);
        }

        .nav-link.active {
            background: var(--primary-navy);
            color: white;
        }

        .logout-section {
            padding: 16px;
            border-top: 1px solid var(--gray-200);
            margin-top: auto;
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: var(--white);
        }

        .logout-btn {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            border-radius: 12px;
            text-decoration: none;
            color: var(--error-red);
            font-weight: 500;
        }

        /* Main Content */
        .main-content {
            flex: 1;
            margin-left: 280px;
            min-height: 100vh;
        }

        .top-header {
            background: var(--white);
            border-bottom: 1px solid var(--gray-200);
            padding: 16px 32px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 99;
        }

        .page-title h1 {
            font-size: 24px;
            font-weight: 700;
            color: var(--gray-900);
        }

        .user-menu {
            display: flex;
            align-items: center;
            gap: 24px;
        }

        .notification-btn {
            background: none;
            border: none;
            font-size: 20px;
            color: var(--gray-600);
            cursor: pointer;
        }

        /* Content Area */
        .content-area {
            padding: 32px;
        }

        /* Card Styles - Modern Banking Design */
        .cards-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
            gap: 32px;
            margin-bottom: 32px;
        }

        /* Card Container with Flip Animation */
        .card-container {
            perspective: 1500px;
            cursor: pointer;
            width: 100%;
            max-width: 380px;
            margin: 0 auto;
        }

        .card {
            width: 100%;
            height: 240px;
            position: relative;
            transition: transform 0.6s cubic-bezier(0.23, 1, 0.32, 1);
            transform-style: preserve-3d;
        }

        .card-container:hover .card {
            transform: rotateY(180deg);
        }

        /* Front & Back */
        .card-front,
        .card-back {
            position: absolute;
            width: 100%;
            height: 100%;
            backface-visibility: hidden;
            border-radius: 24px;
            padding: 20px;
            box-shadow: var(--shadow-lg);
        }

        /* Front Side */
        .card-front {
            background: linear-gradient(135deg, #0a2540 0%, #1a4d8c 100%);
            transform: rotateY(0deg);
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        /* Back Side */
        .card-back {
            background: linear-gradient(135deg, #1a1f2e 0%, #2d2f3a 100%);
            transform: rotateY(180deg);
            border: 1px solid rgba(255, 255, 255, 0.05);
        }

        /* Chip Design */
        .chip {
            width: 45px;
            height: 35px;
            background: linear-gradient(135deg, #e0c87c, #b89a3a);
            border-radius: 8px;
            position: relative;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
        }

        .chip::before {
            content: '';
            position: absolute;
            top: 8px;
            left: 8px;
            width: 10px;
            height: 6px;
            background: rgba(0, 0, 0, 0.2);
            border-radius: 2px;
        }

        /* Contactless Symbol */
        .contactless {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 2px;
        }

        .contactless span {
            width: 24px;
            height: 2px;
            background: rgba(255, 255, 255, 0.5);
            border-radius: 2px;
        }

        .contactless span:nth-child(1) {
            width: 20px;
        }

        .contactless span:nth-child(2) {
            width: 16px;
        }

        .contactless span:nth-child(3) {
            width: 12px;
        }

        /* Card Number */
        .card-number {
            font-family: 'Courier New', monospace;
            font-size: 18px;
            letter-spacing: 2px;
            word-break: break-all;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
        }

        /* Magnetic Strip */
        .magnetic-strip {
            background: #000;
            height: 35px;
            width: 100%;
            margin-top: 15px;
            position: relative;
            overflow: hidden;
        }

        .magnetic-strip::after {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
            animation: shimmer 3s infinite;
        }

        @keyframes shimmer {
            100% {
                left: 100%;
            }
        }

        /* CVV Section */
        .cvv-section {
            background: #fff;
            color: #ffffffff;
            padding: 10px 16px;
            border-radius: 6px;
            margin-top: 12px;
            font-family: 'Courier New', monospace;
            font-size: 16px;
            letter-spacing: 2px;
            font-weight: bold;
            position: relative;
        }

        .cvv-section::before {
            content: 'CVV';
            position: absolute;
            left: 16px;
            top: -18px;
            font-size: 9px;
            color: rgba(255, 255, 255, 0.6);
            text-transform: uppercase;
        }

        /* Signature Area */
        .signature-area {
            margin-top: 12px;
            background: rgba(255, 255, 255, 0.9);
            height: 28px;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: flex-end;
            padding: 0 12px;
            font-size: 9px;
            color: #f0efefff;
            font-style: italic;
        }

        /* Card Details Inside Card */
        .card-details-row {
            display: flex;
            justify-content: space-between;
            margin-top: 15px;
        }

        .card-detail {
            flex: 1;
        }

        .card-detail-label {
            font-size: 9px;
            opacity: 0.7;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-bottom: 4px;
        }

        .card-detail-value {
            font-size: 13px;
            font-weight: 600;
        }

        /* Card Actions Below */
        .card-actions-wrapper {
            margin-top: 16px;
            padding-top: 16px;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
        }

        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 6px 14px;
            border-radius: 30px;
            font-size: 12px;
            font-weight: 600;
            margin-bottom: 12px;
        }

        .status-badge.active {
            background: rgba(46, 125, 50, 0.2);
            color: #2e7d32;
        }

        .status-badge.blocked {
            background: rgba(220, 53, 69, 0.2);
            color: #dc3545;
        }

        .status-badge.expired {
            background: rgba(243, 156, 18, 0.2);
            color: #f39c12;
        }

        .card-buttons {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
        }

        .card-btn {
            background: rgba(255, 255, 255, 0.1);
            border: none;
            color: white;
            padding: 8px 16px;
            border-radius: 10px;
            font-size: 13px;
            font-weight: 500;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            transition: var(--transition);
        }

        .card-btn:hover {
            background: rgba(255, 255, 255, 0.2);
        }

        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 60px;
            background: var(--white);
            border-radius: 24px;
            border: 1px solid var(--gray-200);
            grid-column: 1 / -1;
        }

        /* Table */
        .table-container {
            background: var(--white);
            border-radius: 20px;
            border: 1px solid var(--gray-200);
            overflow-x: auto;
            margin-top: 32px;
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            min-width: 600px;
        }

        .data-table th,
        .data-table td {
            padding: 16px 20px;
            text-align: left;
            border-bottom: 1px solid var(--gray-200);
        }

        .data-table th {
            background: var(--gray-50);
            font-weight: 600;
            font-size: 12px;
            color: var(--gray-600);
            text-transform: uppercase;
        }

        .data-table td {
            font-size: 13px;
        }

        .badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
        }

        .badge-success {
            background: rgba(46, 125, 50, 0.1);
            color: var(--success-green);
        }

        .badge-danger {
            background: rgba(220, 53, 69, 0.1);
            color: var(--error-red);
        }

        .badge-warning {
            background: rgba(243, 156, 18, 0.1);
            color: var(--warning-orange);
        }

        /* Modals */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }

        .modal.active {
            display: flex;
        }

        .modal-content {
            background: var(--white);
            border-radius: 24px;
            max-width: 500px;
            width: 100%;
            max-height: 90vh;
            overflow-y: auto;
        }

        .modal-header {
            padding: 20px 24px;
            border-bottom: 1px solid var(--gray-200);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-header h3 {
            font-size: 18px;
            font-weight: 600;
        }

        .modal-close {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: var(--gray-500);
        }

        .modal-body {
            padding: 24px;
        }

        .modal-footer {
            padding: 16px 24px;
            border-top: 1px solid var(--gray-200);
            display: flex;
            justify-content: flex-end;
            gap: 12px;
        }

        /* Forms */
        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            font-size: 13px;
            font-weight: 500;
            color: var(--gray-700);
            margin-bottom: 8px;
        }

        .form-group input,
        .form-group select {
            width: 100%;
            padding: 12px 16px;
            font-size: 14px;
            border: 1.5px solid var(--gray-200);
            border-radius: 12px;
            transition: var(--transition);
            outline: none;
        }

        .form-group input:focus,
        .form-group select:focus {
            border-color: var(--primary-blue);
            box-shadow: 0 0 0 3px rgba(26, 77, 140, 0.1);
        }

        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 16px;
        }

        .btn-primary {
            padding: 12px 24px;
            background: var(--primary-navy);
            color: white;
            border: none;
            border-radius: 12px;
            font-weight: 600;
            cursor: pointer;
            transition: var(--transition);
        }

        .btn-primary:hover {
            background: var(--primary-dark);
            transform: translateY(-1px);
        }

        .btn-secondary {
            padding: 12px 24px;
            background: var(--gray-100);
            color: var(--gray-700);
            border: none;
            border-radius: 12px;
            font-weight: 600;
            cursor: pointer;
        }

        .alert {
            padding: 14px 16px;
            border-radius: 12px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .alert-success {
            background: rgba(46, 125, 50, 0.1);
            border-left: 3px solid var(--success-green);
            color: var(--success-green);
        }

        .alert-danger {
            background: rgba(220, 53, 69, 0.1);
            border-left: 3px solid var(--error-red);
            color: var(--error-red);
        }

        .footer-note {
            margin-top: 20px;
            text-align: center;
            font-size: 12px;
            color: var(--gray-500);
        }

        /* Mobile Responsive */
        .hamburger {
            display: none;
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
        }

        @media (max-width: 1024px) {
            .sidebar {
                transform: translateX(-100%);
                z-index: 1000;
            }

            .sidebar.mobile-open {
                transform: translateX(0);
            }

            .main-content {
                margin-left: 0;
            }

            .hamburger {
                display: block;
            }
        }

        @media (max-width: 768px) {
            .content-area {
                padding: 20px;
            }

            .top-header {
                padding: 12px 20px;
            }

            .page-title h1 {
                font-size: 20px;
            }

            .cards-grid {
                grid-template-columns: 1fr;
                gap: 24px;
            }

            .card-container {
                max-width: 100%;
            }

            .card {
                height: 210px;
            }

            .card-number {
                font-size: 14px;
            }

            .chip {
                width: 38px;
                height: 30px;
            }

            .card-front,
            .card-back {
                padding: 16px;
            }

            .form-row {
                grid-template-columns: 1fr;
            }

            .request-btn {
                width: 100%;
                justify-content: center;
            }
        }

        @media (max-width: 480px) {
            .card {
                height: 190px;
            }

            .card-number {
                font-size: 12px;
                letter-spacing: 1px;
            }

            .card-detail-value {
                font-size: 11px;
            }

            .card-btn {
                padding: 6px 12px;
                font-size: 11px;
            }
        }
    </style>
    <link rel="stylesheet" href="../assets/css/nexus-theme.css">
</head>

<body>
    <div class="dashboard-wrapper">
        <!-- Sidebar -->
        <aside class="sidebar" id="sidebar">
            <div class="sidebar-header">
                <a href="dashboard.php" class="logo">
                    <div class="logo-icon"><i class="fas fa-building-columns"></i></div>
                    <span class="logo-text">Oakshire Finance</span>
                </a>
            </div>

            <div class="profile-section">
                <div class="profile-avatar">
                    <img src="<?= $profilePic ?>" alt="Profile Picture">
                </div>
                <h5><?= htmlspecialchars($user['full_name']) ?></h5>
                <p><?= htmlspecialchars($user['account_number']) ?></p>
            </div>

            <nav class="nav-menu">
                <div class="nav-item"><a href="dashboard.php" class="nav-link"><i class="fas fa-chart-line"></i>
                        Dashboard</a></div>
                <div class="nav-item"><a href="deposit.php" class="nav-link"><i class="fas fa-arrow-down"></i>
                        Deposit</a></div>
                <div class="nav-item"><a href="withdraw.php" class="nav-link"><i class="fas fa-arrow-up"></i>
                        Withdraw</a></div>

                <div class="nav-item"><a href="transactions.php" class="nav-link"><i class="fas fa-receipt"></i>
                        Transactions</a></div>
                <div class="nav-item"><a href="investment.php" class="nav-link"><i class="fas fa-chart-pie"></i>
                        Investment</a></div>
                <div class="nav-item"><a href="loan.php" class="nav-link"><i class="fas fa-hand-holding-usd"></i>
                        Loans</a></div>
                <div class="nav-item"><a href="cards.php" class="nav-link active"><i class="fas fa-credit-card"></i> My
                        Cards</a></div>
                <div class="nav-item"><a href="profile.php" class="nav-link"><i class="fas fa-user-circle"></i>
                        Settings</a></div>
            </nav>

            <div class="logout-section">
                <a href="../logout.php" class="logout-btn"><i class="fas fa-sign-out-alt"></i> Logout</a>
            </div>
        </aside>

        <!-- Main Content -->
        <main class="main-content">
            <header class="top-header">
                <button class="hamburger" id="hamburger"><i class="fas fa-bars"></i></button>
                <div class="page-title">
                    <h1>My Cards</h1>
                </div>
                <div class="user-menu">
                    <button class="notification-btn"><i class="fas fa-bell"></i></button>
                </div>
            </header>

            <div class="content-area">
                <?php if ($success): ?>
                    <div class="alert alert-success"><i class="fas fa-check-circle"></i> <?= $success ?></div>
                <?php endif; ?>
                <?php if ($error): ?>
                    <div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> <?= $error ?></div>
                <?php endif; ?>

                <!-- Request New Card Button -->
                <div style="margin-bottom: 32px; text-align: right;">
                    <button onclick="openRequestModal()" class="btn-primary">
                        <i class="fas fa-plus-circle"></i> Request New Card
                    </button>
                </div>

                <!-- Cards Grid -->
                <div class="cards-grid">
                    <?php if (empty($cards)): ?>
                        <div class="empty-state">
                            <i class="fas fa-credit-card"
                                style="font-size: 64px; color: var(--gray-400); margin-bottom: 16px; display: block;"></i>
                            <p style="color: var(--gray-500); margin-bottom: 20px;">You don't have any cards yet.</p>
                            <button onclick="openRequestModal()" class="btn-primary" style="margin-top: 0;">Request Your
                                First Card</button>
                        </div>
                    <?php else: ?>
                        <?php foreach ($cards as $card): ?>
                            <div class="card-container">
                                <div class="card">
                                    <!-- Front Side -->
                                    <div class="card-front">
                                        <div
                                            style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                                            <span class="text-white text-sm font-bold tracking-wider">Oakshire Finance</span>
                                            <div class="contactless">
                                                <span></span>
                                                <span></span>
                                                <span></span>
                                            </div>
                                        </div>

                                        <div class="chip"></div>

                                        <div class="card-number mt-3 mb-3">
                                            <?= formatCardNumber($card['card_number']) ?>
                                        </div>

                                        <div class="card-details-row">
                                            <div class="card-detail">
                                                <div class="card-detail-label">CARD HOLDER</div>
                                                <div class="card-detail-value">
                                                    <?= htmlspecialchars($card['card_holder_name']) ?></div>
                                            </div>
                                            <div class="card-detail text-right">
                                                <div class="card-detail-label">EXPIRES</div>
                                                <div class="card-detail-value">
                                                    <?= date('m/y', strtotime($card['expiry_date'])) ?></div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Back Side -->
                                    <div class="card-back">
                                        <div class="magnetic-strip"></div>
                                        <div class="cvv-section">
                                            <div class="flex justify-between items-center">
                                                <span class="text-gray-500 text-xs">***</span>
                                                <span class="text-gray-800 font-mono font-bold"><?= $card['cvv'] ?></span>
                                            </div>
                                        </div>
                                        <div class="signature-area">
                                            <span>Authorized Signature</span>
                                            <div
                                                style="width: 60px; height: 20px; background: #e0e0e0; margin-left: 8px; border-radius: 2px;">
                                            </div>
                                        </div>
                                        <div class="text-center mt-2">
                                            <p class="text-white text-opacity-40 text-[8px] uppercase tracking-wider">This card
                                                is issued by Oakshire Finance</p>
                                        </div>
                                    </div>
                                </div>

                                <!-- Card Status and Actions (Below the card) -->
                                <div class="card-actions-wrapper">
                                    <?= getCardStatusBadge($card['card_status']) ?>
                                    <div class="card-buttons">
                                        <?php if ($card['card_status'] === 'active'): ?>
                                            <form method="POST" style="display: inline;">
                                                <input type="hidden" name="action" value="block_card">
                                                <input type="hidden" name="card_id" value="<?= $card['card_id'] ?>">
                                                <button type="submit" class="card-btn"
                                                    onclick="return confirm('Are you sure you want to block this card?')">
                                                    <i class="fas fa-ban"></i> Block Card
                                                </button>
                                            </form>
                                        <?php elseif ($card['card_status'] === 'blocked'): ?>
                                            <form method="POST" style="display: inline;">
                                                <input type="hidden" name="action" value="unblock_card">
                                                <input type="hidden" name="card_id" value="<?= $card['card_id'] ?>">
                                                <button type="submit" class="card-btn"
                                                    onclick="return confirm('Unblock this card?')">
                                                    <i class="fas fa-check"></i> Unblock Card
                                                </button>
                                            </form>
                                        <?php endif; ?>
                                        <button
                                            onclick="openLimitModal(<?= $card['card_id'] ?>, <?= $card['daily_limit'] ?>, <?= $card['monthly_limit'] ?>, <?= $card['per_transaction_limit'] ?>)"
                                            class="card-btn">
                                            <i class="fas fa-sliders-h"></i> Update Limits
                                        </button>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>

                <!-- Recent Card Transactions -->
                <?php if (!empty($transactions)): ?>
                    <div class="table-container">
                        <div style="padding: 20px 24px; border-bottom: 1px solid var(--gray-200);">
                            <h3><i class="fas fa-history"></i> Recent Card Transactions</h3>
                        </div>
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Card</th>
                                    <th>Merchant</th>
                                    <th>Amount</th>
                                    <th>Status</th>
                            </thead>
                            <tbody>
                                <?php foreach ($transactions as $txn): ?>
                                    <tr>
                                        <td><?= date('M d, Y H:i', strtotime($txn['transaction_date'])) ?>54d
                                        <td>**** <?= substr($txn['card_number'], -4) ?>54d
                                        <td><?= htmlspecialchars($txn['merchant']) ?>54d
                                        <td
                                            style="font-weight: 600; color: <?= $txn['status'] === 'approved' ? '#2e7d32' : '#dc3545' ?>">
                                            $<?= number_format($txn['amount'], 2) ?>
                                            54d
                                        <td>
                                            <span
                                                class="badge <?= $txn['status'] === 'approved' ? 'badge-success' : 'badge-danger' ?>">
                                                <?= ucfirst($txn['status']) ?>
                                            </span>
                                            54d

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

                <div class="footer-note">
                    <i class="fas fa-lock"></i> Your card information is securely stored and encrypted.
                </div>
            </div>
        </main>
    </div>

    <!-- Request Card Modal -->
    <div id="requestModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3><i class="fas fa-credit-card"></i> Request New Card</h3>
                <button class="modal-close" onclick="closeRequestModal()">&times;</button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="request_card">
                <div class="modal-body">
                    <div class="form-group">
                        <label>Card Holder Name</label>
                        <input type="text" name="card_holder_name" value="<?= htmlspecialchars($user['full_name']) ?>"
                            required>
                        <small style="color: var(--gray-500); display: block; margin-top: 4px;">Name as it appears on
                            card</small>
                    </div>
                    <div class="form-group">
                        <label>Card Type</label>
                        <select name="card_type">
                            <option value="virtual">Virtual Card</option>
                            <option value="physical">Physical Card</option>
                        </select>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label>Daily Limit ($)</label>
                            <input type="number" name="daily_limit" step="0.01" value="50000" required>
                        </div>
                        <div class="form-group">
                            <label>Per Transaction Limit ($)</label>
                            <input type="number" name="per_transaction_limit" step="0.01" value="25000" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Monthly Limit ($)</label>
                        <input type="number" name="monthly_limit" step="0.01" value="500000" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-secondary" onclick="closeRequestModal()">Cancel</button>
                    <button type="submit" class="btn-primary">Request Card</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Limit Update Modal -->
    <div id="limitModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3><i class="fas fa-sliders-h"></i> Update Card Limits</h3>
                <button class="modal-close" onclick="closeLimitModal()">&times;</button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="update_limits">
                <input type="hidden" name="card_id" id="limit_card_id">
                <div class="modal-body">
                    <div class="form-group">
                        <label>Daily Limit ($)</label>
                        <input type="number" name="daily_limit" id="limit_daily" step="0.01" required>
                    </div>
                    <div class="form-group">
                        <label>Monthly Limit ($)</label>
                        <input type="number" name="monthly_limit" id="limit_monthly" step="0.01" required>
                    </div>
                    <div class="form-group">
                        <label>Per Transaction Limit ($)</label>
                        <input type="number" name="per_transaction_limit" id="limit_per_transaction" step="0.01"
                            required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-secondary" onclick="closeLimitModal()">Cancel</button>
                    <button type="submit" class="btn-primary">Save Changes</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // Mobile sidebar toggle
        const hamburger = document.getElementById('hamburger');
        const sidebar = document.getElementById('sidebar');
        if (hamburger) {
            hamburger.addEventListener('click', () => sidebar.classList.toggle('mobile-open'));
        }

        // Close sidebar when clicking outside
        document.addEventListener('click', (event) => {
            if (window.innerWidth <= 1024) {
                if (!sidebar.contains(event.target) && !hamburger.contains(event.target) && sidebar.classList.contains('mobile-open')) {
                    sidebar.classList.remove('mobile-open');
                }
            }
        });

        // Handle card flip on mobile (tap to flip)
        const cardContainers = document.querySelectorAll('.card-container');
        cardContainers.forEach(container => {
            let isFlipped = false;

            container.addEventListener('click', (e) => {
                if (window.innerWidth <= 768) {
                    e.stopPropagation();
                    const card = container.querySelector('.card');
                    if (card) {
                        if (isFlipped) {
                            card.style.transform = 'rotateY(0deg)';
                            isFlipped = false;
                        } else {
                            card.style.transform = 'rotateY(180deg)';
                            isFlipped = true;
                        }
                    }
                }
            });
        });

        // Request Card Modal
        const requestModal = document.getElementById('requestModal');
        function openRequestModal() { requestModal.classList.add('active'); }
        function closeRequestModal() { requestModal.classList.remove('active'); }

        // Limit Modal
        const limitModal = document.getElementById('limitModal');
        function openLimitModal(cardId, daily, monthly, perTransaction) {
            document.getElementById('limit_card_id').value = cardId;
            document.getElementById('limit_daily').value = daily;
            document.getElementById('limit_monthly').value = monthly;
            document.getElementById('limit_per_transaction').value = perTransaction;
            limitModal.classList.add('active');
        }
        function closeLimitModal() { limitModal.classList.remove('active'); }

        // Close modals when clicking outside
        window.onclick = function (event) {
            if (event.target === requestModal) closeRequestModal();
            if (event.target === limitModal) closeLimitModal();
        }

        // Auto-dismiss alerts
        const alerts = document.querySelectorAll('.alert');
        alerts.forEach(alert => {
            setTimeout(() => {
                alert.style.transition = 'opacity 0.3s ease';
                alert.style.opacity = '0';
                setTimeout(() => alert.remove(), 300);
            }, 5000);
        });
    </script>
</body>

</html>