<?php
require_once 'includes/config.php';
requireLogin();
$user = getCurrentUser();
$db = getDB();

// User preferred secondary currency
$_h_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']]);
    $_h_uc = $s->fetch() ?: null;
} catch(Exception $e) { $_h_uc = null; }

$activeTab = $_GET['tab'] ?? 'history'; // history | cards
$status = $_GET['status'] ?? 'all';
$search = sanitize($_GET['search'] ?? '');

$where = "WHERE t.user_id = ?";
$params = [$user['id']];

if ($status !== 'all') { $where .= " AND t.status=?"; $params[] = $status; }
if ($search) {
    $where .= " AND (t.phone_number LIKE ? OR t.reference LIKE ? OR o.name LIKE ?)";
    $params = array_merge($params, ["%$search%","%$search%","%$search%"]);
}

// Also include commission transactions for this user
$whereAll = "WHERE t.user_id = ?";
$paramsAll = [$user['id']];

$stmt = $db->prepare("SELECT t.*, o.name as op_name, p.name as pkg_name
    FROM transactions t
    LEFT JOIN operators o ON t.operator_id=o.id
    LEFT JOIN packages p ON t.package_id=p.id
    $where ORDER BY t.created_at DESC LIMIT 100");
$stmt->execute($params);
$txns = $stmt->fetchAll();

// Fetch commissions with original transaction details
$commissionMap = [];
try {
    // Step 1: Get all commission transactions
    $comms = $db->prepare("SELECT * FROM transactions WHERE user_id=? AND type='commission' ORDER BY created_at DESC LIMIT 200");
    $comms->execute([$user['id']]);
    $commRows = $comms->fetchAll();

    // Step 2: Extract refs and fetch original transactions
    $refs = [];
    foreach($commRows as $c) {
        if(preg_match('/Ref:\s*([A-Z0-9]+)/i', $c['note'], $m)) {
            $refs[$m[1]] = $c;
        }
    }

    if(!empty($refs)) {
        $ph = implode(',', array_fill(0, count($refs), '?'));
        $origStmt = $db->prepare("SELECT t.*, o.name as orig_op, p.name as orig_pkg
            FROM transactions t
            LEFT JOIN operators o ON t.operator_id=o.id
            LEFT JOIN packages p ON t.package_id=p.id
            WHERE t.reference IN ($ph)");
        $origStmt->execute(array_keys($refs));
        $origMap = [];
        foreach($origStmt->fetchAll() as $orig) {
            $origMap[$orig['reference']] = $orig;
        }
        // Merge
        foreach($refs as $ref => $c) {
            $c['orig'] = $origMap[$ref] ?? null;
            $commissionMap[$ref] = $c;
        }
    }
} catch(Exception $e) {}

// Count per status
$counts = [];
foreach (['pending','processing','success','refunded','failed'] as $s) {
    $c = $db->prepare("SELECT COUNT(*) FROM transactions WHERE user_id=? AND status=?");
    $c->execute([$user['id'], $s]);
    $counts[$s] = $c->fetchColumn();
}
$counts['all'] = array_sum($counts);

// My Cards — PIN, Gift Card, Calling Card purchases
$myCards = [];
try {
    $cs = $db->prepare("SELECT * FROM user_cards WHERE user_id=? ORDER BY created_at DESC");
    $cs->execute([$user['id']]);
    $myCards = $cs->fetchAll();
} catch(Exception $e) {
    // Also check transactions for card types
}

// Also get card transactions from transactions table
$cardTxns = [];
try {
    $ct = $db->prepare("SELECT * FROM transactions WHERE user_id=? AND type IN ('pin','card','gift') ORDER BY created_at DESC LIMIT 50");
    $ct->execute([$user['id']]);
    $cardTxns = $ct->fetchAll();
} catch(Exception $e) {}

$cardCount = max(count($myCards), count($cardTxns));

// Total stats
$totalSpent = $db->prepare("SELECT COALESCE(SUM(amount),0) FROM transactions WHERE user_id=? AND type='topup' AND status='success'");
$totalSpent->execute([$user['id']]);
$totalSpent = $totalSpent->fetchColumn();

$totalDeposit = $db->prepare("SELECT COALESCE(SUM(amount),0) FROM transactions WHERE user_id=? AND type='deposit' AND status='success'");
$totalDeposit->execute([$user['id']]);
$totalDeposit = $totalDeposit->fetchColumn();
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>History - <?= SITE_NAME ?></title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        * { margin:0; padding:0; box-sizing:border-box; }
        :root {
            --primary:<?= getSetting('color_primary') ?: '#1a3c8f' ?>;
            --secondary:<?= getSetting('color_secondary') ?: '#f5a623' ?>;
            --dark:<?= getSetting('color_dark') ?: '#0d1f4e' ?>;
        }
        body { font-family:'Segoe UI',sans-serif; background:#f5f7fa; padding-bottom:85px; }

        /* Header */
        .header { background:linear-gradient(135deg,var(--dark),var(--primary)); padding:0 20px; position:sticky; top:0; z-index:100; }
        .header-inner { display:flex; align-items:center; gap:15px; height:60px; max-width:500px; margin:0 auto; }
        .back-btn { background:none; border:none; color:white; font-size:20px; cursor:pointer; }
        .header-inner h2 { color:white; font-size:18px; font-weight:700; }

        /* Stats Bar */
        .stats-bar { background:linear-gradient(135deg,var(--dark),var(--primary)); padding:0 20px 18px; }
        .stats-inner { max-width:500px; margin:0 auto; display:grid; grid-template-columns:1fr 1fr 1fr; gap:10px; }
        .stat-box { background:rgba(255,255,255,0.12); border-radius:12px; padding:12px; text-align:center; }
        .stat-box .val { color:white; font-size:18px; font-weight:800; }
        .stat-box .lbl { color:rgba(255,255,255,0.65); font-size:11px; margin-top:3px; }

        .main { max-width:500px; margin:0 auto; padding:15px; }

        /* Status Tabs */
        .tabs-wrap { display:flex; gap:7px; overflow-x:auto; padding-bottom:5px; margin-bottom:15px; scrollbar-width:none; }
        .tabs-wrap::-webkit-scrollbar { display:none; }
        .tab { padding:7px 14px; border-radius:20px; font-size:12px; font-weight:600; text-decoration:none; border:2px solid #e8ecf4; color:#666; white-space:nowrap; transition:0.2s; background:white; display:flex; align-items:center; gap:5px; }
        .tab.active { border-color:var(--primary); background:var(--primary); color:white; }
        .tab .cnt { background:rgba(0,0,0,0.12); padding:1px 6px; border-radius:10px; font-size:10px; }
        .tab:not(.active) .cnt { background:#f0f0f0; color:#888; }

        /* Search */
        .search-wrap { position:relative; margin-bottom:15px; }
        .search-wrap i { position:absolute; left:13px; top:50%; transform:translateY(-50%); color:#aaa; font-size:14px; }
        .search-wrap input { width:100%; padding:11px 11px 11px 38px; border:2px solid #e8ecf4; border-radius:12px; font-size:14px; outline:none; background:white; transition:0.2s; }
        .search-wrap input:focus { border-color:var(--primary); }

        /* Transaction Cards */
        .txn-card { background:white; border-radius:16px; margin-bottom:10px; box-shadow:0 2px 10px rgba(0,0,0,0.05); overflow:hidden; }
        .txn-card-header { display:flex; align-items:center; gap:12px; padding:14px 16px; cursor:pointer; }
        .txn-icon { width:44px; height:44px; border-radius:12px; display:flex; align-items:center; justify-content:center; font-size:18px; flex-shrink:0; }
        .txn-icon.topup { background:#e8f0fe; color:var(--primary); }
        .txn-icon.deposit { background:#f0fff4; color:#38a169; }
        .txn-icon.refund { background:#faf5ff; color:#805ad5; }
        .txn-icon.drive { background:#fff8e6; color:#d69e2e; }
        .txn-icon.commission { background:#f0fff4; color:#38a169; }
        .txn-info { flex:1; min-width:0; }
        .txn-title { font-size:14px; font-weight:700; color:#333; }
        .txn-sub { font-size:12px; color:#999; margin-top:2px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
        .txn-right { text-align:right; flex-shrink:0; }
        .txn-amount { font-size:16px; font-weight:800; }
        .txn-amount.minus { color:#e53e3e; }
        .txn-amount.plus { color:#38a169; }
        .txn-amount.refund-c { color:#805ad5; }
        .txn-status { margin-top:3px; }
        .badge { display:inline-block; padding:2px 9px; border-radius:20px; font-size:10px; font-weight:700; }
        .badge-pending { background:#fffaf0; color:#d69e2e; }
        .badge-processing { background:#ebf8ff; color:#3182ce; }
        .badge-success { background:#f0fff4; color:#38a169; }
        .badge-failed { background:#fff5f5; color:#e53e3e; }
        .badge-refunded { background:#faf5ff; color:#805ad5; }
        .expand-icon { color:#ccc; font-size:12px; transition:0.2s; }

        /* Detail Panel */
        .txn-detail { display:none; border-top:1px solid #f0f0f0; padding:15px 16px; background:#fafbff; }
        .txn-detail.open { display:block; }
        .detail-grid { display:grid; grid-template-columns:1fr 1fr; gap:10px; }
        .detail-item { }
        .detail-item .d-label { font-size:11px; color:#aaa; font-weight:600; text-transform:uppercase; letter-spacing:0.5px; margin-bottom:3px; }
        .detail-item .d-val { font-size:13px; color:#333; font-weight:600; word-break:break-all; }
        .detail-item.full { grid-column:1/-1; }
        /* Detail Modal */
        .det-modal-bg{display:none;position:fixed;inset:0;background:rgba(0,0,0,0.45);z-index:9999;align-items:flex-end;justify-content:center}
        .det-modal-bg.show{display:flex;animation:dmFade 0.2s ease}
        @keyframes dmFade{from{opacity:0}to{opacity:1}}
        .det-modal{background:white;border-radius:24px 24px 0 0;width:100%;max-width:480px;max-height:90vh;overflow-y:auto;animation:dmSlide 0.3s cubic-bezier(0.34,1.1,0.64,1)}
        @keyframes dmSlide{from{transform:translateY(100%)}to{transform:translateY(0)}}
        .det-header{padding:20px 20px 0;text-align:center;position:relative}
        .det-close{position:absolute;right:16px;top:16px;width:32px;height:32px;background:#f5f5f5;border:none;border-radius:50%;font-size:16px;cursor:pointer;color:#666;display:flex;align-items:center;justify-content:center}
        .det-icon{width:60px;height:60px;border-radius:50%;margin:0 auto 12px;display:flex;align-items:center;justify-content:center;font-size:26px}
        .det-title{font-size:18px;font-weight:800;color:#222;margin-bottom:4px}
        .det-sub{font-size:13px;color:#888;margin-bottom:16px}
        .det-body{padding:0 16px 30px}
        .det-row{display:flex;justify-content:space-between;align-items:center;padding:12px 0;border-bottom:1px solid #f5f5f5}
        .det-row:last-child{border:none}
        .det-lbl{font-size:12px;color:#aaa;font-weight:600}
        .det-val{font-size:13px;color:#222;font-weight:700;text-align:right;max-width:60%}
        .det-copy-row{background:#f8fafc;border-radius:12px;padding:12px 14px;display:flex;align-items:center;justify-content:space-between;margin:10px 0}
        .det-copy-btn{background:var(--primary);color:white;border:none;padding:7px 14px;border-radius:9px;font-size:12px;font-weight:700;cursor:pointer}
        .det-copy-btn.copied{background:#38a169}
        .ref-box { background:white; border:1px dashed #d0d8f0; border-radius:8px; padding:10px 12px; margin-top:10px; display:flex; align-items:center; justify-content:space-between; }
        .ref-box span { font-size:12px; color:#666; font-family:monospace; }
        .copy-btn { background:var(--primary); color:white; border:none; padding:5px 12px; border-radius:7px; font-size:11px; cursor:pointer; font-weight:600; }

        /* Status specific colors */
        .txn-card.pending { border-left:4px solid #d69e2e; }
        .txn-card.processing { border-left:4px solid #3182ce; }
        .txn-card.success { border-left:4px solid #38a169; }
        .txn-card.failed { border-left:4px solid #e53e3e; }
        .txn-card.refunded { border-left:4px solid #805ad5; }

        /* Pending notice */
        .pending-notice { background:#fffaf0; border:1px solid #f6e05e; border-radius:8px; padding:8px 12px; margin-top:8px; font-size:12px; color:#744210; display:flex; align-items:center; gap:6px; }

        /* Main Tabs */
        .main-tabs{display:grid;grid-template-columns:1fr 1fr;gap:3px;background:#e8ecf4;border-radius:14px;padding:4px;margin-bottom:16px}
        .main-tab{padding:12px;border:none;border-radius:11px;background:none;font-size:14px;font-weight:700;color:#888;cursor:pointer;transition:0.2s;display:flex;align-items:center;justify-content:center;gap:6px}
        .main-tab.active{background:white;color:var(--primary);box-shadow:0 2px 8px rgba(0,0,0,0.08)}
        .tab-badge{background:var(--primary);color:white;font-size:10px;font-weight:700;padding:2px 6px;border-radius:10px}
        .main-tab:not(.active) .tab-badge{background:#aaa}

        /* My Cards */
        .my-card-item{background:white;border-radius:16px;margin-bottom:12px;box-shadow:0 2px 10px rgba(0,0,0,0.06);overflow:hidden}
        .mc-header{padding:14px 16px;display:flex;align-items:center;gap:12px}
        .mc-icon{width:46px;height:46px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:20px;flex-shrink:0}
        .mc-icon.pin{background:#fffaf0;color:#b7791f}
        .mc-icon.gift{background:#faf5ff;color:#805ad5}
        .mc-icon.card{background:#e6fffa;color:#2c7a7b}
        .mc-info{flex:1;min-width:0}
        .mc-name{font-size:14px;font-weight:700;color:#222}
        .mc-sub{font-size:12px;color:#aaa;margin-top:2px}
        .mc-amount{text-align:right;flex-shrink:0}
        .mc-price{font-size:15px;font-weight:800;color:#e53e3e}
        .mc-status{margin-top:3px}

        /* PIN Box */
        .pin-reveal{padding:0 16px 16px}
        .pin-box-card{background:linear-gradient(135deg,#1a3c8f,#2856c8);border-radius:14px;padding:16px;text-align:center}
        .pin-box-label{color:rgba(255,255,255,0.7);font-size:11px;font-weight:600;letter-spacing:0.5px;margin-bottom:8px}
        .pin-box-code{color:white;font-size:22px;font-weight:800;letter-spacing:4px;font-family:monospace;word-break:break-all}
        .pin-box-card.gift{background:linear-gradient(135deg,#805ad5,#553c9a)}
        .pin-box-card.card{background:linear-gradient(135deg,#2c7a7b,#1d4e4f)}
        .copy-pin-btn{background:rgba(255,255,255,0.2);color:white;border:none;padding:8px 18px;border-radius:10px;font-size:13px;font-weight:600;cursor:pointer;margin-top:10px;width:100%}
        .copy-pin-btn:active{background:rgba(255,255,255,0.35)}
        .pending-pin{background:#fffaf0;border-radius:10px;padding:10px 14px;font-size:13px;color:#92400e;text-align:center;margin:0 16px 16px}

        /* Empty */
        .empty{text-align:center;padding:50px 20px;color:#aaa;background:white;border-radius:16px}
        .empty i{font-size:40px;display:block;margin-bottom:12px;color:#ddd}
        .empty p{font-size:15px}
    </style>
</head>
<body>

<div class="header">
    <div class="header-inner">
        <button class="back-btn" onclick="history.back()"><i class="fas fa-arrow-left"></i></button>
        <h2><i class="fas fa-history"></i> Transaction History</h2>
    </div>
</div>

<!-- Stats Bar -->
<div class="stats-bar">
    <div class="stats-inner">
        <div class="stat-box">
            <div class="val"><?= CURRENCY ?><?= number_format($user['balance'],0) ?></div>
            <?php if($_h_uc): ?><div style="color:rgba(255,255,255,0.5);font-size:10px;margin-top:1px"><?= htmlspecialchars($_h_uc['symbol']) ?><?= number_format($user['balance']*floatval($_h_uc['rate']),2) ?> <?= $_h_uc['code'] ?></div><?php endif; ?>
            <div class="lbl">Balance</div>
        </div>
        <div class="stat-box">
            <div class="val"><?= CURRENCY ?><?= number_format($totalSpent,0) ?></div>
            <?php if($_h_uc): ?><div style="color:rgba(255,255,255,0.5);font-size:10px;margin-top:1px"><?= htmlspecialchars($_h_uc['symbol']) ?><?= number_format($totalSpent*floatval($_h_uc['rate']),2) ?> <?= $_h_uc['code'] ?></div><?php endif; ?>
            <div class="lbl">Total Recharge</div>
        </div>
        <div class="stat-box">
            <div class="val"><?= CURRENCY ?><?= number_format($totalDeposit,0) ?></div>
            <?php if($_h_uc): ?><div style="color:rgba(255,255,255,0.5);font-size:10px;margin-top:1px"><?= htmlspecialchars($_h_uc['symbol']) ?><?= number_format($totalDeposit*floatval($_h_uc['rate']),2) ?> <?= $_h_uc['code'] ?></div><?php endif; ?>
            <div class="lbl">Total Deposit</div>
        </div>
    </div>
</div>

<div class="main">

    <!-- Main Tabs: History | My Cards -->
    <div class="main-tabs">
        <button class="main-tab <?= $activeTab==='history'?'active':'' ?>" onclick="switchMainTab('history')">
            <i class="fas fa-history"></i> Transactions
        </button>
        <button class="main-tab <?= $activeTab==='cards'?'active':'' ?>" onclick="switchMainTab('cards')">
            <i class="fas fa-credit-card"></i> My Cards
            <?php if ($cardCount > 0): ?>
            <span class="tab-badge"><?= $cardCount ?></span>
            <?php endif; ?>
        </button>
    </div>

    <!-- ===== MY CARDS SECTION ===== -->
    <div id="cardsSection" style="display:<?= $activeTab==='cards'?'block':'none' ?>">
        <?php
        // Merge user_cards + card transactions
        $allCardItems = [];

        // From user_cards table (has PIN code)
        foreach ($myCards as $c) {
            $allCardItems[$c['transaction_ref']] = [
                'ref'       => $c['transaction_ref'],
                'type'      => $c['card_type'] ?? 'card',
                'name'      => $c['card_name'],
                'pin'       => $c['pin_code'],
                'amount'    => $c['amount'],
                'currency'  => $c['currency'],
                'status'    => $c['status'],
                'created_at'=> $c['created_at'],
                'from_cards'=> true,
            ];
        }

        // From transactions (fallback - no PIN)
        foreach ($cardTxns as $t) {
            if (!isset($allCardItems[$t['reference']])) {
                $allCardItems[$t['reference']] = [
                    'ref'       => $t['reference'],
                    'type'      => $t['type'],
                    'name'      => $t['note'] ?? ucfirst($t['type']),
                    'pin'       => null,
                    'amount'    => $t['amount'],
                    'currency'  => CURRENCY,
                    'status'    => $t['status'],
                    'created_at'=> $t['created_at'],
                    'from_cards'=> false,
                ];
            }
        }

        // Sort by date
        usort($allCardItems, fn($a,$b) => strtotime($b['created_at']) - strtotime($a['created_at']));

        $cardTypeConfig = [
            'pin'           => ['icon'=>'fa-key',   'class'=>'pin',  'label'=>'Recharge PIN',  'emoji'=>'🔑'],
            'gift'          => ['icon'=>'fa-gift',  'class'=>'gift', 'label'=>'Gift Card',      'emoji'=>'🎁'],
            'calling'       => ['icon'=>'fa-phone', 'class'=>'card', 'label'=>'Calling Card',   'emoji'=>'📞'],
            'card'          => ['icon'=>'fa-phone', 'class'=>'card', 'label'=>'Calling Card',   'emoji'=>'📞'],
            'international' => ['icon'=>'fa-globe', 'class'=>'pin',  'label'=>'International',  'emoji'=>'🌍'],
        ];
        ?>

        <?php if (empty($allCardItems)): ?>
        <div class="empty">
            <i class="fas fa-credit-card"></i>
            <p>No cards purchased yet</p>
        </div>
        <?php else: ?>
        <?php foreach ($allCardItems as $item):
            $cfg = $cardTypeConfig[$item['type']] ?? $cardTypeConfig['card'];
        ?>
        <div class="my-card-item">
            <div class="mc-header">
                <div class="mc-icon <?= $cfg['class'] ?>">
                    <i class="fas <?= $cfg['icon'] ?>"></i>
                </div>
                <div class="mc-info">
                    <div class="mc-name"><?= $cfg['emoji'] ?> <?= htmlspecialchars($item['name']) ?></div>
                    <div class="mc-sub">
                        <?= $cfg['label'] ?> &bull;
                        <?= date('d M Y, h:i A', strtotime($item['created_at'])) ?>
                    </div>
                </div>
                <div class="mc-amount">
                    <div class="mc-price">-<?= CURRENCY ?><?= number_format($item['amount'],2) ?></div>
                    <?php if($_h_uc && floatval($_h_uc['rate'])>0): ?>
                    <div style="font-size:10px;color:#aaa;font-weight:500;margin-top:2px">
                        ≈ <?= htmlspecialchars($_h_uc['symbol']) ?><?= number_format($item['amount']*floatval($_h_uc['rate']),2) ?> <?= $_h_uc['code'] ?>
                    </div>
                    <?php endif; ?>
                    <div class="mc-status">
                        <span class="badge badge-<?= $item['status'] ?>"><?= ucfirst($item['status']) ?></span>
                    </div>
                </div>
            </div>

            <?php if ($item['pin']): ?>
            <div class="pin-reveal">
                <div class="pin-box-card <?= $cfg['class'] ?>">
                    <div class="pin-box-label">
                        <?= $cfg['emoji'] ?> <?= $cfg['label'] ?> Code
                    </div>
                    <div class="pin-box-code" id="pin_<?= md5($item['ref']) ?>"><?= htmlspecialchars($item['pin']) ?></div>
                    <button class="copy-pin-btn" onclick="copyCardPin('<?= htmlspecialchars($item['pin']) ?>', this)">
                        <i class="fas fa-copy"></i> Copy Code
                    </button>
                </div>
                <div style="display:flex;justify-content:space-between;margin-top:10px;font-size:12px;color:#aaa">
                    <span>Ref: <?= $item['ref'] ?></span>
                    <span><?= $item['currency'] ?> <?= $item['amount'] ?></span>
                </div>
            </div>
            <?php elseif ($item['status'] === 'pending'): ?>
            <div class="pending-pin">
                ⏳ Awaiting admin approval — PIN will be provided after approval
            </div>
            <?php else: ?>
            <div class="pending-pin" style="background:#f0f4ff;color:#1a3c8f">
                📋 Ref: <?= $item['ref'] ?>
            </div>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <!-- ===== TRANSACTION HISTORY SECTION ===== -->
    <div id="historySection" style="display:<?= $activeTab==='history'?'block':'none' ?>">

    <!-- Status Tabs -->
    <div class="tabs-wrap">
        <?php
        $tabs = [
            'all'        => ['📋 All',          null],
            'pending'    => ['⏳ Pending',      '#d69e2e'],
            'processing' => ['🔄 Processing',   '#3182ce'],
            'success'    => ['✅ Successful',          '#38a169'],
            'refunded'   => ['↩️ Refund',       '#805ad5'],
            'failed'     => ['❌ Rejected',      '#e53e3e'],
        ];
        foreach ($tabs as $s => [$label, $color]):
        $active = $status === $s;
        ?>
        <a href="?status=<?= $s ?><?= $search ? '&search='.urlencode($search) : '' ?>" class="tab <?= $active?'active':'' ?>">
            <?= $label ?>
            <span class="cnt"><?= $counts[$s] ?? 0 ?></span>
        </a>
        <?php endforeach; ?>
    </div>

    <!-- Search -->
    <form method="GET">
        <input type="hidden" name="status" value="<?= $status ?>">
        <div class="search-wrap">
            <i class="fas fa-search"></i>
            <input type="text" name="search" placeholder="Phone Number or Reference Search..." value="<?= $search ?>">
        </div>
    </form>

    <!-- Transaction List -->
    <?php if (empty($txns)): ?>
    <div class="empty">
        <i class="fas fa-inbox"></i>
        <p>No transactions Not found</p>
        <small><?= $status !== 'all' ? ucfirst($status).' No transactions' : ' No transactions not done' ?></small>
    </div>
    <?php else: ?>

    <?php foreach ($txns as $t):
        $isPlus = in_array($t['type'], ['deposit','commission','refund']);

        $typeConfig = [
            'topup'         => ['icon'=>'fa-mobile-alt',   'label'=>'Mobile Recharge',  'color'=>'#1a3c8f', 'bg'=>'#e8f0fe', 'emoji'=>'📱'],
            'deposit'       => ['icon'=>'fa-plus-circle',  'label'=>'Deposit',           'color'=>'#38a169', 'bg'=>'#f0fff4', 'emoji'=>'💰'],
            'refund'        => ['icon'=>'fa-undo',          'label'=>'Refund',            'color'=>'#805ad5', 'bg'=>'#faf5ff', 'emoji'=>'↩️'],
            'package_fee'   => ['icon'=>'fa-tags',         'label'=>'Package Upgrade',   'color'=>'#805ad5', 'bg'=>'#faf5ff', 'emoji'=>'🎯'],
            'drive'         => ['icon'=>'fa-bolt',          'label'=>'Drive',             'color'=>'#d69e2e', 'bg'=>'#fff8e6', 'emoji'=>'⚡'],
            'commission'    => ['icon'=>'fa-percent',       'label'=>'Commission',        'color'=>'#38a169', 'bg'=>'#f0fff4', 'emoji'=>'💸'],
            'international' => ['icon'=>'fa-globe',         'label'=>'Intl Recharge',     'color'=>'#2856c8', 'bg'=>'#ebf4ff', 'emoji'=>'🌍'],
            'pin'           => ['icon'=>'fa-key',           'label'=>'Recharge PIN',      'color'=>'#b7791f', 'bg'=>'#fffaf0', 'emoji'=>'🔑'],
            'card'          => ['icon'=>'fa-phone',         'label'=>'Calling Card',      'color'=>'#2c7a7b', 'bg'=>'#e6fffa', 'emoji'=>'📞'],
            'gift'          => ['icon'=>'fa-gift',          'label'=>'Gift Card',         'color'=>'#805ad5', 'bg'=>'#faf5ff', 'emoji'=>'🎁'],
            'mbanking'      => ['icon'=>'fa-university',    'label'=>'M.Banking',         'color'=>'#319795', 'bg'=>'#e6fffa', 'emoji'=>'🏦'],
            'bill'          => ['icon'=>'fa-receipt',       'label'=>'Bill Pay',          'color'=>'#2c7a7b', 'bg'=>'#e6fffa', 'emoji'=>'🧾'],
            'manual_drive'  => ['icon'=>'fa-hand-paper',   'label'=>'Manual Drive',      'color'=>'#276749', 'bg'=>'#f0fff4', 'emoji'=>'📦'],
        ];

        $cfg = $typeConfig[$t['type']] ?? ['icon'=>'fa-exchange-alt','label'=>ucfirst($t['type']),'color'=>'#1a3c8f','bg'=>'#e8f0fe','emoji'=>'💳'];
        $typeLabel = $cfg['label'];
        $typeIcon  = $cfg['icon'];
        $typeColor = $cfg['color'];
        $typeBg    = $cfg['bg'];
        $typeEmoji = $cfg['emoji'];

        // Note থেকে extra info বের করো
        $noteInfo = '';
        if (in_array($t['type'], ['international','pin','gift','card'])) {
            if ($t['note']) {
                // Country info
                preg_match('/country[:\s]+([A-Z]{2})/i', $t['note'], $m);
                if (!empty($m[1])) $noteInfo = '🌍 '.$m[1];
                // Provider name
                if (strpos($t['note'], '|') !== false) {
                    $parts = explode('|', $t['note']);
                    $noteInfo = trim($parts[0]);
                    if (strlen($noteInfo) > 40) $noteInfo = substr($noteInfo, 0, 40).'...';
                }
            }
        }
        // Build smart title — short product name
        $prodTitle = $typeLabel;
        if (!empty($t['note'])) {
            $noteClean = $t['note'];
            // Remove PKG/OP metadata
            $noteClean = preg_replace('/\s*\|\s*(PKG|OP|OP_NAME):[^\|]+/', '', $noteClean);
            $noteClean = trim($noteClean);
            // For topup/drive use note as title if it has operator
            if(in_array($t['type'],['topup','drive']) && strlen($noteClean) < 50) {
                $prodTitle = $noteClean;
            }
            // For card/commission use note excerpt
            if($t['type']==='card' && strlen($noteClean) < 60) {
                $parts = explode(':', $noteClean, 2);
                $prodTitle = trim($parts[1] ?? $noteClean);
            }
        }
        if(strlen($prodTitle) > 30) $prodTitle = substr($prodTitle, 0, 28).'...';

        // Prepare commission data for modal
        $commData = [];
        if($t['type'] === 'commission') {
            $cn2 = $t['note'] ?? '';
            preg_match('/Ref:\s*([A-Z0-9]+)/i', $cn2, $cRef2);
            preg_match('/\((\d+(?:\.\d+)?%)\)/', $cn2, $cRate2);
            if(empty($cRate2[1])) preg_match('/:\s*(\d+(?:\.\d+)?%)/', $cn2, $cRate2);
            preg_match('/Package:\s*(.+?)(?:\s*—|$)/i', $cn2, $cPkg2);
            $cOrigRef = $cRef2[1] ?? '';
            $cRate    = $cRate2[1] ?? '';
            $cPkgN    = trim($cPkg2[1] ?? '');
            $cType    = stripos($cn2,'drive')!==false ? 'drive' : (stripos($cn2,'topup')!==false ? 'topup' : (stripos($cn2,'international')!==false ? 'international' : (stripos($cn2,'card')!==false ? 'card' : (stripos($cn2,'pin')!==false ? 'pin' : 'other'))));
            // Fetch original
            $cOrig = null;
            if($cOrigRef) {
                try { $cs2=$db->prepare("SELECT t.*,o.name as orig_op,p.name as orig_pkg FROM transactions t LEFT JOIN operators o ON t.operator_id=o.id LEFT JOIN packages p ON t.package_id=p.id WHERE t.reference=? LIMIT 1"); $cs2->execute([$cOrigRef]); $cOrig=$cs2->fetch(); } catch(Exception $e){}
            }
            if(!$cOrig && $cType==='drive') {
                $dRef = preg_replace('/^CM-/','',$t['reference']);
                try { $cs2=$db->prepare("SELECT t.*,o.name as orig_op,p.name as orig_pkg FROM transactions t LEFT JOIN operators o ON t.operator_id=o.id LEFT JOIN packages p ON t.package_id=p.id WHERE t.reference=? LIMIT 1"); $cs2->execute([$dRef]); $cOrig=$cs2->fetch(); } catch(Exception $e){}
            }
            $tl2=['topup'=>'📱 Mobile Recharge','international'=>'🌍 Intl Recharge','drive'=>'🚗 Drive','card'=>'🎴 Card','pin'=>'📟 PIN','gift'=>'🎁 Gift','mbanking'=>'💳 Mobile Banking'];
            $commData = [
                'rate'    => $cRate,
                'pkg'     => $cPkgN,
                'type'    => $tl2[$cOrig['type']??$cType] ?? ucfirst($cType),
                'phone'   => $cOrig['phone_number'] ?? '',
                'op'      => $cOrig['orig_op'] ?? '',
                'pkg2'    => $cOrig['orig_pkg'] ?? '',
                'amount'  => $cOrig ? '৳'.number_format($cOrig['amount'],2) : '',
                'ref'     => $cOrigRef,
            ];
        }

        // Prepare product detail data for modal
        $detData = [];
        switch($t['type']) {
            case 'topup':
                if($t['phone_number']) $detData[] = ['📱', 'Mobile Number', $t['phone_number']];
                if($t['op_name'])      $detData[] = ['📡', 'Operator', $t['op_name']];
                if($t['pkg_name'])     $detData[] = ['📦', 'Package', $t['pkg_name']];
                if(preg_match('/TrxID[:\s]+(\S+)/i', $t['note']??'', $tm)) $detData[] = ['🔑', 'TrxID', $tm[1]];
                break;
            case 'international':
                if($t['phone_number']) $detData[] = ['📱', 'Mobile Number', $t['phone_number']];
                if($t['pkg_name'])     $detData[] = ['📦', 'Package', $t['pkg_name']];
                if(preg_match('/International:\s*([A-Z]+)/i', $t['note']??'', $cm2)) $detData[] = ['🌍', 'Country', $cm2[1]];
                break;
            case 'drive':
                if($t['pkg_name']) $detData[] = ['📦', 'Package', $t['pkg_name']];
                if($t['op_name'])  $detData[] = ['📡', 'Operator', $t['op_name']];
                break;
            case 'card': case 'pin': case 'gift':
                $pn = $t['pkg_name'] ?: $t['op_name'] ?: '';
                if($pn) $detData[] = ['🎴', 'Product', $pn];
                try {
                    $cardRow2 = $db->prepare("SELECT pin_code,pin_serial,expiry FROM user_cards WHERE reference=? LIMIT 1");
                    $cardRow2->execute([$t['reference']]); $card2 = $cardRow2->fetch();
                    if($card2) {
                        if($card2['pin_code'])   $detData[] = ['🔑', 'PIN Code', $card2['pin_code']];
                        if($card2['pin_serial'])  $detData[] = ['🔢', 'Serial', $card2['pin_serial']];
                        if($card2['expiry'])      $detData[] = ['📅', 'Expiry', $card2['expiry']];
                    }
                } catch(Exception $e){}
                break;
            case 'deposit':
                $dn = trim(preg_replace('/\s*\|.*$/','',$t['note']??''));
                if($dn) $detData[] = ['💳', 'Method', $dn];
                break;
            case 'refund':
                if(preg_match('/[-\s]([A-Z0-9]{6,})/i', $t['note']??'', $rm)) $detData[] = ['🔖', 'Original Ref', $rm[1]];
                break;
            case 'mbanking':
                if($t['phone_number']) $detData[] = ['💳', 'Account', $t['phone_number']];
                if($t['op_name'])      $detData[] = ['🏦', 'Method', $t['op_name']];
                break;
        }
    ?>
    <div class="txn-card <?= $t['status'] ?>" id="card-<?= $t['id'] ?>">
        <div class="txn-card-header"
            onclick="openDetModal(this)"
            data-id="<?= $t['id'] ?>"
            data-type="<?= $t['type'] ?>"
            data-emoji="<?= $typeEmoji ?>"
            data-label="<?= htmlspecialchars($typeLabel,ENT_QUOTES) ?>"
            data-amount="<?= number_format($t['amount'],2) ?>"
            data-isplus="<?= $isPlus?1:0 ?>"
            data-phone="<?= htmlspecialchars($t['phone_number']??'',ENT_QUOTES) ?>"
            data-op="<?= htmlspecialchars($t['op_name']??'',ENT_QUOTES) ?>"
            data-pkg="<?= htmlspecialchars($t['pkg_name']??'',ENT_QUOTES) ?>"
            data-ref="<?= htmlspecialchars($t['reference'],ENT_QUOTES) ?>"
            data-status="<?= $t['status'] ?>"
            data-date="<?= date('d M Y, h:i A', strtotime($t['created_at'])) ?>"
            data-balbefore="<?= CURRENCY ?><?= number_format($t['balance_before'],2) ?><?= ($_h_uc && floatval($_h_uc['rate'])>0) ? ' ≈ '.htmlspecialchars($_h_uc['symbol']).number_format($t['balance_before']*floatval($_h_uc['rate']),2).' '.$_h_uc['code'] : '' ?>"
            data-balafter="<?= CURRENCY ?><?= number_format($t['balance_after'],2) ?><?= ($_h_uc && floatval($_h_uc['rate'])>0) ? ' ≈ '.htmlspecialchars($_h_uc['symbol']).number_format($t['balance_after']*floatval($_h_uc['rate']),2).' '.$_h_uc['code'] : '' ?>"
            data-dual="<?= ($_h_uc && floatval($_h_uc['rate'])>0) ? htmlspecialchars($_h_uc['symbol']).number_format($t['amount']*floatval($_h_uc['rate']),2).' '.$_h_uc['code'] : '' ?>"
            data-commjson="<?= $commData ? htmlspecialchars(json_encode($commData,JSON_UNESCAPED_UNICODE),ENT_QUOTES) : '' ?>"
            data-detjson="<?= $detData ? htmlspecialchars(json_encode(array_values($detData),JSON_UNESCAPED_UNICODE),ENT_QUOTES) : '' ?>"
            data-note="<?php
                $noteShow = '';
                $nt = $t['note'] ?? '';
                // System/auto notes to hide
                $autoNotes = ['Admin approved', 'recharge completed', 'Admin approved - recharge completed', 'Processing', 'Rejected & refunded', 'Refund for rejected', 'DingConnect', 'commission', 'Commission', 'ST Success', 'ECARE'];
                $isAuto = false;
                foreach($autoNotes as $an) {
                    if(stripos($nt, $an) !== false) { $isAuto = true; break; }
                }
                if($nt && !$isAuto && strlen(trim($nt)) > 2) {
                    $noteShow = trim($nt);
                }
                echo htmlspecialchars($noteShow, ENT_QUOTES);
            ?>">
            <div class="txn-icon" style="background:<?= $typeBg ?>;color:<?= $typeColor ?>">
                <i class="fas <?= $typeIcon ?>"></i>
            </div>
            <div class="txn-info">
                <div class="txn-title">
                    <?= $typeEmoji ?> <?= htmlspecialchars($prodTitle) ?>
                </div>
                <div class="txn-sub">
                    <?php if ($t['phone_number']): ?>
                        <?= $t['phone_number'] ?>
                    <?php elseif ($t['op_name']): ?>
                        <?= htmlspecialchars($t['op_name']) ?>
                    <?php else: ?>
                        <?= $t['reference'] ?>
                    <?php endif; ?>
                    &bull; <?= date('d M, h:i A', strtotime($t['created_at'])) ?>
                </div>
                <?php if (in_array($t['status'], ['pending','processing'])): ?>
                <div class="pending-notice">
                    <i class="fas fa-clock"></i>
                    <?= $t['status']==='pending' ? 'Awaiting Admin Approval' : 'Processing...' ?>
                </div>
                <?php endif; ?>
            </div>
            <div class="txn-right">
                <div class="txn-amount <?= $isPlus ? 'plus' : ($t['type']==='refund'?'refund-c':'minus') ?>">
                    <?= $isPlus ? '+' : '-' ?><?= CURRENCY ?><?= number_format($t['amount'],2) ?>
                    <?php if($_h_uc && floatval($_h_uc['rate'])>0): ?>
                    <div style="font-size:10px;color:#aaa;font-weight:500">
                        ≈ <?= htmlspecialchars($_h_uc['symbol']) ?><?= number_format($t['amount']*floatval($_h_uc['rate']),2) ?> <?= $_h_uc['code'] ?>
                    </div>
                    <?php endif; ?>
                </div>
                <div class="txn-status">
                    <span class="badge badge-<?= $t['status'] ?>"><?= ucfirst($t['status']) ?></span>
                </div>
            </div>
            <i class="fas fa-chevron-right" style="color:#ddd;font-size:12px;margin-left:4px"></i>
        </div>

        <!-- Detail stored in data attrs, shown in modal -->
        <div style="display:none" id="detail-<?= $t['id'] ?>">
            <div class="detail-grid">
                <div class="detail-item">
                    <div class="d-label">Type</div>
                    <div class="d-val"><?= $typeEmoji ?> <?= $typeLabel ?></div>
                </div>
                <div class="detail-item">
                    <div class="d-label">Amount</div>
                    <div class="d-val" style="color:<?= $isPlus?'#38a169':'#e53e3e' ?>;font-size:16px">
                        <?= $isPlus?'+':'-' ?><?= CURRENCY ?><?= number_format($t['amount'],2) ?>
                        <?php if($_h_uc && floatval($_h_uc['rate'])>0): ?>
                        <span style="font-size:12px;color:#888;font-weight:500"> ≈ <?= htmlspecialchars($_h_uc['symbol']) ?><?= number_format($t['amount']*floatval($_h_uc['rate']),2) ?> <?= $_h_uc['code'] ?></span>
                        <?php endif; ?>
                    </div>
                </div>
                <?php if ($t['phone_number']): ?>
                <div class="detail-item">
                    <div class="d-label">Mobile Number</div>
                    <div class="d-val" style="font-family:monospace;font-size:15px"><?= $t['phone_number'] ?></div>
                </div>
                <?php endif; ?>
                <?php if ($t['op_name']): ?>
                <div class="detail-item">
                    <div class="d-label">Operator</div>
                    <div class="d-val"><?= $t['op_name'] ?></div>
                </div>
                <?php endif; ?>
                <?php if ($t['pkg_name']): ?>
                <div class="detail-item">
                    <div class="d-label">Package</div>
                    <div class="d-val"><?= $t['pkg_name'] ?></div>
                </div>
                <?php endif; ?>
                <?php
                if ($t['note']) {
                    $noteDisplay = '';
                    $noteLabel   = 'Note';
                    if ($t['type'] === 'topup') {
                        if (preg_match('/TrxID[:\s]+(\S+)/i', $t['note'], $trxm)) {
                            $noteDisplay = 'TrxID: '.$trxm[1];
                            $noteLabel   = 'Transaction ID';
                        }
                    } elseif ($t['type'] !== 'commission') {
                        $nd = $t['note'];
                        $nd = preg_replace('/\s*\|\s*(PKG|OP|OP_NAME|API):[^\|]+/', '', $nd);
                        $nd = preg_replace('/\s*Ref:\s*\w+/i', '', $nd);
                        $nd = trim($nd, " \t\n\r\0\x0B|");
                        if (strlen($nd) > 3) $noteDisplay = $nd;
                    }
                    if ($noteDisplay):
                ?>
                <div class="detail-item full">
                    <div class="d-label"><?= $noteLabel ?></div>
                    <div class="d-val" style="font-size:13px;font-weight:700;font-family:monospace;color:#1a3c8f"><?= htmlspecialchars($noteDisplay) ?></div>
                </div>
                <?php endif; }

                // Commission — show original transaction full details
                if($t['type'] === 'commission'):
                    $cn = $t['note'] ?? '';
                    // Format 1: "Topup commission (3%) on Ref: PT873D — Package: Gold"
                    // Format 2: "Drive commission: 10% of ?95.00"
                    // Format 3: "Card commission (4%) (base: ?10) on Ref: CD0A — Package: Platinum"

                    preg_match('/Ref:\s*([A-Z0-9]+)/i', $cn, $commRefM);
                    preg_match('/\((\d+(?:\.\d+)?%)\)/', $cn, $commRateM);
                    if(empty($commRateM[1])) preg_match('/:\s*(\d+(?:\.\d+)?%)/', $cn, $commRateM);
                    preg_match('/Package:\s*(.+?)(?:\s*—|$)/i', $cn, $commPkgM);

                    $commOrigRef = $commRefM[1] ?? '';
                    $commRate    = $commRateM[1] ?? '';
                    $commPkgName = trim($commPkgM[1] ?? '');

                    // Detect type from note text
                    $commType = 'purchase';
                    if(stripos($cn,'drive')!==false)             $commType = 'drive';
                    elseif(stripos($cn,'topup')!==false)         $commType = 'topup';
                    elseif(stripos($cn,'international')!==false) $commType = 'international';
                    elseif(stripos($cn,'card')!==false)          $commType = 'card';
                    elseif(stripos($cn,'pin')!==false)           $commType = 'pin';
                    elseif(stripos($cn,'gift')!==false)          $commType = 'gift';

                    // Fetch original transaction
                    $commOrig = null;
                    // Try direct ref first
                    if($commOrigRef) {
                        try {
                            $cs = $db->prepare("SELECT t.*, o.name as orig_op, p.name as orig_pkg FROM transactions t LEFT JOIN operators o ON t.operator_id=o.id LEFT JOIN packages p ON t.package_id=p.id WHERE t.reference=? LIMIT 1");
                            $cs->execute([$commOrigRef]); $commOrig = $cs->fetch();
                        } catch(Exception $e){}
                    }
                    // Drive: ref is CM-PTXXXXXX → strip CM- to get PT...
                    if(!$commOrig && $commType==='drive') {
                        $driveRef = preg_replace('/^CM-/', '', $t['reference']);
                        try {
                            $cs = $db->prepare("SELECT t.*, o.name as orig_op, p.name as orig_pkg FROM transactions t LEFT JOIN operators o ON t.operator_id=o.id LEFT JOIN packages p ON t.package_id=p.id WHERE t.reference=? LIMIT 1");
                            $cs->execute([$driveRef]); $commOrig = $cs->fetch();
                        } catch(Exception $e){}
                    }

                    $typeLabels = [
                        'topup'=>'📱 Mobile Recharge','international'=>'🌍 International Recharge',
                        'drive'=>'🚗 Drive','card'=>'🎴 Card','pin'=>'📟 PIN/Calling Card',
                        'gift'=>'🎁 Gift Card','bill'=>'🧾 Bill Pay','mbanking'=>'💳 Mobile Banking',
                    ];
                    $origTypeLabel = $typeLabels[$commOrig['type'] ?? $commType] ?? ucfirst($commType);
                ?>
                <div class="detail-item full">
                    <div style="background:#f0fff4;border-radius:10px;padding:0;border:1px solid #9ae6b4;overflow:hidden">
                        <div style="background:#276749;padding:8px 12px;display:flex;align-items:center;justify-content:space-between">
                            <span style="font-size:12px;font-weight:800;color:white">💸 Commission Details</span>
                            <span style="font-size:14px;font-weight:800;color:#9ae6b4">+৳<?= number_format($t['amount'],2) ?></span>
                        </div>
                        <div style="padding:10px 12px">
                        <?php
                        $rows = [];
                        if($commRate)    $rows[] = ['📊 Commission Rate', $commRate];
                        if($commPkgName) $rows[] = ['💎 User Package', $commPkgName];
                        if($commOrig) {
                            $rows[] = ['🛍️ Product', $origTypeLabel];
                            if(!empty($commOrig['phone_number']))  $rows[] = ['📱 Number', $commOrig['phone_number']];
                            if(!empty($commOrig['orig_op']))       $rows[] = ['📡 Operator', $commOrig['orig_op']];
                            if(!empty($commOrig['orig_pkg']))      $rows[] = ['📦 Package', $commOrig['orig_pkg']];
                            if($commOrig['type']==='international') {
                                if(preg_match('/International:\s*([A-Z]+)/i', $commOrig['note']??'', $cm))
                                    $rows[] = ['🌍 Country', $cm[1]];
                                if(!empty($commOrig['phone_number'])) $rows[] = ['📞 Account', $commOrig['phone_number']];
                            }
                            if(in_array($commOrig['type'],['card','pin','gift'])) {
                                $cardNote = trim(preg_replace('/\s*\|.*$/','', $commOrig['note']??''));
                                if($cardNote) $rows[] = ['🎴 Details', $cardNote];
                            }
                            if(!empty($commOrig['amount'])) $rows[] = ['💰 Purchase Amount', '৳'.number_format($commOrig['amount'],2)];
                        }
                        if($commOrigRef) $rows[] = ['🔖 Original Ref', $commOrigRef];
                        foreach($rows as $i => $row):
                            if(empty($row[1])) continue;
                            $isLast = ($i === array_key_last($rows));
                        ?>
                        <div style="display:flex;justify-content:space-between;align-items:center;font-size:12px;padding:6px 0;<?= !$isLast?'border-bottom:1px solid #c6f6d5':'' ?>">
                            <span style="color:#555"><?= $row[0] ?></span>
                            <span style="font-weight:700;color:#1a1a2e;text-align:right;max-width:60%"><?= htmlspecialchars($row[1]) ?></span>
                        </div>
                        <?php endforeach; ?>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                <div class="detail-item">
                    <div class="d-label">Previous Balance</div>
                    <div class="d-val" style="color:#e53e3e"><?= CURRENCY ?><?= number_format($t['balance_before'],2) ?><?php if($_h_uc && floatval($_h_uc['rate'])>0): ?> <span style="font-size:11px;color:#aaa">≈ <?= htmlspecialchars($_h_uc['symbol']) ?><?= number_format($t['balance_before']*floatval($_h_uc['rate']),2) ?> <?= $_h_uc['code'] ?></span><?php endif; ?></div>
                </div>
                <div class="detail-item">
                    <div class="d-label">New Balance</div>
                    <div class="d-val" style="color:#38a169"><?= CURRENCY ?><?= number_format($t['balance_after'],2) ?><?php if($_h_uc && floatval($_h_uc['rate'])>0): ?> <span style="font-size:11px;color:#aaa">≈ <?= htmlspecialchars($_h_uc['symbol']) ?><?= number_format($t['balance_after']*floatval($_h_uc['rate']),2) ?> <?= $_h_uc['code'] ?></span><?php endif; ?></div>
                </div>
                <div class="detail-item">
                    <div class="d-label">Date & Time</div>
                    <div class="d-val"><?= date('d M Y, h:i A', strtotime($t['created_at'])) ?></div>
                </div>
                <div class="detail-item">
                    <div class="d-label">Status</div>
                    <div class="d-val"><span class="badge badge-<?= $t['status'] ?>"><?= ucfirst($t['status']) ?></span></div>
                </div>
                <?php
                // API status for pending topup/drive
                if ($t['status']==='pending' && $t['api_response']) {
                    $apiArr = json_decode($t['api_response'], true);
                    $apiMsg = $apiArr['MESSAGE'] ?? $apiArr['message'] ?? $apiArr['RECHARGE_STATUS'] ?? '';
                    if ($apiMsg): ?>
                <div class="detail-item full">
                    <div class="d-label">API Status</div>
                    <div class="d-val" style="font-size:11px;color:#888;font-family:monospace;background:#f8f8f8;padding:6px 8px;border-radius:6px"><?= htmlspecialchars($apiMsg) ?></div>
                </div>
                    <?php endif;
                }
                ?>
            </div>
            <div class="ref-box">
                <span id="ref-<?= $t['id'] ?>"><?= $t['reference'] ?></span>
                <button class="copy-btn" onclick="copyRef('<?= $t['reference'] ?>', <?= $t['id'] ?>)">
                    <i class="fas fa-copy"></i> Copy
                </button>
            </div>

            <?php
            $comm = $commissionMap[$t['reference']] ?? null;
            if($comm && $t['type'] !== 'commission'):
                preg_match('/(\d+(?:\.\d+)?%)/i', $comm['note'], $rateM);
                $commRate  = $rateM[1] ?? '';
                $commOrig2 = $comm['orig'] ?? null;
                $origPhone = $commOrig2['phone_number'] ?? $t['phone_number'] ?? '';
                $origOp    = $commOrig2['orig_op']      ?? '';
                $origPkg2  = $commOrig2['orig_pkg']     ?? '';
                $typeLabels2 = [
                    'topup'=>'Mobile Recharge','international'=>'Intl Recharge',
                    'drive'=>'Drive','card'=>'Card','pin'=>'PIN',
                    'gift'=>'Gift Card','bill'=>'Bill Pay','mbanking'=>'Mobile Banking'
                ];
                $origType = $typeLabels2[$commOrig2['type'] ?? $t['type']] ?? ucfirst($t['type']);
            ?>
            <div style="margin:0 14px 14px;background:linear-gradient(135deg,#f0fff4,#e6fffa);border:1px solid #9ae6b4;border-radius:12px;padding:12px 14px">
                <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px">
                    <div style="font-size:12px;font-weight:800;color:#276749;display:flex;align-items:center;gap:6px">
                        <i class="fas fa-coins" style="color:#38a169"></i> Commission Earned
                    </div>
                    <div style="font-size:16px;font-weight:800;color:#38a169">+৳<?= number_format($comm['amount'],2) ?></div>
                </div>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:6px;font-size:11px;color:#444">
                    <div style="background:rgba(255,255,255,0.7);border-radius:8px;padding:7px 10px">
                        <div style="color:#888;margin-bottom:2px">Type</div>
                        <div style="font-weight:700">📱 <?= $origType ?></div>
                    </div>
                    <?php if($origPhone): ?>
                    <div style="background:rgba(255,255,255,0.7);border-radius:8px;padding:7px 10px">
                        <div style="color:#888;margin-bottom:2px">Number</div>
                        <div style="font-weight:700;font-family:monospace"><?= $origPhone ?></div>
                    </div>
                    <?php endif; ?>
                    <?php if($origOp): ?>
                    <div style="background:rgba(255,255,255,0.7);border-radius:8px;padding:7px 10px">
                        <div style="color:#888;margin-bottom:2px">Operator</div>
                        <div style="font-weight:700"><?= htmlspecialchars($origOp) ?></div>
                    </div>
                    <?php endif; ?>
                    <?php if($origPkg2): ?>
                    <div style="background:rgba(255,255,255,0.7);border-radius:8px;padding:7px 10px">
                        <div style="color:#888;margin-bottom:2px">Package</div>
                        <div style="font-weight:700"><?= htmlspecialchars($origPkg2) ?></div>
                    </div>
                    <?php endif; ?>
                    <?php if($commRate): ?>
                    <div style="background:rgba(255,255,255,0.7);border-radius:8px;padding:7px 10px">
                        <div style="color:#888;margin-bottom:2px">Rate</div>
                        <div style="font-weight:700">📊 <?= $commRate ?></div>
                    </div>
                    <?php endif; ?>
                    <div style="background:rgba(255,255,255,0.7);border-radius:8px;padding:7px 10px">
                        <div style="color:#888;margin-bottom:2px">Prev Balance</div>
                        <div style="font-weight:700">৳<?= number_format($comm['balance_before'],2) ?></div>
                    </div>
                    <div style="background:rgba(255,255,255,0.7);border-radius:8px;padding:7px 10px">
                        <div style="color:#888;margin-bottom:2px">New Balance</div>
                        <div style="font-weight:700;color:#38a169">৳<?= number_format($comm['balance_after'],2) ?></div>
                    </div>
                    <div style="background:rgba(255,255,255,0.7);border-radius:8px;padding:7px 10px;grid-column:1/-1">
                        <div style="color:#888;margin-bottom:2px">Time</div>
                        <div style="font-weight:700">🕐 <?= date('d M Y, h:i A', strtotime($comm['created_at'])) ?></div>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
    <?php endforeach; ?>
    <?php endif; ?>

    </div><!-- end historySection -->

</div><!-- end main -->

<script>
function switchMainTab(tab) {
    document.getElementById('historySection').style.display = tab==='history' ? 'block' : 'none';
    document.getElementById('cardsSection').style.display   = tab==='cards'   ? 'block' : 'none';
    document.querySelectorAll('.main-tab').forEach((el,i) => {
        el.classList.toggle('active', (i===0 && tab==='history') || (i===1 && tab==='cards'));
    });
    // Update URL
    const url = new URL(window.location);
    url.searchParams.set('tab', tab);
    window.history.pushState({}, '', url);
}

function openDetModal(el) {
    const d = el.dataset;
    const isPlus = d.isplus === '1';

    // Icon & colors
    const colors = {
        topup:'#1a3c8f', deposit:'#38a169', commission:'#805ad5',
        international:'#2b6cb0', pin:'#d69e2e', gift:'#e53e3e',
        card:'#319795', refund:'#805ad5', package_fee:'#e53e3e', drive:'#f5a623'
    };
    const color = colors[d.type] || '#718096';
    document.getElementById('dmIcon').textContent = d.emoji;
    document.getElementById('dmIcon').style.background = color+'22';
    document.getElementById('dmTitle').textContent = d.label;
    document.getElementById('dmSub').textContent = d.date;

    document.getElementById('dmType').innerHTML = d.emoji + ' ' + d.label;
    document.getElementById('dmAmount').textContent = (isPlus ? '+' : '-') + '৳' + d.amount;
    document.getElementById('dmAmount').style.color = isPlus ? '#38a169' : '#e53e3e';

    // Dual
    if (d.dual) {
        document.getElementById('dmDual').textContent = '≈ ' + d.dual;
        document.getElementById('dmDualRow').style.display = 'flex';
    } else {
        document.getElementById('dmDualRow').style.display = 'none';
    }

    // Phone
    if (d.phone) {
        document.getElementById('dmPhone').textContent = d.phone;
        document.getElementById('dmPhoneRow').style.display = 'flex';
    } else { document.getElementById('dmPhoneRow').style.display = 'none'; }

    // Operator
    if (d.op) {
        document.getElementById('dmOp').textContent = d.op;
        document.getElementById('dmOpRow').style.display = 'flex';
    } else { document.getElementById('dmOpRow').style.display = 'none'; }

    // Package
    if (d.pkg) {
        document.getElementById('dmPkg').textContent = d.pkg;
        document.getElementById('dmPkgRow').style.display = 'flex';
    } else { document.getElementById('dmPkgRow').style.display = 'none'; }

    document.getElementById('dmBalBefore').textContent = d.balbefore;
    document.getElementById('dmBalAfter').textContent  = d.balafter;
    document.getElementById('dmDate').textContent      = d.date;

    // Status badge
    const stColors = {success:'#38a169',pending:'#d69e2e',processing:'#2b6cb0',failed:'#e53e3e',refunded:'#805ad5'};
    const stc = stColors[d.status] || '#718096';
    document.getElementById('dmStatus').innerHTML = '<span style="background:'+stc+'22;color:'+stc+';padding:4px 12px;border-radius:20px;font-size:12px;font-weight:700">'+d.status.charAt(0).toUpperCase()+d.status.slice(1)+'</span>';

    document.getElementById('dmRef').textContent = d.ref;

    // Admin Note
    const noteSection = document.getElementById('dmNoteSection');
    const noteBody    = document.getElementById('dmNoteBody');
    const noteTitle   = document.getElementById('dmNoteTitle');
    const noteArrow   = document.getElementById('dmNoteArrow');
    noteSection.style.display = 'block';
    noteBody.style.display = 'none';
    noteArrow.style.transform = '';
    if(d.note && d.note.trim()) {
        noteTitle.textContent = d.note.length > 40 ? d.note.substring(0,38)+'...' : d.note;
        noteBody.textContent  = d.note;
        noteArrow.style.display = 'inline';
    } else {
        noteTitle.textContent   = d.status === 'success' ? '✅ Completed by Admin' : (d.status === 'pending' ? '⏳ Awaiting Admin' : 'Admin Note');
        noteBody.textContent    = '';
        noteArrow.style.display = 'none';
    }

    // Product details
    const detSection = document.getElementById('dmDetSection');
    const detRows    = document.getElementById('dmDetRows');
    const detTitle   = document.getElementById('dmDetTitle');
    if(d.detjson && d.type !== 'commission') {
        try {
            const items = JSON.parse(d.detjson);
            if(items.length > 0) {
                const titles = {topup:'📱 Recharge Details',international:'🌍 International Details',drive:'🚗 Drive Details',card:'🎴 Card Details',pin:'📟 PIN Details',gift:'🎁 Gift Details',deposit:'💰 Deposit Details',refund:'↩️ Refund Details',mbanking:'💳 Mobile Banking'};
                detTitle.textContent = titles[d.type] || '📋 Product Details';
                detRows.innerHTML = items.map((item,idx,arr)=>`
                    <div style="display:flex;justify-content:space-between;align-items:center;font-size:12px;padding:5px 0;${idx<arr.length-1?'border-bottom:1px solid #dce8ff':''}">
                        <span style="color:#555">${item[0]} ${item[1]}</span>
                        <span style="font-weight:700;color:#1a1a2e;text-align:right;max-width:60%;word-break:break-all">${item[2]}</span>
                    </div>`).join('');
                detSection.style.display = 'block';
            } else { detSection.style.display = 'none'; }
        } catch(e) { detSection.style.display = 'none'; }
    } else { detSection.style.display = 'none'; }

    // Commission details
    const commSection = document.getElementById('dmCommSection');
    const commRows    = document.getElementById('dmCommRows');
    if(d.commjson && d.type === 'commission') {
        try {
            const c = JSON.parse(d.commjson);
            const items = [
                ['📊 Rate', c.rate],
                ['💎 Package', c.pkg],
                ['🛍️ Product', c.type],
                ['📱 Number', c.phone],
                ['📡 Operator', c.op],
                ['📦 Package', c.pkg2],
                ['💰 Purchase', c.amount],
                ['🔖 Ref', c.ref],
            ];
            commRows.innerHTML = items.filter(i=>i[1]).map((item,idx,arr)=>`
                <div style="display:flex;justify-content:space-between;font-size:12px;padding:5px 0;${idx<arr.length-1?'border-bottom:1px solid #c6f6d5':''}">
                    <span style="color:#555">${item[0]}</span>
                    <span style="font-weight:700;color:#1a1a2e;text-align:right">${item[1]}</span>
                </div>`).join('');
            commSection.style.display = 'block';
        } catch(e) { commSection.style.display = 'none'; }
    } else {
        commSection.style.display = 'none';
    }

    document.getElementById('detModal').classList.add('show');
}

function closeDetModal() {
    document.getElementById('detModal').classList.remove('show');
}

function toggleAdminNote(){
    const body  = document.getElementById('dmNoteBody');
    const arrow = document.getElementById('dmNoteArrow');
    if(!body.textContent.trim()) return; // no content
    const open = body.style.display !== 'none';
    body.style.display  = open ? 'none' : 'block';
    arrow.style.transform = open ? '' : 'rotate(180deg)';
}

function copyField(elId, btnId) {
    const text = document.getElementById(elId).textContent;
    navigator.clipboard?.writeText(text).then(() => {
        const btn = document.getElementById(btnId);
        const orig = btn.innerHTML;
        btn.innerHTML = '✅ Copied!';
        btn.classList.add('copied');
        setTimeout(() => { btn.innerHTML = orig; btn.classList.remove('copied'); }, 2000);
    });
}

function toggleDetail(id) {
    const detail = document.getElementById('detail-' + id);
    const icon = document.getElementById('icon-' + id);
    const isOpen = detail.classList.contains('open');
    document.querySelectorAll('.txn-detail').forEach(d => d.classList.remove('open'));
    document.querySelectorAll('.expand-icon').forEach(i => i.style.transform = '');
    if (!isOpen) {
        detail.classList.add('open');
        icon.style.transform = 'rotate(180deg)';
    }
}

function copyRef(ref, id) {
    navigator.clipboard.writeText(ref).then(() => {
        const btn = document.querySelector('#card-' + id + ' .copy-btn');
        btn.innerHTML = '<i class="fas fa-check"></i> Copied!';
        btn.style.background = '#38a169';
        setTimeout(() => { btn.innerHTML = '<i class="fas fa-copy"></i> Copy'; btn.style.background = ''; }, 2000);
    });
}

function copyCardPin(pin, btn) {
    navigator.clipboard?.writeText(pin).then(() => {
        const orig = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-check"></i> Copied!';
        btn.style.background = 'rgba(255,255,255,0.4)';
        setTimeout(() => { btn.innerHTML = orig; btn.style.background = ''; }, 2000);
    });
}
</script>
<?php include 'includes/bottom_nav.php'; ?>

<!-- Transaction Detail Modal -->
<div class="det-modal-bg" id="detModal" onclick="if(event.target===this)closeDetModal()">
<div class="det-modal">
    <div class="det-header">
        <button class="det-close" onclick="closeDetModal()">✕</button>
        <div class="det-icon" id="dmIcon">💳</div>
        <div class="det-title" id="dmTitle">Transaction</div>
        <div class="det-sub" id="dmSub"></div>
    </div>
    <div class="det-body">
        <div class="det-row">
            <span class="det-lbl">Type</span>
            <span class="det-val" id="dmType"></span>
        </div>
        <div class="det-row">
            <span class="det-lbl">Amount</span>
            <span class="det-val" id="dmAmount" style="font-size:18px;font-weight:800"></span>
        </div>
        <div class="det-row" id="dmDualRow" style="display:none">
            <span class="det-lbl">Equivalent</span>
            <span class="det-val" id="dmDual" style="color:#b7791f"></span>
        </div>
        <div class="det-row" id="dmPhoneRow" style="display:none">
            <span class="det-lbl">Phone Number</span>
            <div style="display:flex;align-items:center;gap:8px">
                <span class="det-val" id="dmPhone"></span>
                <button class="det-copy-btn" onclick="copyField('dmPhone','phoneBtn')" id="phoneBtn">Copy</button>
            </div>
        </div>
        <div class="det-row" id="dmOpRow" style="display:none">
            <span class="det-lbl">Operator</span>
            <span class="det-val" id="dmOp"></span>
        </div>
        <div class="det-row" id="dmPkgRow" style="display:none">
            <span class="det-lbl">Package</span>
            <span class="det-val" id="dmPkg"></span>
        </div>
        <div class="det-row">
            <span class="det-lbl">Previous Balance</span>
            <span class="det-val" id="dmBalBefore"></span>
        </div>
        <div class="det-row">
            <span class="det-lbl">New Balance</span>
            <span class="det-val" id="dmBalAfter"></span>
        </div>

        <!-- Admin Note -->
        <div id="dmNoteSection" style="display:none;margin:8px 0">
            <div style="background:#fffbeb;border-radius:10px;border:1px solid #f6e05e;overflow:hidden">
                <div id="dmNoteHeader" style="padding:10px 14px;display:flex;align-items:center;justify-content:space-between;cursor:pointer" onclick="toggleAdminNote()">
                    <div style="display:flex;align-items:center;gap:8px">
                        <span style="font-size:16px">📝</span>
                        <span style="font-size:13px;font-weight:700;color:#b7791f" id="dmNoteTitle">Admin Note</span>
                    </div>
                    <i class="fas fa-chevron-down" id="dmNoteArrow" style="color:#b7791f;font-size:12px;transition:0.2s"></i>
                </div>
                <div id="dmNoteBody" style="display:none;padding:0 14px 12px;font-size:13px;color:#744210;font-weight:600;line-height:1.5;border-top:1px solid #f6e05e" id="dmNote"></div>
            </div>
        </div>

        <!-- Product Details Section -->
        <div id="dmDetSection" style="display:none;margin:8px 0">
            <div style="background:#f0f4ff;border-radius:10px;overflow:hidden;border:1px solid #c3d3f7">
                <div style="background:#1a3c8f;padding:8px 12px;font-size:12px;font-weight:800;color:white" id="dmDetTitle">📋 Product Details</div>
                <div id="dmDetRows" style="padding:8px 12px"></div>
            </div>
        </div>

        <!-- Commission Details Section -->
        <div id="dmCommSection" style="display:none;margin:8px 0">
            <div style="background:#f0fff4;border-radius:10px;overflow:hidden;border:1px solid #9ae6b4">
                <div style="background:#276749;padding:8px 12px;font-size:12px;font-weight:800;color:white">💸 Commission Details</div>
                <div id="dmCommRows" style="padding:8px 12px"></div>
            </div>
        </div>
        <div class="det-row">
            <span class="det-lbl">Date & Time</span>
            <span class="det-val" id="dmDate"></span>
        </div>
        <div class="det-row">
            <span class="det-lbl">Status</span>
            <span class="det-val" id="dmStatus"></span>
        </div>
        <div class="det-copy-row">
            <div>
                <div style="font-size:11px;color:#aaa;font-weight:600;margin-bottom:3px">REFERENCE / TRX ID</div>
                <div style="font-size:14px;font-weight:800;color:#333;font-family:monospace" id="dmRef"></div>
            </div>
            <button class="det-copy-btn" onclick="copyField('dmRef','refBtn')" id="refBtn"><i class="fas fa-copy"></i> Copy</button>
        </div>
    </div>
</div>
</div>
<script>document.addEventListener("DOMContentLoaded",function(){ if(window.pageReady) window.pageReady(); });</script>
</body>
</html>
