<?php
require_once '../config/database.php';
require_once '../includes/functions.php';
$pageTitle = 'My Purchases';
include 'side.php';
$conn = getConnection();

// ── Admin colors already set in side.php — re-use directly ──────────────────
// $adminPrimary / $adminSuccess / $adminWarning / $adminDanger / $pRgb all available

/* ── Currency ── */
$uCountry = $userData['country'] ?? 'Kenya';
$cStmt = $conn->prepare("SELECT currency_symbol,exchange_rate FROM countries WHERE name=? AND status='active'");
$cStmt->bind_param("s",$uCountry); $cStmt->execute();
$cRow    = $cStmt->get_result()->fetch_assoc();
$cSym    = $cRow['currency_symbol'] ?? 'KSh';
$cRate   = floatval($cRow['exchange_rate'] ?? 1);
$usdRate = ($cRate > 0) ? $cRate : 1;

/* ── Flash ── */
$notif = $_SESSION['purchase_notif'] ?? null; unset($_SESSION['purchase_notif']);
if (isset($_GET['done']) && !$notif) {
    $notif = ['type'=>'success','msg'=>'Payment confirmed! Your product is ready below.'];
}
$pending = isset($_GET['pending']) ? 1 : 0;

/* ── My purchases ── */
$pq = $conn->prepare("
    SELECT pp.*, dp.title, dp.category, dp.file_name, dp.cover_image, dp.file_size,
           dp.commission_percent, dp.description, dp.delivery_type, dp.delivery_link
    FROM product_purchases pp
    JOIN digital_products dp ON pp.product_id = dp.id
    WHERE pp.user_id = ?
    ORDER BY pp.purchased_at DESC, pp.id DESC
");
$pq->bind_param("i",$userId); $pq->execute();
$purchases = $pq->get_result()->fetch_all(MYSQLI_ASSOC);

/* ── Stats ── */
$totOwned = 0; $totPending = 0; $totSpent = 0;
foreach ($purchases as $p) {
    if ($p['status'] === 'completed') { $totOwned++; $totSpent += $p['amount_paid']; }
    elseif ($p['status'] === 'pending') $totPending++;
}

/* ── Commissions earned ── */
$comEarned = floatval($conn->query("SELECT COALESCE(SUM(commission_amount),0) as t FROM product_commissions WHERE recipient_id=$userId")->fetch_assoc()['t'] ?? 0);

$catMeta = [
    'ebook'       => ['label'=>'eBook',       'icon'=>'fa-book-open',      'color'=>'var(--P)'],
    'source_code' => ['label'=>'Source Code', 'icon'=>'fa-code',           'color'=>'var(--OK)'],
    'template'    => ['label'=>'Template',    'icon'=>'fa-layer-group',    'color'=>'var(--WN)'],
    'software'    => ['label'=>'Software',    'icon'=>'fa-cube',           'color'=>'#3b82f6'],
    'course'      => ['label'=>'Course',      'icon'=>'fa-graduation-cap', 'color'=>'#ec4899'],
    'other'       => ['label'=>'File',        'icon'=>'fa-box-open',       'color'=>'#06b6d4'],
];

function fmtSize($bytes) {
    if (!$bytes) return '';
    if ($bytes < 1024)    return $bytes.' B';
    if ($bytes < 1048576) return round($bytes/1024,1).' KB';
    return round($bytes/1048576,1).' MB';
}
function detectPlatformName($url) {
    if (!$url) return 'Link';
    if (stripos($url,'whatsapp.com')!==false) return 'WhatsApp Group';
    if (stripos($url,'drive.google')!==false) return 'Google Drive';
    if (stripos($url,'docs.google') !==false) return 'Google Docs';
    if (stripos($url,'t.me')        !==false) return 'Telegram';
    if (stripos($url,'dropbox.com') !==false) return 'Dropbox';
    if (stripos($url,'mega.nz')     !==false) return 'MEGA';
    if (stripos($url,'github.com')  !==false) return 'GitHub';
    if (stripos($url,'youtube.com') !==false) return 'YouTube';
    return 'External Link';
}
function detectPlatformIcon($url) {
    if (!$url) return 'fa-solid fa-link';
    if (stripos($url,'whatsapp.com')!==false) return 'fa-brands fa-whatsapp';
    if (stripos($url,'drive.google')!==false) return 'fa-brands fa-google-drive';
    if (stripos($url,'t.me')        !==false) return 'fa-brands fa-telegram';
    if (stripos($url,'dropbox.com') !==false) return 'fa-brands fa-dropbox';
    if (stripos($url,'github.com')  !==false) return 'fa-brands fa-github';
    if (stripos($url,'youtube.com') !==false) return 'fa-brands fa-youtube';
    return 'fa-solid fa-link';
}
?>
<style>
/* ═══════════════════════════════════════════════════════════════
   EARNOVIX — My Purchases
   Uses CSS vars from side.php — no :root redeclaration
═══════════════════════════════════════════════════════════════ */

*,*::before,*::after { box-sizing:border-box }
.pg { padding:0; overflow-x:hidden; width:100%; max-width:100%; }

/* ── Flash (matches dashboard .notif-bar pattern) ── */
.sfl {
    display:flex; align-items:center; gap:8px;
    padding:9px 13px; border-radius:10px;
    font-size:12px; font-weight:600;
    margin:10px 13px 0; border-left:3px solid;
    animation:fadeUp .3s ease both;
}
.sfl.success { background:var(--OK-bg); border-color:var(--OK); color:var(--OK); }
.sfl.error   { background:var(--DN-bg); border-color:var(--DN); color:var(--DN); }
.sfl.info    { background:var(--P-bg);  border-color:var(--P);  color:var(--P);  }

/* ── Pending banner ── */
.pending-banner {
    display:flex; align-items:center; gap:10px;
    margin:10px 13px 0; padding:11px 14px;
    background:var(--WN-bg); border:1px solid rgba(245,158,11,.3);
    border-left:3px solid var(--WN);
    border-radius:0 10px 10px 0;
    font-size:12px; font-weight:600; color:var(--WN);
    animation:fadeUp .3s ease both;
    transition:background .3s, border-color .3s, color .3s;
}

/* ── HERO (mirrors store.php hero — uses side.php tokens) ── */
.shero {
    position:relative; overflow:hidden;
    padding:22px 16px 26px;
    background:var(--bg2);
    border-bottom:1px solid var(--bdr);
}
[data-theme="dark"] .shero {
    background: linear-gradient(150deg, #07060f 0%, #0e0c1a 45%, #141228 100%);
}
.shero-mesh {
    position:absolute; inset:0; pointer-events:none;
    background:
        radial-gradient(ellipse 55% 55% at 15% 25%, rgba(var(--Pr),.18) 0%, transparent 65%),
        radial-gradient(ellipse 45% 55% at 85% 75%, rgba(var(--Pr),.10) 0%, transparent 65%);
}
[data-theme="light"] .shero-mesh { opacity:.6; }
.shero-glow {
    position:absolute; bottom:0; left:0; right:0; height:1px;
    background:linear-gradient(90deg, transparent, rgba(var(--Pr),.5) 50%, transparent);
}
.shero-inner { position:relative; z-index:2; }
.shero-top {
    display:flex; align-items:flex-start; justify-content:space-between;
    gap:12px; margin-bottom:16px;
}
.shero-eyebrow {
    font-size:9px; font-weight:800; letter-spacing:2px; text-transform:uppercase;
    color:var(--P); opacity:.7; display:flex; align-items:center; gap:5px; margin-bottom:6px;
}
.shero-title {
    font-size:21px; font-weight:900; letter-spacing:-.5px; line-height:1.15;
    color:var(--txt);
}
[data-theme="dark"] .shero-title { color:#fff; }
.shero-sub { font-size:11px; color:var(--txt2); margin-top:5px; line-height:1.55; }
.shero-right {
    display:flex; flex-direction:column; gap:7px; align-items:flex-end; flex-shrink:0;
}
.shero-btn {
    display:inline-flex; align-items:center; gap:6px;
    background:var(--P-bg); border:1px solid rgba(var(--Pr),.25);
    color:var(--P); padding:8px 13px; border-radius:10px;
    font-size:11.5px; font-weight:700; text-decoration:none;
    white-space:nowrap; transition:.18s;
}
.shero-btn:hover { background:rgba(var(--Pr),.18); transform:translateY(-1px); }
[data-theme="dark"] .shero-btn { background:rgba(255,255,255,.07); border-color:rgba(255,255,255,.15); color:#fff; }
[data-theme="dark"] .shero-btn:hover { background:rgba(255,255,255,.14); }

/* Hero stats — matches .nstat / .shs from store/dashboard */
.shero-stats { display:grid; grid-template-columns:repeat(4,1fr); gap:8px; }
.shs {
    background:var(--bg3); border:1px solid var(--bdr);
    border-radius:12px; padding:10px 8px; text-align:center;
    transition:background .2s, border-color .2s;
}
.shs:hover { border-color:rgba(var(--Pr),.25); }
.shs-n { font-size:18px; font-weight:900; color:var(--txt); letter-spacing:-.5px; line-height:1; }
.shs-l { font-size:9px; color:var(--txt2); text-transform:uppercase; letter-spacing:.7px; font-weight:600; margin-top:3px; }

/* Currency toggle — identical to store.php */
.cur-toggle {
    display:flex; align-items:center;
    background:var(--bg3); border:1px solid var(--bdr);
    border-radius:20px; padding:3px; gap:2px;
}
.cur-opt {
    padding:3px 11px; border-radius:16px; font-size:10.5px; font-weight:700;
    cursor:pointer; transition:all .22s; color:var(--txt2);
    border:none; background:none; font-family:inherit;
}
.cur-opt.active { background:var(--P); color:#fff; box-shadow:0 2px 10px rgba(var(--Pr),.4); }
[data-theme="light"] .cur-opt.active { color:#fff; }

/* ── BODY ── */
.mp-body { padding:13px 13px 0; }
@media(max-width:480px) { .mp-body { padding:10px 10px 0; } }

/* Section header — matches dashboard .sec-lbl pattern */
.sec-hdr {
    display:flex; align-items:center; justify-content:space-between; margin-bottom:9px;
}
.sec-hdr-t {
    font-size:9px; font-weight:700; letter-spacing:2px; text-transform:uppercase;
    color:var(--P); opacity:.7; display:flex; align-items:center; gap:8px;
}
.sec-hdr-t::after {
    content:''; width:40px; height:1px;
    background:linear-gradient(90deg, rgba(var(--Pr),.3), transparent);
}
.sec-hdr-r a {
    font-size:11.5px; font-weight:700; color:var(--P);
    text-decoration:none; display:flex; align-items:center; gap:4px; transition:.12s;
    opacity:.8;
}
.sec-hdr-r a:hover { opacity:1; }

/* ── PURCHASE LIST ── */
.plist { display:flex; flex-direction:column; gap:9px; margin-bottom:12px; }

/* Purchase card — matches .wcard / .hstat structure */
.pc {
    background:var(--card); border:1px solid var(--bdr);
    border-radius:14px; overflow:hidden;
    transition:box-shadow .2s, border-color .2s, background .25s;
}
.pc:hover { box-shadow:var(--shadow); border-color:rgba(var(--Pr),.25); }
.pc.owned    { border-color:rgba(34,197,94,.28); }
.pc.owned:hover { box-shadow:0 8px 20px rgba(34,197,94,.10); }
.pc.pc-pending { border-color:rgba(245,158,11,.28); }

/* Top accent bar — matches .wcard::before */
.pc::before {
    content:''; display:block; height:2.5px;
    border-radius:14px 14px 0 0;
}
.pc.owned::before    { background:var(--OK); }
.pc.pc-pending::before { background:var(--WN); }
.pc.failed::before   { background:var(--DN); }

.pc-inner { display:flex; align-items:center; gap:12px; padding:12px 14px; }

/* Thumbnail */
.pct {
    width:52px; height:52px; border-radius:11px; flex-shrink:0;
    display:flex; align-items:center; justify-content:center;
    font-size:20px; color:rgba(255,255,255,.9);
    position:relative; overflow:hidden;
}
.pct img { width:52px; height:52px; object-fit:cover; border-radius:11px; }
.pct-own {
    position:absolute; bottom:-1px; right:-1px;
    width:16px; height:16px; background:var(--OK);
    border-radius:50%; border:2px solid var(--card);
    display:flex; align-items:center; justify-content:center;
}
.pct-own i { font-size:7px; color:#fff; }

/* Body */
.pc-body { flex:1; min-width:0; }
.pc-title {
    font-size:13px; font-weight:700; color:var(--txt);
    margin-bottom:4px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;
}
.pc-meta { display:flex; gap:7px; flex-wrap:wrap; align-items:center; }
.pm { display:flex; align-items:center; gap:3px; font-size:10.5px; color:var(--txt2); }
.pm i { font-size:9px; }
.pm.ok  { color:var(--OK); }
.pm.pri { color:var(--P); }
.pm.wn  { color:var(--WN); }

/* Category pill — matches .pcat-pill from store */
.cat-pill {
    display:inline-flex; align-items:center; gap:3px;
    font-size:9px; font-weight:800; padding:2px 7px;
    border-radius:20px; color:#fff;
}

/* Right side */
.pc-right { display:flex; flex-direction:column; align-items:flex-end; gap:5px; flex-shrink:0; }
.pc-amt { font-size:13px; font-weight:800; color:var(--txt); letter-spacing:-.3px; }

/* Status badges — matches .badge-up / dashboard pattern */
.sbadge {
    display:inline-flex; align-items:center; gap:3px;
    padding:3px 9px; border-radius:20px;
    font-size:9px; font-weight:700; text-transform:uppercase; letter-spacing:.4px;
}
.sbadge.completed { background:var(--OK-bg); color:var(--OK); }
.sbadge.pending   { background:var(--WN-bg); color:var(--WN); }
.sbadge.failed    { background:var(--DN-bg); color:var(--DN); }

/* Action buttons — matches .copy-btn / .pbuy-btn */
.dl-btn {
    display:inline-flex; align-items:center; gap:5px;
    height:32px; padding:0 13px; border-radius:9px;
    font-size:11px; font-weight:700; text-decoration:none;
    transition:.15s; white-space:nowrap; cursor:pointer; border:none;
    font-family:inherit;
}
.dl-btn.file {
    background:var(--OK); color:#fff;
    box-shadow:0 3px 10px rgba(34,197,94,.3);
}
.dl-btn.file:hover { filter:brightness(1.1); transform:translateY(-1px); }
[data-theme="light"] .dl-btn.file { color:#fff; }
.dl-btn.link {
    background:var(--P); color:#fff;
    box-shadow:0 3px 10px rgba(var(--Pr),.3);
}
.dl-btn.link:hover { filter:brightness(1.1); transform:translateY(-1px); }
[data-theme="light"] .dl-btn.link { color:#fff; }
.dl-btn.disabled {
    background:var(--bg3); color:var(--txt3);
    cursor:not-allowed; box-shadow:none;
}
.access-left { font-size:10px; color:var(--txt3); font-weight:600; text-align:right; }

/* ── COMMISSIONS SECTION ── */
.cm-card {
    background:var(--card); border:1px solid var(--bdr);
    border-radius:14px; overflow:hidden; margin-bottom:12px;
    transition:background .25s, border-color .25s;
}
.cm-hdr {
    display:flex; align-items:center; justify-content:space-between;
    padding:11px 14px;
    background:var(--bg3); border-bottom:1px solid var(--bdr);
    transition:background .25s;
}
.cm-hdr-t {
    font-size:13px; font-weight:700; color:var(--txt);
    display:flex; align-items:center; gap:7px;
}
.cm-hdr-t i { color:var(--OK); font-size:12px; }
.cm-hdr-r { font-size:12px; font-weight:800; color:var(--OK); }

.cm-row {
    display:flex; align-items:center; gap:11px;
    padding:10px 14px; border-bottom:1px solid var(--bdr);
    transition:background .1s;
}
.cm-row:last-child { border-bottom:none; }
.cm-row:hover { background:var(--bg3); }

.cm-av {
    width:34px; height:34px; border-radius:9px; flex-shrink:0;
    background:var(--WN-bg); border:1px solid rgba(245,158,11,.2);
    display:flex; align-items:center; justify-content:center;
    color:var(--WN); font-size:12px;
}
.cm-body { flex:1; min-width:0; }
.cm-name {
    font-size:12.5px; font-weight:600; color:var(--txt); margin-bottom:2px;
    white-space:nowrap; overflow:hidden; text-overflow:ellipsis;
}
.cm-meta { font-size:10.5px; color:var(--txt2); }
.cm-amt { font-size:14px; font-weight:800; color:var(--OK); white-space:nowrap; }

/* ── EMPTY STATE ── */
.empty {
    text-align:center; padding:40px 16px;
    background:var(--card); border:1px solid var(--bdr); border-radius:14px;
}
.empty-ico { font-size:38px; color:var(--txt3); margin-bottom:10px; }
.empty-t   { font-size:14px; font-weight:700; color:var(--txt); margin-bottom:4px; }
.empty-s   { font-size:12px; color:var(--txt2); margin-bottom:16px; }
.goto-store {
    display:inline-flex; align-items:center; gap:6px;
    height:40px; padding:0 18px; border-radius:10px;
    background:var(--P); color:#fff;
    font-size:12.5px; font-weight:800; text-decoration:none;
    box-shadow:0 4px 14px rgba(var(--Pr),.3); transition:.15s;
}
.goto-store:hover { filter:brightness(1.1); transform:translateY(-1px); }
[data-theme="light"] .goto-store { color:#fff; }

/* ── Animations (matches dashboard stagger) ── */
@keyframes fadeUp { from{opacity:0;transform:translateY(10px)} to{opacity:1;transform:translateY(0)} }
.shero           { animation:fadeUp .4s ease both .03s; }
.sec-hdr         { animation:fadeUp .4s ease both .08s; }
.pc:nth-child(1) { animation:fadeUp .3s ease .06s both; }
.pc:nth-child(2) { animation:fadeUp .3s ease .10s both; }
.pc:nth-child(3) { animation:fadeUp .3s ease .14s both; }
.pc:nth-child(4) { animation:fadeUp .3s ease .18s both; }
.pc:nth-child(n+5){ animation:fadeUp .3s ease .22s both; }
.cm-card         { animation:fadeUp .4s ease both .25s; }
</style>

<div class="pg">

<?php if ($notif): ?>
<div class="sfl <?= htmlspecialchars($notif['type']) ?>">
    <i class="fa-solid fa-<?= $notif['type']==='success'?'circle-check':'circle-info' ?>"></i>
    <?= htmlspecialchars($notif['msg']) ?>
</div>
<?php endif; ?>

<?php if ($totPending > 0 || $pending): ?>
<div class="pending-banner" id="pendingBanner">
    <i class="fa-solid fa-spinner fa-spin"></i>
    <span>You have <strong><?= $totPending ?> pending payment<?= $totPending!=1?'s':'' ?></strong>. Checking status…</span>
</div>
<?php endif; ?>

<!-- ── HERO ── -->
<div class="shero">
    <div class="shero-mesh"></div>
    <div class="shero-glow"></div>
    <div class="shero-inner">
        <div class="shero-top">
            <div>
                <div class="shero-eyebrow"><i class="fa-solid fa-bag-shopping"></i> My Library</div>
                <div class="shero-title">Your digital<br>collection.</div>
                <div class="shero-sub">All your purchased products in one place. Download, access and share.</div>
            </div>
            <div class="shero-right">
                <div class="cur-toggle">
                    <button class="cur-opt active" id="btnKES" onclick="setCur('kes')"><?= htmlspecialchars($cSym) ?></button>
                    <button class="cur-opt" id="btnUSD" onclick="setCur('usd')">USD $</button>
                </div>
                <a href="store.php" class="shero-btn"><i class="fa-solid fa-store"></i> Browse Store</a>
            </div>
        </div>
        <div class="shero-stats">
            <div class="shs">
                <div class="shs-n"><?= $totOwned ?></div>
                <div class="shs-l">Owned</div>
            </div>
            <div class="shs">
                <div class="shs-n mv" data-kes="<?= round($totSpent) ?>"><?= $cSym.' '.number_format(round($totSpent)) ?></div>
                <div class="shs-l">Spent</div>
            </div>
            <div class="shs">
                <div class="shs-n" style="color:<?= $totPending>0?'var(--WN)':'var(--txt)' ?>"><?= $totPending ?></div>
                <div class="shs-l">Pending</div>
            </div>
            <div class="shs">
                <div class="shs-n mv" style="color:var(--OK)" data-kes="<?= round($comEarned) ?>"><?= $cSym.' '.number_format(round($comEarned)) ?></div>
                <div class="shs-l">Comm.</div>
            </div>
        </div>
    </div>
</div>

<!-- ── BODY ── -->
<div class="mp-body">

<!-- Section header -->
<div class="sec-hdr">
    <div class="sec-hdr-t"><i class="fa-solid fa-box-open"></i> My Products</div>
    <div class="sec-hdr-r"><a href="store.php"><i class="fa-solid fa-plus"></i> Browse More</a></div>
</div>

<?php if (empty($purchases)): ?>
<div class="empty">
    <div class="empty-ico"><i class="fa-solid fa-bag-shopping"></i></div>
    <div class="empty-t">No purchases yet</div>
    <div class="empty-s">Visit the store to find eBooks, source codes, templates and more.</div>
    <a href="store.php" class="goto-store"><i class="fa-solid fa-store"></i> Go to Store</a>
</div>

<?php else: ?>
<div class="plist">
<?php foreach ($purchases as $p):
    $cm       = $catMeta[$p['category']] ?? $catMeta['other'];
    $isLink   = ($p['delivery_type'] ?? 'file') === 'link';
    $dlCount  = intval($p['download_count'] ?? 0);
    $dlMax    = intval($p['max_downloads']  ?? 10);
    $canAct   = $p['status'] === 'completed' && !empty($p['download_token']) && $dlCount < $dlMax;
    $linkUrl      = $p['delivery_link'] ?? '';
    $platformName = detectPlatformName($linkUrl);
    $platformIcon = detectPlatformIcon($linkUrl);
    $hasCov   = !empty($p['cover_image']) && file_exists('../'.$p['cover_image']);
    $statusCls= $p['status'] === 'completed' ? 'owned' : ($p['status'] === 'pending' ? 'pc-pending' : 'failed');
    $accLeft  = $dlMax - $dlCount;
?>
<div class="pc <?= $statusCls ?>">
    <div class="pc-inner">

        <!-- Thumbnail -->
        <div class="pct" style="background:<?= $cm['color'] ?>">
            <?php if ($hasCov): ?>
                <img src="../<?= htmlspecialchars($p['cover_image']) ?>" alt="">
            <?php else: ?>
                <i class="fa-solid <?= $cm['icon'] ?>"></i>
            <?php endif; ?>
            <?php if ($p['status']==='completed'): ?>
                <div class="pct-own"><i class="fa-solid fa-check"></i></div>
            <?php endif; ?>
        </div>

        <!-- Body -->
        <div class="pc-body">
            <div class="pc-title"><?= htmlspecialchars($p['title']) ?></div>
            <div class="pc-meta">
                <span class="cat-pill" style="background:<?= $cm['color'] ?>">
                    <i class="fa-solid <?= $cm['icon'] ?>" style="font-size:7px"></i><?= $cm['label'] ?>
                </span>
                <?php if ($isLink): ?>
                    <span class="pm pri"><i class="<?= $platformIcon ?>"></i><?= $platformName ?></span>
                <?php else: ?>
                    <?php if ($fs = fmtSize($p['file_size'])): ?>
                    <span class="pm"><i class="fa-solid fa-file"></i><?= $fs ?></span>
                    <?php endif; ?>
                <?php endif; ?>
                <span class="pm <?= $p['status']==='completed'?'ok':'' ?>">
                    <i class="fa-solid fa-<?= $isLink?'link':'download' ?>"></i>
                    <?= $dlCount ?>/<?= $dlMax ?> <?= $isLink?'accesses':'downloads' ?>
                </span>
                <span class="pm">
                    <i class="fa-regular fa-calendar"></i>
                    <?= date('M j, Y', strtotime($p['purchased_at'] ?? $p['created_at'] ?? 'now')) ?>
                </span>
            </div>
        </div>

        <!-- Right -->
        <div class="pc-right">
            <div class="pc-amt mv" data-kes="<?= round($p['amount_paid']) ?>">
                <?= $cSym.' '.number_format(round($p['amount_paid'])) ?>
            </div>

            <span class="sbadge <?= $p['status'] ?>">
                <?php if ($p['status']==='completed'): ?>
                    <i class="fa-solid fa-check" style="font-size:7px"></i>
                <?php elseif ($p['status']==='pending'): ?>
                    <i class="fa-solid fa-spinner fa-spin" style="font-size:7px"></i>
                <?php else: ?>
                    <i class="fa-solid fa-xmark" style="font-size:7px"></i>
                <?php endif; ?>
                <?= ucfirst($p['status']) ?>
            </span>

            <?php if ($canAct): ?>
                <?php if ($isLink): ?>
                <a href="download.php?token=<?= urlencode($p['download_token']) ?>"
                   class="dl-btn link" target="_blank" rel="noopener noreferrer">
                    <i class="<?= $platformIcon ?>"></i> Open
                </a>
                <?php else: ?>
                <a href="download.php?token=<?= urlencode($p['download_token']) ?>" class="dl-btn file">
                    <i class="fa-solid fa-download"></i> Download
                </a>
                <?php endif; ?>
                <div class="access-left"><?= $accLeft ?> left</div>

            <?php elseif ($p['status'] === 'pending'): ?>
                <span class="sbadge pending">
                    <i class="fa-solid fa-clock" style="font-size:7px"></i> Waiting
                </span>

            <?php elseif ($p['status'] === 'completed' && $dlCount >= $dlMax): ?>
                <span class="dl-btn disabled">
                    <i class="fa-solid fa-ban" style="font-size:9px"></i>
                    Limit reached
                </span>
            <?php endif; ?>
        </div>

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

<!-- ── COMMISSIONS ── -->
<?php
$cmq = $conn->query("
    SELECT pc.*, dp.title as product_title, u.username as buyer_name, pc.created_at
    FROM product_commissions pc
    JOIN digital_products dp ON pc.product_id = dp.id
    JOIN users u ON pc.buyer_id = u.id
    WHERE pc.recipient_id = $userId
    ORDER BY pc.created_at DESC LIMIT 20
");
$commRows = $cmq ? $cmq->fetch_all(MYSQLI_ASSOC) : [];
if (!empty($commRows)): ?>
<div class="sec-hdr" style="margin-top:4px">
    <div class="sec-hdr-t"><i class="fa-solid fa-coins"></i> Product Commissions</div>
    <div class="sec-hdr-r"><span style="font-size:11.5px;font-weight:800;color:var(--OK)" class="mv" data-kes="<?= round($comEarned) ?>"><?= $cSym.' '.number_format($comEarned,2) ?></span></div>
</div>
<div class="cm-card">
    <?php foreach ($commRows as $cr): ?>
    <div class="cm-row">
        <div class="cm-av"><i class="fa-solid fa-receipt"></i></div>
        <div class="cm-body">
            <div class="cm-name">Sale of "<?= htmlspecialchars($cr['product_title']) ?>"</div>
            <div class="cm-meta">Level <?= $cr['level_number'] ?> &middot; by <?= htmlspecialchars($cr['buyer_name']) ?> &middot; <?= date('M j', strtotime($cr['created_at'])) ?></div>
        </div>
        <div class="cm-amt mv" data-kes="<?= round($cr['commission_amount']) ?>">
            +<?= $cSym.' '.number_format($cr['commission_amount'],2) ?>
        </div>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

</div><!-- /mp-body -->
</div><!-- /pg -->

<!-- ── PENDING POLL (unchanged logic) ── -->
<?php if ($totPending > 0 || $pending): ?>
<script>
var ADMIN_OK = '<?= addslashes($adminSuccess) ?>';
var pollCount = 0, maxPolls = 90;
var pollInt = setInterval(checkStatus, 2000);
checkStatus();

function checkStatus() {
    pollCount++;
    if (pollCount > maxPolls) {
        clearInterval(pollInt);
        var b = document.getElementById('pendingBanner');
        if (b) b.innerHTML = '<i class="fa-solid fa-triangle-exclamation"></i><span>Check timed out. <a href="my_purchases.php" style="color:var(--WN);font-weight:800">Refresh</a> to see updates.</span>';
        return;
    }
    fetch('check_purchase_status.php', {cache:'no-store'})
        .then(function(r){ return r.json(); })
        .then(function(d){
            if (d.completed && d.items && d.items.length > 0) {
                clearInterval(pollInt);
                var b = document.getElementById('pendingBanner');
                if (b) {
                    b.style.background   = 'var(--OK-bg)';
                    b.style.borderColor  = 'rgba(34,197,94,.3)';
                    b.style.color        = ADMIN_OK;
                    b.innerHTML = '<i class="fa-solid fa-circle-check"></i><span><strong>Payment confirmed!</strong> Reloading…</span>';
                }
                setTimeout(function(){ window.location.href = 'my_purchases.php?done=1'; }, 1500);
            } else if (d.pending_count === 0 && pollCount > 3) {
                clearInterval(pollInt);
                window.location.reload();
            }
        })
        .catch(function(){});
}
</script>
<?php endif; ?>

<script>
/* ── Currency (identical to store.php / dashboard) ── */
var CS       = '<?= addslashes($cSym) ?>';
var USD_RATE = <?= (float)$usdRate ?>;
var curMode  = 'kes';

function fmtMoney(local, mode) {
    if (mode === 'usd') {
        var usd = USD_RATE > 0 ? local / USD_RATE : local;
        return '$ ' + usd.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    }
    return CS + ' ' + Math.round(local).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

function refreshAll(mode) {
    document.querySelectorAll('.mv').forEach(function(el) {
        var v = parseFloat(el.getAttribute('data-kes') || 0);
        el.textContent = fmtMoney(v, mode);
    });
}

window.setCur = function(mode) {
    curMode = mode;
    document.getElementById('btnKES').classList.toggle('active', mode === 'kes');
    document.getElementById('btnUSD').classList.toggle('active', mode === 'usd');
    refreshAll(mode);
};
</script>

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