<?php
// TEMPORARY: turn on errors to debug. Remove once working.
error_reporting(E_ALL);
ini_set('display_errors', 1);

$pageName  = "My Cards";
include($_SERVER['DOCUMENT_ROOT'] . "/user/layout/header.php");

require_once($_SERVER['DOCUMENT_ROOT'] . "/include/Function/cardFunction.php");

$user_id = userDetails('id');

// ============ HOLD CARD HANDLER ============
if (isset($_POST['hold_card']) && isset($_POST['card_id'])) {
    $status = 3;
    $card_id = (int) $_POST['card_id'];
    $sql2 = "UPDATE card SET card_status = :card_status WHERE id = :card_id AND user_id = :user_id";
    $stmt = $conn->prepare($sql2);
    $stmt->execute([
        'card_status' => $status,
        'card_id'     => $card_id,
        'user_id'     => $user_id
    ]);

    $msg1 = "<div class='alert alert-warning'>
                <script type='text/javascript'>
                    function Redirect() { window.location='./cards.php'; }
                    setTimeout('Redirect()', 3000);
                </script>
                <center><img src='../assets/images/loading.gif' width='180px'/></center>
                <center><strong style='color:black;'>Please wait while we validate your request...</strong></center>
             </div>";
}

// ============ ACTIVATE CARD HANDLER ============
if (isset($_POST['active_card']) && isset($_POST['card_id'])) {
    $status = 1;
    $card_id = (int) $_POST['card_id'];
    $sql2 = "UPDATE card SET card_status = :card_status WHERE id = :card_id AND user_id = :user_id";
    $stmt = $conn->prepare($sql2);
    $stmt->execute([
        'card_status' => $status,
        'card_id'     => $card_id,
        'user_id'     => $user_id
    ]);

    $msg1 = "<div class='alert alert-warning'>
                <script type='text/javascript'>
                    function Redirect() { window.location='./cards.php'; }
                    setTimeout('Redirect()', 3000);
                </script>
                <center><img src='../assets/images/loading.gif' width='180px'/></center>
                <center><strong style='color:black;'>Please wait while we validate your request...</strong></center>
             </div>";
}

// ============ FETCH USER CARDS ============
$cards = [];
try {
    $sqlCards = "SELECT * FROM card WHERE user_id = :user_id ORDER BY id DESC";
    $stmtCards = $conn->prepare($sqlCards);
    $stmtCards->execute(['user_id' => $user_id]);
    $cards = $stmtCards->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $cards = [];
}

// ============ FETCH CARD TRANSACTIONS COUNT ============
$totalTransactions = 0;
try {
    $sqlTx = "SELECT COUNT(*) as total FROM transactions WHERE user_id = :user_id AND trans_type = 'Card'";
    $stmtTx = $conn->prepare($sqlTx);
    $stmtTx->execute(['user_id' => $user_id]);
    $txCount = $stmtTx->fetch(PDO::FETCH_ASSOC);
    $totalTransactions = (int) ($txCount['total'] ?? 0);
} catch (Exception $e) {
    $totalTransactions = 0;
}

if (!function_exists('normalizeCardStatus')) {
    function normalizeCardStatus($raw) {
        if ($raw === null || $raw === '') return 0;
        if (is_numeric($raw)) {
            $n = (int) $raw;
            return ($n >= 0 && $n <= 4) ? $n : 0;
        }
        $label = strtolower(trim($raw));
        $map = [
            'pending'    => 0,
            'processing' => 2,
            'applied'    => 2,
            'active'     => 1,
            'approved'   => 1,
            'on hold'    => 3,
            'hold'       => 3,
            'held'       => 3,
            'rejected'   => 4,
            'declined'   => 4,
        ];
        return $map[$label] ?? 0;
    }
}

// ============ COUNT PENDING / ACTIVE / HELD ============
$pendingCount = 0;
$activeCount  = 0;
$heldCount    = 0;
foreach ($cards as $c) {
    $status = normalizeCardStatus($c['card_status'] ?? null);
    if ($status === 0 || $status === 2) $pendingCount++;
    elseif ($status === 1) $activeCount++;
    elseif ($status === 3) $heldCount++;
}

// Cardholder name (safe fallbacks)
$cardholderName = strtoupper(trim(($row['firstname'] ?? '') . ' ' . ($row['lastname'] ?? '')));
if (empty($cardholderName)) $cardholderName = 'CARDHOLDER';

if (!isset($currency)) $currency = '$';
if (!isset($acct_balance)) $acct_balance = 0;

if (!function_exists('getCardStatusMeta')) {
    function getCardStatusMeta($status) {
        $status = (int) $status;
        $map = [
            0 => ['label' => 'Pending',    'class' => 'bg-amber-50 text-amber-700 border-amber-200'],
            1 => ['label' => 'Active',     'class' => 'bg-green-50 text-green-700 border-green-200'],
            2 => ['label' => 'Processing', 'class' => 'bg-amber-50 text-amber-700 border-amber-200'],
            3 => ['label' => 'On Hold',    'class' => 'bg-red-50 text-red-700 border-red-200'],
            4 => ['label' => 'Rejected',   'class' => 'bg-red-50 text-red-700 border-red-200'],
        ];
        return $map[$status] ?? $map[0];
    }
}

if (!function_exists('maskCardNumber')) {
    function maskCardNumber($number) {
        if (empty($number)) return '•••• •••• •••• ••••';
        $stripped = preg_replace('/\s+/', '', $number);
        if (strlen($stripped) < 4) return '•••• •••• •••• ••••';
        $last4 = substr($stripped, -4);
        return '•••• •••• •••• ' . $last4;
    }
}

if (!function_exists('formatCardNumber')) {
    function formatCardNumber($number) {
        if (empty($number)) return '•••• •••• •••• ••••';
        $stripped = preg_replace('/\s+/', '', $number);
        return implode(' ', str_split($stripped, 4));
    }
}
?>
<!-- Main Content Area -->
<main class="pt-10 md:pt-14 pb-24 md:pb-8 min-h-screen lg:ml-80 bg-slate-50">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        <div class="space-y-6" x-data="{ showHoldModal: false, showActivateModal: false, showDetailsModal: false, selectedCard: null, cardDetails: {} }">

    <?php if (!empty($msg1)): ?>
        <div class="mb-4"><?= $msg1 ?></div>
    <?php endif; ?>

    <!-- Header -->
    <div class="flex items-center justify-between">
        <div>
            <h1 class="text-2xl md:text-3xl font-semibold text-slate-900">Virtual Cards</h1>
            <p class="text-sm text-slate-500 mt-1">Manage your virtual debit cards</p>
        </div>
        <a href="<?= $web_url ?>/user/apply.php"
           class="inline-flex items-center space-x-2 px-5 py-2.5 rounded-lg bg-primary-500 hover:bg-primary-600 transition-colors text-sm font-medium text-white">
            <i data-lucide="plus" class="w-4 h-4"></i>
            <span>Apply for Card</span>
        </a>
    </div>

    <!-- Stats -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-3">
        <div class="bg-white border border-slate-200 shadow-sm rounded-xl p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-xs text-slate-500">Total Balance</p>
                    <h3 class="text-xl font-semibold text-slate-900 mt-1"><?= $currency ?><?= number_format($acct_balance, 2, '.', ',') ?></h3>
                </div>
                <div class="w-9 h-9 rounded-lg bg-primary-50 flex items-center justify-center border border-primary-200">
                    <i data-lucide="wallet" class="w-4 h-4 text-primary-500"></i>
                </div>
            </div>
        </div>

        <div class="bg-white border border-slate-200 shadow-sm rounded-xl p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-xs text-slate-500">Total Transactions</p>
                    <h3 class="text-xl font-semibold text-slate-900 mt-1"><?= $totalTransactions ?></h3>
                </div>
                <div class="w-9 h-9 rounded-lg bg-primary-50 flex items-center justify-center border border-primary-200">
                    <i data-lucide="activity" class="w-4 h-4 text-primary-500"></i>
                </div>
            </div>
        </div>

        <div class="bg-white border border-slate-200 shadow-sm rounded-xl p-4">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-xs text-slate-500">Pending Applications</p>
                    <h3 class="text-xl font-semibold text-slate-900 mt-1"><?= $pendingCount ?></h3>
                </div>
                <div class="w-9 h-9 rounded-lg bg-amber-50 flex items-center justify-center border border-amber-200">
                    <i data-lucide="clock" class="w-4 h-4 text-amber-600"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- Cards -->
    <?php if (empty($cards)): ?>
        <div class="bg-white border border-slate-200 shadow-sm rounded-xl p-12 text-center">
            <div class="w-16 h-16 rounded-2xl bg-primary-50 flex items-center justify-center mx-auto mb-4 border border-primary-200">
                <i data-lucide="credit-card" class="w-8 h-8 text-primary-500"></i>
            </div>
            <h3 class="text-lg font-semibold text-slate-900 mb-1">No cards yet</h3>
            <p class="text-sm text-slate-500 mb-5">Apply for your first virtual debit card to get started.</p>
            <a href="<?= $web_url ?>/user/apply.php"
               class="inline-flex items-center space-x-2 px-5 py-2.5 rounded-lg bg-primary-500 hover:bg-primary-600 transition-colors text-sm font-medium text-white">
                <i data-lucide="plus" class="w-4 h-4"></i>
                <span>Apply for Card</span>
            </a>
        </div>
    <?php else: ?>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
            <?php foreach ($cards as $card):
                $cardId       = $card['id'] ?? 0;
                $cardStatus   = normalizeCardStatus($card['card_status'] ?? null);
                $cardLevel    = $card['card_level'] ?? ($card['card_name'] ?? 'Classic');
                $cardType     = $card['card_type'] ?? 'Visa';
                $cardNumber   = $card['card_number'] ?? '';
                $cardExpiry   = $card['card_expiration'] ?? ($card['card_expiry'] ?? '');
                $cardCvv      = $card['card_security']   ?? ($card['card_cvv'] ?? '');
                $cardBalance  = (float) ($card['card_balance'] ?? 0);
                $cardLimit    = (float) ($card['card_limit'] ?? 0);
                $cardLimitRemain = (float) ($card['card_limit_remain'] ?? 0);
                $cardCreated  = $card['created_at'] ?? date('Y-m-d');
                $cardHolderDB = $card['cardholder_name'] ?? $cardholderName;
                $billingAddr  = $card['billing_address'] ?? '';
                $billingCity  = $card['billing_city'] ?? '';
                $billingZip   = $card['billing_zipcode'] ?? '';
                $billingCountry = $card['billing_country'] ?? '';

                $statusMeta = getCardStatusMeta($cardStatus);
                $isActive   = ($cardStatus === 1);
                $isHeld     = ($cardStatus === 3);
                $isPending  = (!$isActive && !$isHeld);

                $detailsJson = htmlspecialchars(json_encode([
                    'id'             => $cardId,
                    'cardName'       => $cardLevel . ' ' . $cardType,
                    'cardLevel'      => $cardLevel,
                    'cardType'       => $cardType,
                    'cardNumber'     => formatCardNumber($cardNumber),
                    'maskedNumber'   => maskCardNumber($cardNumber),
                    'expiry'         => $cardExpiry,
                    'cvv'            => $cardCvv,
                    'balance'        => $currency . number_format($cardBalance, 2, '.', ','),
                    'limit'          => $currency . number_format($cardLimit, 2, '.', ','),
                    'limitRemain'    => $currency . number_format($cardLimitRemain, 2, '.', ','),
                    'cardholder'     => strtoupper($cardHolderDB),
                    'billingAddress' => $billingAddr,
                    'billingCity'    => $billingCity,
                    'billingZip'     => $billingZip,
                    'billingCountry' => $billingCountry,
                    'created'        => date('M d, Y', strtotime($cardCreated)),
                    'statusLabel'    => $statusMeta['label'],
                    'statusClass'    => $statusMeta['class'],
                ]), ENT_QUOTES, 'UTF-8');
            ?>
                <div class="group" x-data="{ flipped: false }">
                    <div class="relative h-56 perspective-1000">
                        <div class="relative w-full h-full transition-transform duration-700 transform-style-preserve-3d" :class="flipped ? 'rotate-y-180' : ''">

                            <!-- Front -->
                            <div class="absolute w-full h-full backface-hidden">
                                <div class="h-full rounded-xl p-5 text-white relative overflow-hidden bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 border border-slate-700 <?= $isHeld ? 'opacity-70' : '' ?>">
                                    <div class="relative flex justify-between items-start">
                                        <div>
                                            <?php if ($cardType === 'Mastercard'): ?>
                                            <svg class="h-5 w-9 mb-1.5" viewBox="0 0 152 100" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <circle cx="50" cy="50" r="48" fill="#EB001B" opacity="0.9"/>
                                                <circle cx="102" cy="50" r="48" fill="#F79E1B" opacity="0.9"/>
                                                <path d="M76 15.7C67.1 22.5 61 32.9 61 44.7C61 56.5 67.1 66.9 76 73.7C84.9 66.9 91 56.5 91 44.7C91 32.9 84.9 22.5 76 15.7Z" fill="#FF5F00"/>
                                            </svg>
                                            <?php else: ?>
                                            <svg class="h-5 w-9 mb-1.5" viewBox="0 0 1000 324" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <path d="M433.334 318.516H348.568L403.315 5.01855H488.081L433.334 318.516Z" fill="white"/>
                                                <path d="M727.98 15.9043C712.039 9.56622 686.227 2.51855 653.355 2.51855C574.054 2.51855 519.055 45.5277 518.802 106.826C518.306 152.343 558.126 177.912 587.98 193.316C618.34 209.233 629.315 219.335 629.315 233.014C629.061 254.008 603.493 263.591 579.702 263.591C547.839 263.591 530.7 258.287 505.123 245.892L493.902 240.335L482.166 313.221C501.069 323.07 536.096 331.667 572.643 332.163C657.14 332.163 711.128 289.897 711.895 224.144C712.394 188.508 689.871 160.445 643.015 136.91C615.2 121.744 598.306 111.638 598.554 97.2356C598.554 84.5987 613.224 70.9167 648.747 70.9167C677.823 70.4206 699.053 77.7188 715.707 85.5144L726.681 90.8186L738.417 19.9214L727.98 15.9043Z" fill="white"/>
                                                <path fill-rule="evenodd" clip-rule="evenodd" d="M841.897 5.01855H773.691C755.782 5.01855 742.397 10.0624 734.862 30.0238L630.236 318.516H715.464C715.464 318.516 729.143 280.806 732.429 272.002C742.901 272.002 822.706 272.002 835.844 272.002C838.373 283.215 845.93 318.516 845.93 318.516H922.667L841.897 5.01855ZM762.22 208.49C769.018 189.752 796.85 116.686 796.85 116.686C796.602 117.174 803.16 99.19 806.699 88.0899L812.02 114.188C812.02 114.188 829.775 192.026 833.061 208.49H762.22Z" fill="white"/>
                                                <path d="M251.994 5.01855L171.471 219.335L162.137 174.313C146.216 129.054 102.175 80.0894 52.8662 56.8035L126.462 318.02H212.215L336.832 5.01855H251.994Z" fill="white"/>
                                                <path d="M127.963 5.01855H0.66211L0.167969 10.3101C98.1497 31.7971 163.301 76.5646 190.132 129.298L162.633 13.5747C157.329 -0.60098 144.316 5.51465 127.963 5.01855Z" fill="white"/>
                                            </svg>
                                            <?php endif; ?>
                                            <p class="text-[10px] opacity-50"><?= htmlspecialchars($cardLevel) ?></p>
                                        </div>
                                        <div class="flex gap-2">
                                            <span class="<?= $statusMeta['class'] ?> border px-2 py-0.5 rounded text-[10px] font-medium">
                                                <?= $statusMeta['label'] ?>
                                            </span>
                                            <?php if ($isActive && $cardNumber): ?>
                                                <button type="button" @click="flipped = !flipped" class="bg-white/10 hover:bg-white/20 border border-white/20 w-6 h-6 rounded flex items-center justify-center transition-colors">
                                                    <i data-lucide="repeat" class="w-3 h-3 text-white"></i>
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                    </div>

                                    <div class="relative mt-6">
                                        <?php if ($isActive && $cardNumber): ?>
                                            <p class="text-base font-medium tracking-wider font-mono"><?= maskCardNumber($cardNumber) ?></p>
                                        <?php elseif ($isHeld): ?>
                                            <p class="text-sm text-white/40">Card is currently on hold</p>
                                        <?php else: ?>
                                            <p class="text-sm text-white/40">Card details pending approval</p>
                                        <?php endif; ?>
                                    </div>

                                    <div class="relative mt-auto pt-3 flex justify-between items-end">
                                        <div>
                                            <p class="text-[10px] opacity-50">Cardholder</p>
                                            <p class="font-medium text-xs truncate max-w-[160px]"><?= htmlspecialchars(strtoupper($cardHolderDB)) ?></p>
                                        </div>
                                        <?php if ($isActive && !empty($cardExpiry)): ?>
                                            <div class="text-right">
                                                <p class="text-[10px] opacity-50">Expires</p>
                                                <p class="font-medium text-xs"><?= htmlspecialchars($cardExpiry) ?></p>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>

                            <!-- Back -->
                            <div class="absolute w-full h-full backface-hidden rotate-y-180">
                                <div class="h-full rounded-xl bg-slate-800 border border-slate-700/50 text-white relative overflow-hidden">
                                    <div class="bg-slate-900 h-10 mt-5"></div>
                                    <div class="p-5">
                                        <div class="bg-white text-gray-800 px-3 py-1.5 rounded text-right mb-3">
                                            <span class="text-xs font-mono"><?= htmlspecialchars($cardCvv ?: '---') ?></span>
                                        </div>
                                        <p class="text-[10px] text-gray-500 mb-3">For security, keep this CVV private</p>
                                        <div class="text-[10px] text-gray-500 space-y-0.5">
                                            <p>Card Level: <?= htmlspecialchars($cardLevel) ?></p>
                                            <p>Issued: <?= date('M Y', strtotime($cardCreated)) ?></p>
                                            <?php if ($isActive): ?>
                                                <p>Balance: <?= $currency ?><?= number_format($cardBalance, 2, '.', ',') ?></p>
                                            <?php endif; ?>
                                            <button type="button" @click="flipped = false" class="mt-2 text-primary-400 hover:text-primary-300 hover:underline">← Back to front</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Actions -->
                    <div class="mt-3 grid grid-cols-2 gap-2">
                        <?php if ($isActive): ?>
                            <button type="button"
                                @click="cardDetails = <?= $detailsJson ?>; showDetailsModal = true;"
                                class="bg-primary-50 hover:bg-primary-100 border border-primary-200 text-primary-700 px-3 py-2 rounded-lg text-xs font-medium transition-colors flex items-center justify-center gap-1">
                                <i data-lucide="eye" class="w-3.5 h-3.5"></i>
                                View Details
                            </button>
                            <button type="button" @click="selectedCard = <?= $cardId ?>; showHoldModal = true"
                                class="bg-red-50 hover:bg-red-100 border border-red-200 text-red-600 px-3 py-2 rounded-lg text-xs font-medium transition-colors flex items-center justify-center gap-1">
                                <i data-lucide="pause-circle" class="w-3.5 h-3.5"></i>
                                Hold Card
                            </button>
                        <?php elseif ($isHeld): ?>
                            <button type="button" @click="selectedCard = <?= $cardId ?>; showActivateModal = true"
                                class="col-span-2 bg-green-50 hover:bg-green-100 border border-green-200 text-green-600 px-3 py-2 rounded-lg text-xs font-medium transition-colors flex items-center justify-center gap-1">
                                <i data-lucide="play-circle" class="w-3.5 h-3.5"></i>
                                Reactivate Card
                            </button>
                        <?php else: ?>
                            <div class="col-span-2 bg-amber-50 border border-amber-200 text-amber-700 px-3 py-2 rounded-lg text-xs text-center">
                                <i data-lucide="clock" class="w-3.5 h-3.5 inline mr-1"></i>
                                Awaiting approval
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <!-- Card Details Modal -->
    <div x-show="showDetailsModal" x-cloak class="fixed inset-0 bg-black/60 z-50 flex items-center justify-center p-4" @click.self="showDetailsModal = false">
        <div class="bg-white border border-slate-200 shadow-xl rounded-xl max-w-md w-full overflow-hidden" @keydown.escape.window="showDetailsModal = false">

            <!-- Modal Header -->
            <div class="bg-gradient-to-br from-primary-600 to-primary-800 text-white px-5 py-4 flex items-center justify-between">
                <div class="flex items-center gap-3">
                    <div class="w-9 h-9 rounded-lg bg-white/15 flex items-center justify-center">
                        <i data-lucide="credit-card" class="w-4 h-4 text-white"></i>
                    </div>
                    <div>
                        <h3 class="text-sm font-semibold" x-text="cardDetails.cardName"></h3>
                        <p class="text-[10px] text-white/60" x-text="'Issued ' + cardDetails.created"></p>
                    </div>
                </div>
                <button type="button" @click="showDetailsModal = false" class="text-white/60 hover:text-white transition-colors">
                    <i data-lucide="x" class="w-5 h-5"></i>
                </button>
            </div>

            <!-- Modal Body -->
            <div class="p-5 space-y-4">

                <!-- Status Badge -->
                <div class="flex items-center justify-between">
                    <span class="text-xs text-slate-500">Status</span>
                    <span class="border px-2.5 py-0.5 rounded text-[11px] font-medium" :class="cardDetails.statusClass" x-text="cardDetails.statusLabel"></span>
                </div>

                <!-- Card Number -->
                <div x-data="{ showNumber: false }">
                    <p class="text-xs text-slate-500 mb-1">Card Number</p>
                    <div class="flex items-center justify-between bg-slate-50 border border-slate-200 rounded-lg px-3.5 py-2.5">
                        <span class="font-mono text-sm text-slate-900 tracking-wider" x-text="showNumber ? cardDetails.cardNumber : cardDetails.maskedNumber"></span>
                        <button type="button" @click="showNumber = !showNumber" class="text-primary-600 hover:text-primary-700 transition-colors ml-2">
                            <i x-show="!showNumber" data-lucide="eye" class="w-4 h-4"></i>
                            <i x-show="showNumber" data-lucide="eye-off" class="w-4 h-4"></i>
                        </button>
                    </div>
                </div>

                <!-- Expiry & CVV Row -->
                <div class="grid grid-cols-2 gap-3">
                    <div>
                        <p class="text-xs text-slate-500 mb-1">Expiry Date</p>
                        <div class="bg-slate-50 border border-slate-200 rounded-lg px-3.5 py-2.5">
                            <span class="font-mono text-sm text-slate-900" x-text="cardDetails.expiry"></span>
                        </div>
                    </div>
                    <div x-data="{ showCvv: false }">
                        <p class="text-xs text-slate-500 mb-1">CVV</p>
                        <div class="flex items-center justify-between bg-slate-50 border border-slate-200 rounded-lg px-3.5 py-2.5">
                            <span class="font-mono text-sm text-slate-900" x-text="showCvv ? cardDetails.cvv : '•••'"></span>
                            <button type="button" @click="showCvv = !showCvv" class="text-primary-600 hover:text-primary-700 transition-colors ml-2">
                                <i x-show="!showCvv" data-lucide="eye" class="w-3.5 h-3.5"></i>
                                <i x-show="showCvv" data-lucide="eye-off" class="w-3.5 h-3.5"></i>
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Cardholder -->
                <div>
                    <p class="text-xs text-slate-500 mb-1">Cardholder Name</p>
                    <div class="bg-slate-50 border border-slate-200 rounded-lg px-3.5 py-2.5">
                        <span class="text-sm text-slate-900 font-medium" x-text="cardDetails.cardholder"></span>
                    </div>
                </div>

                <!-- Balance & Limits -->
                <div class="grid grid-cols-3 gap-3">
                    <div class="bg-slate-50 border border-slate-200 rounded-lg px-3 py-2.5 text-center">
                        <p class="text-[10px] text-slate-500 mb-0.5">Balance</p>
                        <p class="text-sm font-semibold text-slate-900" x-text="cardDetails.balance"></p>
                    </div>
                    <div class="bg-slate-50 border border-slate-200 rounded-lg px-3 py-2.5 text-center">
                        <p class="text-[10px] text-slate-500 mb-0.5">Limit</p>
                        <p class="text-sm font-semibold text-slate-900" x-text="cardDetails.limit"></p>
                    </div>
                    <div class="bg-slate-50 border border-slate-200 rounded-lg px-3 py-2.5 text-center">
                        <p class="text-[10px] text-slate-500 mb-0.5">Remaining</p>
                        <p class="text-sm font-semibold text-slate-900" x-text="cardDetails.limitRemain"></p>
                    </div>
                </div>

                <!-- Billing Address -->
                <div x-show="cardDetails.billingAddress">
                    <p class="text-xs text-slate-500 mb-1">Billing Address</p>
                    <div class="bg-slate-50 border border-slate-200 rounded-lg px-3.5 py-2.5">
                        <p class="text-sm text-slate-900">
                            <span x-text="cardDetails.billingAddress"></span><template x-if="cardDetails.billingCity"><span x-text="', ' + cardDetails.billingCity"></span></template><template x-if="cardDetails.billingZip"><span x-text="' ' + cardDetails.billingZip"></span></template><template x-if="cardDetails.billingCountry"><span x-text="', ' + cardDetails.billingCountry"></span></template>
                        </p>
                    </div>
                </div>

            </div>

            <!-- Modal Footer -->
            <div class="px-5 pb-5">
                <button type="button" @click="showDetailsModal = false"
                        class="w-full bg-slate-100 hover:bg-slate-200 text-slate-700 py-2.5 rounded-lg text-sm font-medium transition-colors">Close</button>
            </div>
        </div>
    </div>

    <!-- Hold Modal -->
    <div x-show="showHoldModal" x-cloak class="fixed inset-0 bg-black/60 z-50 flex items-center justify-center p-4" @click.self="showHoldModal = false">
        <div class="bg-white border border-slate-200 shadow-xl rounded-xl max-w-md w-full p-5">
            <div class="flex items-center gap-3 mb-4">
                <div class="w-10 h-10 rounded-lg bg-red-50 border border-red-200 flex items-center justify-center">
                    <i data-lucide="pause-circle" class="w-5 h-5 text-red-500"></i>
                </div>
                <h3 class="text-lg font-semibold text-slate-900">Hold Card?</h3>
            </div>
            <p class="text-sm text-slate-600 mb-5">This will temporarily disable your card. You can reactivate it at any time.</p>
            <form method="POST">
                <input type="hidden" name="card_id" :value="selectedCard">
                <div class="flex gap-3">
                    <button type="button" @click="showHoldModal = false"
                            class="flex-1 bg-slate-100 hover:bg-slate-200 text-slate-700 py-2.5 rounded-lg text-sm font-medium transition-colors">Cancel</button>
                    <button type="submit" name="hold_card"
                            class="flex-1 bg-red-500 hover:bg-red-600 text-white py-2.5 rounded-lg text-sm font-medium transition-colors">Yes, Hold Card</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Activate Modal -->
    <div x-show="showActivateModal" x-cloak class="fixed inset-0 bg-black/60 z-50 flex items-center justify-center p-4" @click.self="showActivateModal = false">
        <div class="bg-white border border-slate-200 shadow-xl rounded-xl max-w-md w-full p-5">
            <div class="flex items-center gap-3 mb-4">
                <div class="w-10 h-10 rounded-lg bg-green-50 border border-green-200 flex items-center justify-center">
                    <i data-lucide="play-circle" class="w-5 h-5 text-green-500"></i>
                </div>
                <h3 class="text-lg font-semibold text-slate-900">Reactivate Card?</h3>
            </div>
            <p class="text-sm text-slate-600 mb-5">Your card will be active again and ready to use for transactions.</p>
            <form method="POST">
                <input type="hidden" name="card_id" :value="selectedCard">
                <div class="flex gap-3">
                    <button type="button" @click="showActivateModal = false"
                            class="flex-1 bg-slate-100 hover:bg-slate-200 text-slate-700 py-2.5 rounded-lg text-sm font-medium transition-colors">Cancel</button>
                    <button type="submit" name="active_card"
                            class="flex-1 bg-green-500 hover:bg-green-600 text-white py-2.5 rounded-lg text-sm font-medium transition-colors">Yes, Reactivate</button>
                </div>
            </form>
        </div>
    </div>

</div>

<style>
    [x-cloak] { display: none !important; }
    .perspective-1000 { perspective: 1000px; }
    .transform-style-preserve-3d { transform-style: preserve-3d; }
    .backface-hidden { backface-visibility: hidden; }
    .rotate-y-180 { transform: rotateY(180deg); }
</style>

<script>
    lucide.createIcons();
    document.addEventListener('alpine:init', () => {
        Alpine.effect(() => {
            setTimeout(() => lucide.createIcons(), 0);
        });
    });
</script>

        </div>
    </main>

<?php
include($_SERVER['DOCUMENT_ROOT'] . "/user/layout/footer.php");
?>