<?php
require_once 'includes/config.php';
require_once 'includes/telegram.php';
require_once 'includes/commission.php';
requireLogin();
require_once 'includes/service_check.php';
checkServiceEnabled('cards');
$user = getCurrentUser();
$db   = getDB();

// Ensure tables exist
try {
    $db->exec("CREATE TABLE IF NOT EXISTS card_categories (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, icon VARCHAR(20) DEFAULT '🎴', color VARCHAR(20) DEFAULT '#1a3c8f', description TEXT, image VARCHAR(255) DEFAULT NULL, sort_order INT DEFAULT 0, is_active TINYINT(1) DEFAULT 1, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
    $db->exec("CREATE TABLE IF NOT EXISTS cards (id INT AUTO_INCREMENT PRIMARY KEY, category_id INT NOT NULL, name VARCHAR(200) NOT NULL, description TEXT, image VARCHAR(255) DEFAULT NULL, price DECIMAL(10,2) NOT NULL DEFAULT 0, original_price DECIMAL(10,2) DEFAULT NULL, commission DECIMAL(10,2) DEFAULT 0, validity VARCHAR(100) DEFAULT NULL, region VARCHAR(100) DEFAULT NULL, stock INT DEFAULT 0, is_active TINYINT(1) DEFAULT 1, sort_order INT DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
    try { $db->exec("ALTER TABLE cards ADD COLUMN commission DECIMAL(10,2) DEFAULT 0 AFTER original_price"); } catch(Exception $e) {}
    $db->exec("CREATE TABLE IF NOT EXISTS card_pins (id INT AUTO_INCREMENT PRIMARY KEY, card_id INT NOT NULL, pin_code VARCHAR(500) NOT NULL, serial_number VARCHAR(200) DEFAULT NULL, extra_info TEXT DEFAULT NULL, status ENUM('available','sold','reserved') DEFAULT 'available', sold_to INT DEFAULT NULL, sold_at TIMESTAMP NULL, order_id INT DEFAULT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
    $db->exec("CREATE TABLE IF NOT EXISTS card_favorites (id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, card_id INT NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY unique_fav (user_id, card_id))");
    $db->exec("CREATE TABLE IF NOT EXISTS card_orders (id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, card_id INT NOT NULL, pin_id INT DEFAULT NULL, quantity INT DEFAULT 1, unit_price DECIMAL(10,2) NOT NULL, total_price DECIMAL(10,2) NOT NULL, commission_amount DECIMAL(10,2) DEFAULT 0, balance_before DECIMAL(10,2), balance_after DECIMAL(10,2), reference VARCHAR(50), status ENUM('pending','completed','failed','refunded') DEFAULT 'pending', note TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
} catch(Exception $e) {}

$error = ''; $successData = null;

// Handle favorite toggle
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['fav_card_id'])) {
    $favId = intval($_POST['fav_card_id']);
    try {
        $exists = $db->prepare("SELECT id FROM card_favorites WHERE user_id=? AND card_id=?");
        $exists->execute([$user['id'], $favId]);
        if ($exists->fetch()) {
            $db->prepare("DELETE FROM card_favorites WHERE user_id=? AND card_id=?")->execute([$user['id'], $favId]);
            echo json_encode(['ok'=>true,'fav'=>false]); exit;
        } else {
            $db->prepare("INSERT IGNORE INTO card_favorites (user_id,card_id) VALUES (?,?)")->execute([$user['id'], $favId]);
            echo json_encode(['ok'=>true,'fav'=>true]); exit;
        }
    } catch(Exception $e) { echo json_encode(['ok'=>false]); exit; }
}

// Handle purchase
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['buy_card_id'])) {
    $cardId = intval($_POST['buy_card_id']);

    $card = $db->prepare("SELECT c.*, cc.name as cat_name FROM cards c JOIN card_categories cc ON c.category_id=cc.id WHERE c.id=? AND c.is_active=1");
    $card->execute([$cardId]); $card = $card->fetch();

    if (!$card) { $error = 'Card not found!'; }
    elseif ($user['balance'] < $card['price']) { $error = 'Insufficient balance! Need: ৳'.number_format($card['price'],2); }
    else {
        // Get available PIN
        $pinRow = $db->prepare("SELECT * FROM card_pins WHERE card_id=? AND status='available' ORDER BY id ASC LIMIT 1");
        $pinRow->execute([$cardId]); $pin = $pinRow->fetch();

        if (!$pin) { $error = 'Out of stock! Please try again later.'; }
        else {
            $ref = 'CD'.strtoupper(substr(md5(uniqid()),0,8));
            $balBefore = $user['balance'];
            $balAfter  = $balBefore - $card['price'];

            $db->beginTransaction();
            try {
                // Deduct balance
                $db->prepare("UPDATE users SET balance=balance-? WHERE id=?")->execute([$card['price'],$user['id']]);
                // Mark PIN sold
                $db->prepare("UPDATE card_pins SET status='sold', sold_to=?, sold_at=NOW() WHERE id=?")->execute([$user['id'],$pin['id']]);
                // Update stock
                $db->prepare("UPDATE cards SET stock=stock-1 WHERE id=? AND stock>0")->execute([$cardId]);
                // Create order
                $db->prepare("INSERT INTO card_orders (user_id,card_id,pin_id,unit_price,total_price,balance_before,balance_after,reference,status) VALUES (?,?,?,?,?,?,?,?,'completed')")->execute([$user['id'],$cardId,$pin['id'],$card['price'],$card['price'],$balBefore,$balAfter,$ref]);
                $orderId = $db->lastInsertId();
                // Update pin with order id
                $db->prepare("UPDATE card_pins SET order_id=? WHERE id=?")->execute([$orderId,$pin['id']]);
                // Save to transactions (for history)
                $db->prepare("INSERT INTO transactions (user_id,type,amount,charge,net_amount,balance_before,balance_after,reference,status,note) VALUES (?,?,?,0,?,?,?,?,?,?)")
                   ->execute([$user['id'],'card',$card['price'],$card['price'],$balBefore,$balAfter,$ref,'success',$ref]);
                // Commission (1 sec later so it shows after card in history)
                $cardCommBase = floatval($card['commission'] ?? 0);
                $commAmt = applyCommission($db, $user['id'], 'card', $card['price'], $ref, $cardCommBase ?: null);
                // Fix commission created_at to be 1 second after card
                $db->prepare("UPDATE transactions SET created_at=DATE_ADD(created_at, INTERVAL 1 SECOND) WHERE user_id=? AND type='commission' AND note LIKE ? ORDER BY id DESC LIMIT 1")
                   ->execute([$user['id'], '%'.$ref.'%']);
                // Notification
                $db->prepare("INSERT INTO notifications (user_id,title,message,type) VALUES (?,?,?,'success')")->execute([$user['id'],'🎴 Card Purchased!',$card['name'].' — Ref: '.$ref]);
                $db->commit();

                // Notify user telegram
                $tgDetails = ['📦 Card'=>$card['name'], '💰 Price'=>'৳'.number_format($card['price'],2), '🔖 Ref'=>$ref];
                if($commAmt>0) $tgDetails['💸 Commission'] = '+৳'.number_format($commAmt,2);
                notifyUser($user['id'], 'Card কেনা সফল! 🎴', $tgDetails);

                $successData = [
                    'card_name'  => $card['name'],
                    'pin_code'   => $pin['pin_code'],
                    'serial'     => $pin['serial_number'],
                    'extra'      => $pin['extra_info'],
                    'ref'        => $ref,
                    'price'      => $card['price'],
                    'validity'   => $card['validity'],
                    'commission' => $commAmt,
                ];
                $user = getCurrentUser();
            } catch(Exception $e) { $db->rollBack(); $error = 'Error: '.$e->getMessage(); }
        }
    }
}

// User currency
$_card_uc = null;
try {
    $s = $db->prepare("SELECT c.* FROM users u JOIN currencies c ON u.preferred_currency=c.code WHERE u.id=? AND c.is_active=1 AND c.code<>'BDT'");
    $s->execute([$user['id']]);
    $_card_uc = $s->fetch() ?: null;
} catch(Exception $e) {}

// Load categories
$categories = $db->query("SELECT * FROM card_categories WHERE is_active=1 ORDER BY sort_order,id")->fetchAll();
// Load cards with stock
$cards = $db->query("SELECT c.*, cc.name as cat_name, cc.icon as cat_icon, cc.color as cat_color FROM cards c JOIN card_categories cc ON c.category_id=cc.id WHERE c.is_active=1 ORDER BY c.category_id, c.sort_order, c.id")->fetchAll();
// My favorites
$favIds = [];
try {
    $favRows = $db->prepare("SELECT card_id FROM card_favorites WHERE user_id=?");
    $favRows->execute([$user['id']]);
    $favIds = array_column($favRows->fetchAll(), 'card_id');
} catch(Exception $e) {}

// My orders
$myOrders = $db->prepare("SELECT o.*, c.name as card_name, c.image as card_img, cc.name as cat_name, cc.color as cat_color, p.pin_code, p.serial_number, p.extra_info FROM card_orders o JOIN cards c ON o.card_id=c.id JOIN card_categories cc ON c.category_id=cc.id LEFT JOIN card_pins p ON o.pin_id=p.id WHERE o.user_id=? ORDER BY o.created_at DESC LIMIT 20");
$myOrders->execute([$user['id']]); $myOrders = $myOrders->fetchAll();

// Group cards by category
$grouped = [];
foreach($cards as $c) $grouped[$c['category_id']][] = $c;
?>
<!DOCTYPE html>
<html lang="bn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>Cards — <?= SITE_NAME ?></title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
:root{
            --primary:<?= getSetting('color_primary') ?: '#1a3c8f' ?>;
            --secondary:<?= getSetting('color_secondary') ?: '#f5a623' ?>;
            --dark:<?= getSetting('color_dark') ?: '#0d1f4e' ?>;
        }
*{margin:0;padding:0;box-sizing:border-box;-webkit-tap-highlight-color:transparent}
body{font-family:'Segoe UI',sans-serif;background:#f5f7fa;min-height:100vh;padding-bottom:90px}

/* Header */
.hdr{background:linear-gradient(135deg,var(--dark),var(--primary));padding:0 18px}
.hdr-in{display:flex;align-items:center;gap:12px;height:58px;max-width:480px;margin:0 auto}
.back-btn{background:none;border:none;color:white;font-size:18px;cursor:pointer;width:36px;height:36px;display:flex;align-items:center;justify-content:center;border-radius:50%;flex-shrink:0}
.hdr-title{color:white;font-size:18px;font-weight:700;flex:1}
.bal{background:rgba(255,255,255,0.18);color:white;padding:5px 12px;border-radius:20px;font-size:12px;font-weight:700}

.main{max-width:480px;margin:0 auto;padding:16px}

/* Tabs */
.tabs{display:flex;gap:0;background:white;border-radius:14px;padding:4px;margin-bottom:16px;box-shadow:0 2px 10px rgba(0,0,0,0.06)}
.tab{flex:1;padding:10px;text-align:center;border-radius:10px;cursor:pointer;font-size:13px;font-weight:700;color:#888;transition:0.2s}
.tab.on{background:var(--primary);color:white}

/* Category scroll */
.cat-scroll{display:flex;gap:8px;overflow-x:auto;padding-bottom:4px;margin-bottom:16px;scrollbar-width:none}
.cat-scroll::-webkit-scrollbar{display:none}
.cat-chip{flex-shrink:0;padding:8px 16px;border-radius:20px;border:2px solid #e8ecf4;background:white;cursor:pointer;font-size:12px;font-weight:700;color:#555;transition:0.2s;display:flex;align-items:center;gap:6px;white-space:nowrap}
.cat-chip.on{color:white;border-color:transparent}

/* Card list */
.card-item{background:white;border-radius:16px;overflow:hidden;margin-bottom:12px;box-shadow:0 2px 12px rgba(0,0,0,0.06);cursor:pointer;transition:0.2s;border:2px solid transparent}
.card-item:active{transform:scale(0.98)}
.card-item.sel{border-color:var(--primary)}
.card-img-wrap{position:relative;height:200px;background:#f0f4ff;display:flex;align-items:center;justify-content:center;overflow:hidden}
.card-img-wrap img{width:100%;height:100%;object-fit:cover}
.card-img-wrap .no-img{font-size:56px}
.card-badge{position:absolute;top:10px;left:10px;background:rgba(0,0,0,0.65);color:white;font-size:10px;font-weight:700;padding:3px 10px;border-radius:20px}
.stock-badge{position:absolute;top:10px;right:10px;font-size:10px;font-weight:700;padding:3px 10px;border-radius:20px}
.in-stock{background:#22c55e;color:white}
.low-stock{background:#f59e0b;color:white}
.out-stock{background:#ef4444;color:white}
.card-info{padding:14px}
.card-name{font-size:14px;font-weight:700;color:var(--dark);margin-bottom:4px}
.card-meta{font-size:12px;color:#888;margin-bottom:10px;display:flex;gap:12px;flex-wrap:wrap}
.card-meta span{display:flex;align-items:center;gap:4px}
.price-row{display:flex;align-items:center;gap:10px}
.price{font-size:20px;font-weight:800;color:var(--primary)}
.orig-price{font-size:13px;color:#bbb;text-decoration:line-through}
.discount{background:#fef3c7;color:#d97706;font-size:11px;font-weight:700;padding:2px 8px;border-radius:20px}
.buy-btn{width:100%;padding:14px;background:linear-gradient(135deg,var(--primary),#2856c8);color:white;border:none;border-radius:12px;font-size:15px;font-weight:700;cursor:pointer;margin-top:12px;display:flex;align-items:center;justify-content:center;gap:8px}
        .buy-btn *{pointer-events:none}
.buy-btn:disabled{background:#c5cdd8;cursor:not-allowed}
.buy-btn.out{background:#e5e7eb;color:#9ca3af}

/* My Orders */
.order-item{background:white;border-radius:14px;margin-bottom:10px;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,0.05)}
.order-head{padding:14px 16px;display:flex;align-items:center;gap:12px;cursor:pointer}
.order-thumb{width:48px;height:48px;border-radius:10px;object-fit:cover;background:#f0f4ff;display:flex;align-items:center;justify-content:center;font-size:22px;flex-shrink:0;overflow:hidden}
.order-thumb img{width:100%;height:100%;object-fit:cover}
.order-info{flex:1}
.order-name{font-size:13px;font-weight:700;color:var(--dark)}
.order-date{font-size:11px;color:#aaa;margin-top:2px}
.order-price{font-size:15px;font-weight:800;color:var(--primary);margin-right:6px}
.status-badge{font-size:10px;font-weight:700;padding:2px 8px;border-radius:20px}
.status-completed{background:#f0fff4;color:#276749}
.status-refunded{background:#fff5f5;color:#c53030}
.order-detail{display:none;padding:0 16px 16px;border-top:1px solid #f5f5f5}
.order-detail.open{display:block}
.pin-reveal{background:linear-gradient(135deg,var(--dark),var(--primary));border-radius:12px;padding:16px;margin-top:10px;text-align:center}
.pin-label{color:rgba(255,255,255,0.7);font-size:11px;margin-bottom:6px}
.pin-code{color:white;font-size:22px;font-weight:800;letter-spacing:3px;font-family:monospace;word-break:break-all}
.pin-extra{color:rgba(255,255,255,0.6);font-size:11px;margin-top:6px}
.copy-btn{background:rgba(255,255,255,0.2);color:white;border:none;padding:8px 16px;border-radius:8px;font-size:13px;font-weight:700;cursor:pointer;margin-top:10px;width:100%}
        .copy-btn *{pointer-events:none}

/* Alert */
.err{background:#fff5f5;color:#c53030;padding:12px 14px;border-radius:12px;margin-bottom:14px;font-size:13px;font-weight:600;border-left:3px solid #e53e3e}

/* Popup */
.pop-ov{display:none;position:fixed;inset:0;background:rgba(0,0,0,0.6);z-index:500;align-items:flex-end;justify-content:center}
.pop-ov.on{display:flex}
.pop-box{background:white;border-radius:28px 28px 0 0;padding:28px 22px 38px;width:100%;max-width:480px;animation:slideUp 0.3s ease}
@keyframes slideUp{from{transform:translateY(100%)}to{transform:translateY(0)}}
.pop-close{position:absolute;top:14px;right:16px;background:none;border:none;font-size:22px;color:#bbb;cursor:pointer}
.pop-icon{width:68px;height:68px;border-radius:50%;background:linear-gradient(135deg,#22c55e,#16a34a);display:flex;align-items:center;justify-content:center;margin:0 auto 14px;box-shadow:0 4px 20px rgba(34,197,94,0.4)}
.pop-icon i{color:white;font-size:30px}
.pop-title{text-align:center;font-size:18px;font-weight:800;color:var(--dark);margin-bottom:6px}
.pop-sub{text-align:center;font-size:13px;color:#888;margin-bottom:18px}
.pop-pin-box{background:linear-gradient(135deg,var(--dark),var(--primary));border-radius:16px;padding:20px;text-align:center;margin-bottom:14px}
.pop-pin-label{color:rgba(255,255,255,0.7);font-size:12px;margin-bottom:8px}
.pop-pin-code{color:white;font-size:26px;font-weight:800;letter-spacing:4px;font-family:monospace;word-break:break-all;line-height:1.4}
.pop-pin-serial{color:rgba(255,255,255,0.6);font-size:12px;margin-top:6px}
.pop-copy{width:100%;padding:12px;background:white;color:var(--primary);border:none;border-radius:10px;font-size:14px;font-weight:700;cursor:pointer;margin-top:10px}
.pop-home{width:100%;padding:14px;background:var(--primary);color:white;border:none;border-radius:14px;font-size:15px;font-weight:700;cursor:pointer;margin-top:10px}

.empty{text-align:center;padding:40px;color:#aaa}
.empty i{font-size:36px;display:block;margin-bottom:10px;color:#ddd}
</style>
</head>
<body>

<div class="hdr">
    <div class="hdr-in">
        <button class="back-btn" onclick="history.back()"><i class="fas fa-arrow-left"></i></button>
        <div class="hdr-title">🎴 Cards</div>
        <div class="bal">৳<?= number_format($user['balance'],2) ?></div>
    </div>
</div>

<div class="main">
    <!-- Tabs -->
    <div class="tabs">
        <div class="tab on" onclick="switchTab('browse',this)">🛒 Browse</div>
        <div class="tab" onclick="switchTab('favorites',this)">❤️ Saved (<?= count($favIds) ?>)</div>
        <div class="tab" onclick="switchTab('myorders',this)">📦 My Cards (<?= count($myOrders) ?>)</div>
    </div>

    <!-- ===== BROWSE ===== -->
    <div id="tab-browse">
        <?php if($error): ?>
        <div class="err">❌ <?= htmlspecialchars($error) ?></div>
        <?php endif; ?>

        <?php if(empty($categories)): ?>
        <div class="empty"><i class="fas fa-layer-group"></i> No cards available yet</div>
        <?php else: ?>

        <!-- Category filter -->
        <div class="cat-scroll">
            <div class="cat-chip on" data-cat="all" onclick="filterCat('all',this)" style="background:var(--primary);border-color:var(--primary);color:white">All</div>
            <?php foreach($categories as $cat): ?>
            <div class="cat-chip" data-cat="<?= $cat['id'] ?>" onclick="filterCat('<?= $cat['id'] ?>',this)" style="--cc:<?= $cat['color'] ?>">
                <?php if($cat['image']): ?><img src="<?= htmlspecialchars($cat['image']) ?>" style="width:18px;height:18px;object-fit:contain;border-radius:3px"><?php else: ?><?= $cat['icon'] ?><?php endif; ?>
                <?= htmlspecialchars($cat['name']) ?>
            </div>
            <?php endforeach; ?>
        </div>

        <!-- Cards -->
        <div id="cardList">
        <?php foreach($cards as $c):
            $stockLabel = $c['stock']>5 ? 'In Stock' : ($c['stock']>0 ? 'Only '.$c['stock'].' left' : 'Out of Stock');
            $stockClass = $c['stock']>5 ? 'in-stock' : ($c['stock']>0 ? 'low-stock' : 'out-stock');
            $disc = $c['original_price'] && $c['original_price']>$c['price'] ? round((1-$c['price']/$c['original_price'])*100) : 0;
        ?>
        <div class="card-item" data-cat="<?= $c['category_id'] ?>">
            <div class="card-img-wrap">
                <?php if($c['image']): ?><img src="<?= htmlspecialchars($c['image']) ?>" alt=""><?php else: ?><span class="no-img"><?= $c['cat_icon'] ?></span><?php endif; ?>
                <span class="card-badge"><?= htmlspecialchars($c['cat_name']) ?></span>
                <span class="stock-badge <?= $stockClass ?>"><?= $stockLabel ?></span>
            </div>
            <div class="card-info">
                <div style="display:flex;align-items:flex-start;justify-content:space-between;gap:8px;margin-bottom:4px">
                    <div class="card-name" style="flex:1"><?= htmlspecialchars($c['name']) ?></div>
                    <button class="fav-btn" id="fav<?= $c['id'] ?>" onclick="toggleFav(<?= $c['id'] ?>,this)" title="<?= in_array($c['id'],$favIds)?'Remove from favorites':'Save to favorites' ?>" style="background:<?= in_array($c['id'],$favIds)?'#fff0f3':'#f5f7fa' ?>;border:2px solid <?= in_array($c['id'],$favIds)?'#ffb3c1':'#e8ecf4' ?>;border-radius:10px;width:38px;height:38px;display:flex;align-items:center;justify-content:center;cursor:pointer;flex-shrink:0;transition:0.2s;font-size:18px" data-active="<?= in_array($c['id'],$favIds)?'1':'0' ?>">
                        <?= in_array($c['id'],$favIds) ? '❤️' : '🤍' ?>
                    </button>
                </div>
                <div class="card-meta">
                    <?php if($c['validity']): ?><span>⏱ <?= htmlspecialchars($c['validity']) ?></span><?php endif; ?>
                    <?php if($c['region']): ?><span>🌍 <?= htmlspecialchars($c['region']) ?></span><?php endif; ?>
                </div>
                <?php if($c['description']): ?>
                <div class="desc-wrap" id="dw<?= $c['id'] ?>">
                    <div class="desc-text" id="dt<?= $c['id'] ?>" style="font-size:13px;color:#555;line-height:1.7;max-height:60px;overflow:hidden;transition:max-height 0.3s ease">
                        <?php
                        // Auto-link URLs in description
                        $desc = htmlspecialchars($c['description']);
                        $desc = preg_replace('/(https?:\/\/[^\s<]+)/', '<a href="$1" target="_blank" style="color:var(--primary);font-weight:600">$1</a>', $desc);
                        echo nl2br($desc);
                        ?>
                    </div>
                    <button onclick="toggleDesc(<?= $c['id'] ?>)" id="db<?= $c['id'] ?>" style="background:none;border:none;color:var(--primary);font-size:11px;font-weight:700;cursor:pointer;padding:4px 0;display:flex;align-items:center;gap:4px">
                        <span id="dbt<?= $c['id'] ?>">Show more</span> <i class="fas fa-chevron-down" id="dbi<?= $c['id'] ?>" style="font-size:10px;transition:0.2s"></i>
                    </button>
                </div>
                <?php endif; ?>
                <?php
                $cardCommission = floatval($c['commission']??0);
                $actualCardComm = $cardCommission>0 ? ($commRate>0 ? round($cardCommission*$commRate/100,2) : $cardCommission) : 0;
                ?>
                <div style="margin-bottom:<?= $actualCardComm>0?'6px':'10px' ?>">
                    <span style="font-size:16px;font-weight:800;color:var(--primary)">৳<?= number_format($c['price'],2) ?></span>
                    <?php if($_card_uc && floatval($_card_uc['rate'])>0): ?>
                    <span style="font-size:11px;color:#aaa;margin-left:5px">≈ <?= htmlspecialchars($_card_uc['symbol']) ?><?= number_format($c['price']*floatval($_card_uc['rate']),2) ?> <?= $_card_uc['code'] ?></span>
                    <?php endif; ?>
                </div>
                <?php if($actualCardComm > 0): ?>
                <div style="display:inline-flex;align-items:center;gap:5px;background:#f0fff4;border:1px solid #c6f6d5;border-radius:20px;padding:3px 10px;margin-bottom:8px;font-size:12px;font-weight:700;color:#276749">
                    💸 +৳<?= number_format($actualCardComm,2) ?>
                    <?php if($_card_uc && floatval($_card_uc['rate'])>0): ?>
                    <span style="font-size:10px;color:#aaa;font-weight:500">≈ <?= htmlspecialchars($_card_uc['symbol']) ?><?= number_format($actualCardComm*floatval($_card_uc['rate']),2) ?> <?= $_card_uc['code'] ?></span>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
                <?php if($c['stock'] > 0): ?>
                <button type="button" class="buy-btn"
                    data-cid="<?= $c['id'] ?>"
                    data-name="<?= htmlspecialchars($c['name'],ENT_QUOTES) ?>"
                    data-price="<?= $c['price'] ?>"
                    data-commission="<?= floatval($c['commission']??0) ?>"
                    data-stock="<?= $c['stock'] ?>"
                    data-img="<?= htmlspecialchars($c['image']??'',ENT_QUOTES) ?>"
                    data-validity="<?= htmlspecialchars($c['validity']??'',ENT_QUOTES) ?>"
                    data-cat="<?= htmlspecialchars($c['cat_name']??'',ENT_QUOTES) ?>">
                    <i class="fas fa-shopping-cart"></i> Buy Now — ৳<?= number_format($c['price'],2) ?>
                </button>
                <?php else: ?>
                <button class="buy-btn out" disabled><i class="fas fa-times-circle"></i> Out of Stock</button>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>

    <!-- ===== FAVORITES ===== -->
    <div id="tab-favorites" style="display:none">
        <?php
        $favCards = array_filter($cards, fn($c) => in_array($c['id'], $favIds));
        if(empty($favCards)):
        ?>
        <div class="empty" style="padding:50px 20px">
            <div style="font-size:48px;margin-bottom:12px">🤍</div>
            <div style="font-size:15px;font-weight:700;color:#555;margin-bottom:6px">No saved cards yet</div>
            <div style="font-size:13px;color:#aaa">Card এ ❤️ চাপলে এখানে save হবে</div>
        </div>
        <?php else: foreach($favCards as $c):
            $stockLabel = $c['stock']>5 ? 'In Stock' : ($c['stock']>0 ? 'Only '.$c['stock'].' left' : 'Out of Stock');
            $stockClass = $c['stock']>5 ? 'in-stock' : ($c['stock']>0 ? 'low-stock' : 'out-stock');
            $disc = $c['original_price'] && $c['original_price']>$c['price'] ? round((1-$c['price']/$c['original_price'])*100) : 0;
        ?>
        <div class="card-item" data-cat="<?= $c['category_id'] ?>">
            <div class="card-img-wrap">
                <?php if($c['image']): ?><img src="<?= htmlspecialchars($c['image']) ?>" alt=""><?php else: ?><span class="no-img"><?= $c['cat_icon'] ?></span><?php endif; ?>
                <span class="card-badge"><?= htmlspecialchars($c['cat_name']) ?></span>
                <span class="stock-badge <?= $stockClass ?>"><?= $stockLabel ?></span>
            </div>
            <div class="card-info">
                <div style="display:flex;align-items:flex-start;justify-content:space-between;gap:8px;margin-bottom:4px">
                    <div class="card-name" style="flex:1"><?= htmlspecialchars($c['name']) ?></div>
                    <button class="fav-btn" id="fav2-<?= $c['id'] ?>" onclick="toggleFav(<?= $c['id'] ?>,this)" style="background:none;border:none;font-size:20px;cursor:pointer;padding:0;flex-shrink:0;line-height:1;margin-top:-2px">❤️</button>
                </div>
                <div class="card-meta">
                    <?php if($c['validity']): ?><span>⏱ <?= htmlspecialchars($c['validity']) ?></span><?php endif; ?>
                    <?php if($c['region']): ?><span>🌍 <?= htmlspecialchars($c['region']) ?></span><?php endif; ?>
                </div>
                <?php
                $fCardComm = floatval($c['commission']??0);
                $fActualComm = $fCardComm>0 ? ($commRate>0 ? round($fCardComm*$commRate/100,2) : $fCardComm) : 0;
                ?>
                <div style="margin-bottom:<?= $fActualComm>0?'6px':'10px' ?>">
                    <span style="font-size:16px;font-weight:800;color:var(--primary)">৳<?= number_format($c['price'],2) ?></span>
                    <?php if($_card_uc && floatval($_card_uc['rate'])>0): ?>
                    <span style="font-size:11px;color:#aaa;margin-left:5px">≈ <?= htmlspecialchars($_card_uc['symbol']) ?><?= number_format($c['price']*floatval($_card_uc['rate']),2) ?> <?= $_card_uc['code'] ?></span>
                    <?php endif; ?>
                </div>
                <?php if($fActualComm > 0): ?>
                <div style="display:inline-flex;align-items:center;gap:5px;background:#f0fff4;border:1px solid #c6f6d5;border-radius:20px;padding:3px 10px;margin-bottom:8px;font-size:12px;font-weight:700;color:#276749">
                    💸 +৳<?= number_format($fActualComm,2) ?>
                    <?php if($_card_uc && floatval($_card_uc['rate'])>0): ?>
                    <span style="font-size:10px;color:#aaa;font-weight:500">≈ <?= htmlspecialchars($_card_uc['symbol']) ?><?= number_format($fActualComm*floatval($_card_uc['rate']),2) ?> <?= $_card_uc['code'] ?></span>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
                <?php if($c['stock'] > 0): ?>
                <button type="button" class="buy-btn"
                    data-cid="<?= $c['id'] ?>"
                    data-name="<?= htmlspecialchars($c['name'],ENT_QUOTES) ?>"
                    data-price="<?= $c['price'] ?>"
                    data-commission="<?= floatval($c['commission']??0) ?>"
                    data-stock="<?= $c['stock'] ?>"
                    data-img="<?= htmlspecialchars($c['image']??'',ENT_QUOTES) ?>"
                    data-validity="<?= htmlspecialchars($c['validity']??'',ENT_QUOTES) ?>"
                    data-cat="<?= htmlspecialchars($c['cat_name']??'',ENT_QUOTES) ?>">
                    <i class="fas fa-shopping-cart"></i> Buy Now — ৳<?= number_format($c['price'],2) ?>
                </button>
                <?php else: ?><button class="buy-btn out" disabled>Out of Stock</button><?php endif; ?>
            </div>
        </div>
        <?php endforeach; endif; ?>
    </div>

    <!-- ===== MY ORDERS ===== -->
    <div id="tab-myorders" style="display:none">
        <?php if(empty($myOrders)): ?>
        <div class="empty"><i class="fas fa-shopping-bag"></i> No purchases yet</div>
        <?php else: foreach($myOrders as $o): ?>
        <div class="order-item">
            <div class="order-head" onclick="toggleOrder(<?= $o['id'] ?>)">
                <div class="order-thumb">
                    <?php if($o['card_img']): ?><img src="<?= htmlspecialchars($o['card_img']) ?>"><?php else: ?><i class="fas fa-layer-group" style="color:<?= $o['cat_color'] ?>"></i><?php endif; ?>
                </div>
                <div class="order-info">
                    <div class="order-name"><?= htmlspecialchars($o['card_name']) ?></div>
                    <div class="order-date"><?= date('d M Y, h:i A',strtotime($o['created_at'])) ?></div>
                </div>
                <div style="text-align:right">
                    <div class="order-price">৳<?= number_format($o['total_price'],2) ?></div>
                    <span class="status-badge status-<?= $o['status'] ?>"><?= ucfirst($o['status']) ?></span>
                </div>
                <i class="fas fa-chevron-down" id="och<?= $o['id'] ?>" style="color:#ddd;font-size:12px;margin-left:6px;transition:0.2s"></i>
            </div>
            <div class="order-detail" id="odet<?= $o['id'] ?>">
                <?php if($o['status']==='completed' && $o['pin_code']): ?>
                <!-- PIN reveal -->
                <div class="pin-reveal" id="pincard<?= $o['id'] ?>">
                    <?php if($o['card_img']): ?>
                    <img src="<?= htmlspecialchars($o['card_img']) ?>" style="width:60px;height:60px;object-fit:contain;border-radius:10px;margin-bottom:10px;background:rgba(255,255,255,0.1)">
                    <?php endif; ?>
                    <div style="font-size:12px;color:rgba(255,255,255,0.6);margin-bottom:4px"><?= htmlspecialchars($o['cat_name']) ?></div>
                    <div style="font-size:14px;font-weight:800;color:white;margin-bottom:12px"><?= htmlspecialchars($o['card_name']) ?></div>
                    <div class="pin-label">PIN Code</div>
                    <div class="pin-code" id="opin<?= $o['id'] ?>"><?= htmlspecialchars($o['pin_code']) ?></div>
                    <?php if($o['serial_number']): ?><div class="pin-extra">Serial: <?= htmlspecialchars($o['serial_number']) ?></div><?php endif; ?>
                    <?php if($o['extra_info']): ?><div class="pin-extra"><?= htmlspecialchars($o['extra_info']) ?></div><?php endif; ?>
                    <div style="font-size:11px;color:rgba(255,255,255,0.4);margin-top:8px">Ref: <?= htmlspecialchars($o['reference']??'—') ?> · <?= date('d M Y',strtotime($o['created_at'])) ?></div>
                    <div style="display:flex;gap:8px;margin-top:12px">
                        <button class="copy-btn copy-pin-btn" style="flex:1" data-target="opin<?= $o['id'] ?>">
                        <i class="fas fa-copy" style="pointer-events:none"></i> <span style="pointer-events:none">Copy PIN</span>
                    </button>
                        <button class="copy-btn share-card-btn" style="flex:1;background:rgba(255,255,255,0.25)"
                        data-name="<?= htmlspecialchars($o['card_name'],ENT_QUOTES) ?>"
                        data-pin="<?= htmlspecialchars($o['pin_code'],ENT_QUOTES) ?>"
                        data-serial="<?= htmlspecialchars($o['serial_number']??'',ENT_QUOTES) ?>"
                        data-extra="<?= htmlspecialchars($o['extra_info']??'',ENT_QUOTES) ?>"
                        data-ref="<?= htmlspecialchars($o['reference']??'',ENT_QUOTES) ?>"
                        data-img="<?= htmlspecialchars($o['card_img']??'',ENT_QUOTES) ?>"
                        data-desc="">
                        <i class="fas fa-share-alt" style="pointer-events:none"></i> <span style="pointer-events:none">Share</span>
                    </button>
                    </div>
                </div>
                <?php else: ?>
                <div style="font-size:12px;color:#aaa;text-align:center;padding:10px">
                    Status: <?= ucfirst($o['status']) ?> · Ref: <?= htmlspecialchars($o['reference']??'—') ?>
                </div>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; endif; ?>
    </div>
</div>

<!-- Buy Confirmation Popup -->
<div class="pop-ov" id="buyPop">
<div class="pop-box" style="position:relative;padding:0;overflow:hidden">
    <!-- Card image banner -->
    <div id="buyImgBanner" style="height:140px;background:linear-gradient(135deg,var(--dark),var(--primary));display:flex;align-items:center;justify-content:center;position:relative;overflow:hidden">
        <img id="buyImg" src="" style="width:100%;height:100%;object-fit:cover;display:none">
        <div id="buyImgIcon" style="font-size:56px">🎴</div>
        <!-- Overlay gradient -->
        <div style="position:absolute;inset:0;background:linear-gradient(to top,rgba(0,0,0,0.6),transparent)"></div>
        <!-- Category badge -->
        <div id="buyCatBadge" style="position:absolute;top:12px;left:14px;background:rgba(255,255,255,0.2);backdrop-filter:blur(8px);color:white;font-size:11px;font-weight:700;padding:4px 12px;border-radius:20px"></div>
        <!-- Close button -->
        <button onclick="closeBuyPop()" style="position:absolute;top:12px;right:12px;background:rgba(255,255,255,0.2);backdrop-filter:blur(8px);border:none;color:white;width:32px;height:32px;border-radius:50%;font-size:16px;cursor:pointer;display:flex;align-items:center;justify-content:center">✕</button>
        <!-- Card name over image -->
        <div style="position:absolute;bottom:14px;left:14px;right:14px">
            <div id="buyCardName" style="color:white;font-size:16px;font-weight:800;line-height:1.3"></div>
        </div>
    </div>

    <!-- Content -->
    <div style="padding:20px 22px">
        <!-- Price breakdown -->
        <div style="background:#f8fafc;border-radius:14px;padding:16px;margin-bottom:18px">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px">
                <span style="font-size:13px;color:#888;font-weight:600">Card Price</span>
                <div style="text-align:right">
                    <span id="buyPrice" style="font-size:18px;font-weight:800;color:var(--primary)"></span>
                    <div id="buyPriceUC" style="font-size:11px;color:#aaa;margin-top:1px"></div>
                </div>
            </div>
            <div id="buyCommRow" style="display:none;align-items:center;justify-content:space-between;margin-bottom:10px">
                <span style="font-size:13px;color:#38a169;font-weight:600">💸 Commission</span>
                <span id="buyCommAmt" style="font-size:14px;font-weight:800;color:#38a169"></span>
            </div>
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;padding-bottom:10px;border-bottom:1px dashed #e8ecf4">
                <span style="font-size:13px;color:#888;font-weight:600">Your Balance</span>
                <div style="text-align:right">
                    <span id="buyBalance" style="font-size:14px;font-weight:700;color:#333"></span>
                    <div id="buyBalanceUC" style="font-size:11px;color:#aaa;margin-top:1px"></div>
                </div>
            </div>
            <div style="display:flex;justify-content:space-between;align-items:center">
                <span style="font-size:13px;color:#888;font-weight:600">After Purchase</span>
                <div style="text-align:right">
                    <span id="buyAfter" style="font-size:14px;font-weight:700"></span>
                    <div id="buyAfterUC" style="font-size:11px;color:#aaa;margin-top:1px"></div>
                </div>
            </div>
            <div id="buyValidity" style="margin-top:10px;padding-top:10px;border-top:1px dashed #e8ecf4;font-size:12px;color:#888;display:none">
                <i class="fas fa-clock" style="color:var(--primary)"></i> Validity: <span id="buyValidityTxt"></span>
            </div>
        </div>

        <!-- Stock info (hidden) -->
        <div id="buyStock" style="display:none"></div>

        <!-- Insufficient balance warning -->
        <div id="buyWarn" style="display:none;background:#fff5f5;border:1px solid #fed7d7;border-radius:10px;padding:10px 14px;font-size:13px;color:#c53030;font-weight:600;text-align:center;margin-bottom:14px">
            ⚠️ Insufficient balance!
        </div>

        <!-- Confirm form -->
        <form method="POST" id="buyConfirmForm">
            <input type="hidden" name="buy_card_id" id="buyCardId">
            <button type="submit" id="buyConfirmBtn" style="width:100%;padding:16px;background:linear-gradient(135deg,#16a34a,#22c55e);color:white;border:none;border-radius:16px;font-size:16px;font-weight:800;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:10px;box-shadow:0 4px 20px rgba(34,197,94,0.35);transition:0.2s">
                <i class="fas fa-check-circle"></i> Confirm Purchase
            </button>
        </form>
        <button onclick="closeBuyPop()" style="width:100%;padding:13px;background:none;border:none;color:#888;font-size:14px;font-weight:600;cursor:pointer;margin-top:8px">Cancel</button>
    </div>
</div>
</div>

<!-- Share Popup -->
<div class="pop-ov" id="sharePop">
<div class="pop-box" style="position:relative">
    <button onclick="closeSharePop()" class="pop-close">✕</button>
    <div style="text-align:center;margin-bottom:18px">
        <div style="font-size:32px;margin-bottom:6px">📤</div>
        <div style="font-size:17px;font-weight:800;color:var(--dark)">Share Card</div>
        <div id="shareCardName" style="font-size:13px;color:#888;margin-top:3px"></div>
    </div>
    <div style="display:flex;flex-direction:column;gap:10px;margin-bottom:16px" id="shareBtnsGrid">
        <button data-share="text" style="background:#f0f4ff;border:2px solid #dbeafe;border-radius:14px;padding:14px 16px;cursor:pointer;display:flex;align-items:center;gap:14px;pointer-events:auto;text-align:left">
            <div style="font-size:26px;pointer-events:none">📋</div>
            <div style="pointer-events:none">
                <div style="font-size:14px;font-weight:700;color:var(--primary)">Full Details</div>
                <div style="font-size:11px;color:#888;margin-top:2px">Name + PIN + Serial copy করবে</div>
            </div>
        </button>
        <button data-share="whatsapp" style="background:#f0fdf4;border:2px solid #bbf7d0;border-radius:14px;padding:14px 16px;cursor:pointer;display:flex;align-items:center;gap:14px;pointer-events:auto;text-align:left">
            <div style="font-size:26px;pointer-events:none">💬</div>
            <div style="pointer-events:none">
                <div style="font-size:14px;font-weight:700;color:#16a34a">WhatsApp</div>
                <div style="font-size:11px;color:#888;margin-top:2px">WhatsApp এ share করবে</div>
            </div>
        </button>
        <button data-share="namepin" style="background:#fefce8;border:2px solid #fde68a;border-radius:14px;padding:14px 16px;cursor:pointer;display:flex;align-items:center;gap:14px;pointer-events:auto;text-align:left">
            <div style="font-size:26px;pointer-events:none">🎴</div>
            <div style="pointer-events:none">
                <div style="font-size:14px;font-weight:700;color:#d97706">Name + PIN</div>
                <div style="font-size:11px;color:#888;margin-top:2px">Card name ও PIN একসাথে copy</div>
            </div>
        </button>
        <button data-share="pin" style="background:#fff5f5;border:2px solid #fecaca;border-radius:14px;padding:14px 16px;cursor:pointer;display:flex;align-items:center;gap:14px;pointer-events:auto;text-align:left">
            <div style="font-size:26px;pointer-events:none">🔑</div>
            <div style="pointer-events:none">
                <div style="font-size:14px;font-weight:700;color:#dc2626">PIN Only</div>
                <div style="font-size:11px;color:#888;margin-top:2px">শুধু PIN copy করবে</div>
            </div>
        </button>
    </div>
    <div id="shareToast" style="display:none;background:#f0fff4;color:#16a34a;padding:10px;border-radius:10px;text-align:center;font-size:13px;font-weight:700">✅ Copied!</div>
</div>
</div>
<?php if($successData): ?>
<div class="pop-ov on" id="successPop">
<div class="pop-box" style="position:relative">
    <button class="pop-close" onclick="document.getElementById('successPop').classList.remove('on')">✕</button>
    <div class="pop-icon"><i class="fas fa-check"></i></div>
    <div class="pop-title">Purchase Successful!</div>
    <div class="pop-sub"><?= htmlspecialchars($successData['card_name']) ?></div>
    <div class="pop-pin-box">
        <div class="pop-pin-label">Your PIN Code</div>
        <div class="pop-pin-code" id="successPin"><?= htmlspecialchars($successData['pin_code']) ?></div>
        <?php if($successData['serial']): ?><div class="pop-pin-serial">Serial: <?= htmlspecialchars($successData['serial']) ?></div><?php endif; ?>
        <?php if($successData['extra']): ?><div class="pop-pin-serial"><?= htmlspecialchars($successData['extra']) ?></div><?php endif; ?>
        <button class="pop-copy" onclick="copyPin('successPin')"><i class="fas fa-copy"></i> Copy PIN</button>
    </div>
    <div style="display:flex;gap:8px;margin-bottom:4px;font-size:12px;color:#888;justify-content:center;flex-wrap:wrap">
        <?php if($successData['validity']): ?><span>⏱ <?= htmlspecialchars($successData['validity']) ?></span><?php endif; ?>
        <span>🔖 Ref: <?= htmlspecialchars($successData['ref']) ?></span>
        <?php if($successData['commission']>0): ?>
        <span style="color:#38a169;font-weight:700">💸 Commission: +৳<?= number_format($successData['commission'],2) ?></span>
        <?php endif; ?>
    </div>
    <button class="pop-home" onclick="location.href='dashboard.php'"><i class="fas fa-home"></i> Back to Home</button>
</div>
</div>
<?php endif; ?>

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

<script>
const USER_BALANCE = <?= floatval($user['balance']) ?>;
<?php if($_card_uc): ?>
const UC_RATE = <?= floatval($_card_uc['rate']) ?>;
const UC_SYM  = "<?= addslashes($_card_uc['symbol']) ?>";
const UC_CODE = "<?= $_card_uc['code'] ?>";
<?php else: ?>
const UC_RATE=0, UC_SYM='', UC_CODE='';
<?php endif; ?>

<?php
// Get user's card commission rate
$commRate = 0;
try {
    $pkgRow = $db->prepare("SELECT p.card_commission FROM users u LEFT JOIN user_packages p ON COALESCE(u.package_id,1)=p.id WHERE u.id=?");
    $pkgRow->execute([$user['id']]);
    $commRate = floatval($pkgRow->fetchColumn() ?: 0);
} catch(Exception $e) {}
?>
const COMM_RATE = <?= $commRate ?>;

// Event delegation for buy buttons
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.buy-btn[data-cid]').forEach(function(btn) {
        btn.addEventListener('click', function() {
            openBuyPopup(
                this.dataset.cid,
                this.dataset.name,
                parseFloat(this.dataset.price),
                parseInt(this.dataset.stock),
                this.dataset.img,
                this.dataset.validity,
                this.dataset.cat,
                parseFloat(this.dataset.commission||0)
            );
        });
    });
});

function fmt(amt) { return '৳' + amt.toFixed(2); }
function fmtUC(amt) { return UC_RATE>0 ? ' ≈ '+UC_SYM+(amt*UC_RATE).toFixed(2)+' '+UC_CODE : ''; }

function openBuyPopup(cardId, name, price, stock, img, validity, catName, cardComm) {
    document.getElementById('buyCardId').value = cardId;
    document.getElementById('buyCardName').textContent = name;
    document.getElementById('buyCatBadge').textContent = catName;

    // Price + currency
    document.getElementById('buyPrice').textContent = fmt(price);
    document.getElementById('buyPriceUC').textContent = fmtUC(price);

    // Commission
    // Commission = card's own commission × user package rate%
    const cardCommission = parseFloat(cardComm) || 0;
    const comm = (COMM_RATE > 0 && cardCommission > 0) ? Math.round(cardCommission * COMM_RATE / 100 * 100) / 100 : 0;
    const commRow = document.getElementById('buyCommRow');
    if(comm > 0) {
        commRow.style.display = 'flex';
        document.getElementById('buyCommAmt').textContent = '+' + fmt(comm) + fmtUC(comm);
    } else {
        commRow.style.display = 'none';
    }

    // Balance
    const after = USER_BALANCE - price;
    document.getElementById('buyBalance').textContent = fmt(USER_BALANCE);
    document.getElementById('buyBalanceUC').textContent = fmtUC(USER_BALANCE);
    document.getElementById('buyAfter').textContent = fmt(Math.max(0, after));
    document.getElementById('buyAfter').style.color = after < 0 ? '#e53e3e' : '#38a169';
    document.getElementById('buyAfterUC').textContent = after >= 0 ? fmtUC(after) : '';

    // Image
    const imgEl = document.getElementById('buyImg');
    const iconEl = document.getElementById('buyImgIcon');
    if(img) { imgEl.src=img; imgEl.style.display='block'; iconEl.style.display='none'; }
    else { imgEl.style.display='none'; iconEl.style.display='block'; }

    // Validity
    const valDiv = document.getElementById('buyValidity');
    if(validity) { valDiv.style.display='flex'; document.getElementById('buyValidityTxt').textContent = validity; }
    else { valDiv.style.display='none'; }

    // Stock
    document.getElementById('buyStock').textContent = stock <= 5 ? '⚠️ Only '+stock+' left in stock!' : '✅ '+stock+' in stock';
    document.getElementById('buyStock').style.color = stock <= 5 ? '#d69e2e' : '#38a169';

    // Insufficient balance
    const warn = document.getElementById('buyWarn');
    const btn  = document.getElementById('buyConfirmBtn');
    if(after < 0) {
        warn.innerHTML = '⚠️ Insufficient balance! Need ' + fmt(price) + ' but you have ' + fmt(USER_BALANCE);
        warn.style.display = 'block';
        btn.style.background = '#c5cdd8';
        btn.style.boxShadow = 'none';
        btn.disabled = true;
    } else {
        warn.style.display = 'none';
        btn.style.background = 'linear-gradient(135deg,#16a34a,#22c55e)';
        btn.style.boxShadow = '0 4px 20px rgba(34,197,94,0.35)';
        btn.disabled = false;
    }

    document.getElementById('buyPop').classList.add('on');
}

function closeBuyPop() {
    document.getElementById('buyPop').classList.remove('on');
}

document.getElementById('buyPop').addEventListener('click', function(e) {
    if(e.target === this) closeBuyPop();
});

function switchTab(tab, el) {
    document.querySelectorAll('.tabs .tab').forEach(t => t.classList.remove('on'));
    el.classList.add('on');
    document.getElementById('tab-browse').style.display = tab==='browse'?'':'none';
    document.getElementById('tab-favorites').style.display = tab==='favorites'?'':'none';
    document.getElementById('tab-myorders').style.display = tab==='myorders'?'':'none';
}

function toggleFav(cardId, btn) {
    fetch('cards.php', {
        method: 'POST',
        headers: {'Content-Type':'application/x-www-form-urlencoded'},
        body: 'fav_card_id='+cardId
    }).then(r=>r.json()).then(d=>{
        if(d.ok) {
            const isFav = d.fav;
            document.querySelectorAll('[id^="fav"]').forEach(b => {
                const bid = b.id.replace('fav2-','').replace('fav','');
                if(bid == cardId) {
                    b.textContent = isFav ? '❤️' : '🤍';
                    b.style.background = isFav ? '#fff0f3' : '#f5f7fa';
                    b.style.borderColor = isFav ? '#ffb3c1' : '#e8ecf4';
                    b.dataset.active = isFav ? '1' : '0';
                }
            });
            // Pop animation
            btn.style.transform = 'scale(1.3)';
            setTimeout(()=>btn.style.transform='scale(1)', 200);
        }
    }).catch(()=>{});
}

function filterCat(catId, el) {
    document.querySelectorAll('.cat-chip').forEach(c => {
        c.classList.remove('on');
        c.style.background = '';
        c.style.borderColor = '#e8ecf4';
        c.style.color = '#555';
    });
    el.classList.add('on');
    if(catId === 'all') {
        el.style.background = 'var(--primary)';
        el.style.borderColor = 'var(--primary)';
        el.style.color = 'white';
    } else {
        const color = getComputedStyle(el).getPropertyValue('--cc').trim() || 'var(--primary)';
        el.style.background = color;
        el.style.borderColor = color;
        el.style.color = 'white';
    }
    document.querySelectorAll('.card-item').forEach(c => {
        c.style.display = (catId==='all' || c.dataset.cat===catId) ? '' : 'none';
    });
}

// Share system
let shareData = {};
function openSharePop(id, name, pin, serial, extra, ref, img, desc) {
    shareData = {id, name, pin, serial, extra, ref, img, desc: desc||''};
    document.getElementById('shareCardName').textContent = name;
    document.getElementById('shareToast').style.display = 'none';
    document.getElementById('sharePop').classList.add('on');
}
function closeSharePop() { document.getElementById('sharePop').classList.remove('on'); }

// Event delegation for share buttons
document.addEventListener('DOMContentLoaded', function() {

    // Share card buttons
    document.querySelectorAll('.share-card-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            openSharePop(
                0,
                this.dataset.name,
                this.dataset.pin,
                this.dataset.serial,
                this.dataset.extra,
                this.dataset.ref,
                this.dataset.img,
                this.dataset.desc
            );
        });
    });

    // Copy PIN buttons
    document.querySelectorAll('.copy-pin-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            copyPin(this.dataset.target);
        });
    });

    document.getElementById('shareBtnsGrid')?.addEventListener('click', function(e) {
        const btn = e.target.closest('[data-share]');
        if(!btn) return;
        const type = btn.dataset.share;
        if(type==='text') shareText();
        else if(type==='namepin') shareNamePin();
        else if(type==='whatsapp') shareWhatsApp();
        else if(type==='pin') shareOnlyPin();
    });

    document.getElementById('sharePop')?.addEventListener('click', function(e) {
        if(e.target===this) closeSharePop();
    });
});

function showShareToast(msg) {
    const t = document.getElementById('shareToast');
    t.textContent = '✅ ' + msg;
    t.style.display = 'block';
    setTimeout(() => t.style.display='none', 2500);
}

function shareText() {
    let txt = `🎴 ${shareData.name}`;
    if(shareData.desc) txt += `\n\n${shareData.desc}`;
    txt += `\n\n🔑 PIN: ${shareData.pin}`;
    if(shareData.serial) txt += `\n📋 Serial: ${shareData.serial}`;
    if(shareData.extra)  txt += `\nℹ️ ${shareData.extra}`;
    txt += `\n\n🔖 Ref: ${shareData.ref}`;
    navigator.clipboard?.writeText(txt).then(() => showShareToast('Copied!'));
}

function shareOnlyPin() {
    navigator.clipboard?.writeText(shareData.pin).then(() => showShareToast('PIN Copied!'));
}

function shareWhatsApp() {
    let txt = `🎴 *${shareData.name}*`;
    if(shareData.desc) txt += `\n\n${shareData.desc}`;
    txt += `\n\n🔑 *PIN:* \`${shareData.pin}\``;
    if(shareData.serial) txt += `\n📋 *Serial:* ${shareData.serial}`;
    if(shareData.extra)  txt += `\nℹ️ ${shareData.extra}`;
    txt += `\n\n🔖 Ref: ${shareData.ref}`;
    window.open('https://wa.me/?text='+encodeURIComponent(txt), '_blank');
}

function shareNamePin() {
    let txt = shareData.name + '\n🔑 PIN: ' + shareData.pin;
    if(shareData.serial) txt += '\nSerial: ' + shareData.serial;
    navigator.clipboard?.writeText(txt).then(() => showShareToast('Copied!'));
}

function toggleOrder(id) {
    const d = document.getElementById('odet'+id);
    const icon = document.getElementById('och'+id);
    const open = d.classList.toggle('open');
    icon.style.transform = open ? 'rotate(180deg)' : '';
}

function toggleDesc(id) {
    const dt = document.getElementById('dt'+id);
    const dbt = document.getElementById('dbt'+id);
    const dbi = document.getElementById('dbi'+id);
    const isOpen = dt.style.maxHeight !== '60px';
    dt.style.maxHeight = isOpen ? '60px' : '1000px';
    dbt.textContent = isOpen ? 'Show more' : 'Show less';
    dbi.style.transform = isOpen ? '' : 'rotate(180deg)';
}

function copyPin(elId) {
    const txt = document.getElementById(elId)?.textContent || '';
    navigator.clipboard?.writeText(txt).then(() => {
        const btn = event.target;
        const orig = btn.innerHTML;
        btn.innerHTML = '✅ Copied!';
        setTimeout(() => btn.innerHTML = orig, 2000);
    });
}
</script>
<script>document.addEventListener("DOMContentLoaded",function(){ if(window.pageReady) window.pageReady(); });</script>
</body>
</html>
