<?php
require_once '../config/database.php';
require_once '../includes/functions.php';
$pageTitle = 'Digital Products';
include 'side.php';
require_once 'admin_protect.php';

$conn = getConnection();

/* ── DELETE ─────────────────────────────────────────────────────────────────── */
if (isset($_GET['del']) && is_numeric($_GET['del'])) {
    $did = intval($_GET['del']);
    $row = $conn->query("SELECT file_path,cover_image FROM digital_products WHERE id=$did")->fetch_assoc();
    if ($row) {
        $base = dirname(dirname(__FILE__)).'/secure_uploads/products/';
        if ($row['file_path'])   @unlink($base.basename($row['file_path']));
        if ($row['cover_image']) @unlink(dirname(dirname(__FILE__)).'/'.$row['cover_image']);
        $conn->query("DELETE FROM digital_products WHERE id=$did");
    }
    header('Location: admin_products.php?msg=deleted'); exit;
}

/* ── TOGGLE STATUS ───────────────────────────────────────────────────────────── */
if (isset($_GET['toggle']) && is_numeric($_GET['toggle'])) {
    $tid = intval($_GET['toggle']);
    $conn->query("UPDATE digital_products SET status=CASE WHEN status='active' THEN 'inactive' ELSE 'active' END WHERE id=$tid");
    header('Location: admin_products.php?'.$_SERVER['QUERY_STRING']); exit;
}

/* ── TOGGLE FEATURED ─────────────────────────────────────────────────────────── */
if (isset($_GET['feat']) && is_numeric($_GET['feat'])) {
    $fid = intval($_GET['feat']);
    $conn->query("UPDATE digital_products SET featured=!featured WHERE id=$fid");
    header('Location: admin_products.php?'.$_SERVER['QUERY_STRING']); exit;
}

/* ── FILTERS ─────────────────────────────────────────────────────────────────── */
$fcat    = sanitize($_GET['cat']      ?? 'all');
$fstatus = sanitize($_GET['status']   ?? 'all');
$fdeliv  = sanitize($_GET['delivery'] ?? 'all');
$fsearch = sanitize($_GET['s']        ?? '');
$page    = max(1, intval($_GET['page'] ?? 1));
$pp = 15; $off = ($page - 1) * $pp;

$where = '1=1';
if ($fcat    !== 'all') $where .= " AND category='".$conn->real_escape_string($fcat)."'";
if ($fstatus !== 'all') $where .= " AND status='".$conn->real_escape_string($fstatus)."'";
if ($fdeliv  !== 'all') $where .= " AND delivery_type='".$conn->real_escape_string($fdeliv)."'";
if ($fsearch)           $where .= " AND title LIKE '%".$conn->real_escape_string($fsearch)."%'";

$products   = $conn->query("SELECT * FROM digital_products WHERE $where ORDER BY created_at DESC LIMIT $off,$pp")->fetch_all(MYSQLI_ASSOC);
$totalCount = intval($conn->query("SELECT COUNT(*) as c FROM digital_products WHERE $where")->fetch_assoc()['c'] ?? 0);
$totalPages = max(1, ceil($totalCount / $pp));

/* ── TOP STATS ───────────────────────────────────────────────────────────────── */
$totAll      = intval($conn->query("SELECT COUNT(*) as c FROM digital_products")->fetch_assoc()['c']);
$totActive   = intval($conn->query("SELECT COUNT(*) as c FROM digital_products WHERE status='active'")->fetch_assoc()['c']);
$totFeatured = intval($conn->query("SELECT COUNT(*) as c FROM digital_products WHERE featured=1")->fetch_assoc()['c']);
$totSales    = intval($conn->query("SELECT COALESCE(SUM(sales_count),0) as c FROM digital_products")->fetch_assoc()['c']);
$totRevenue  = floatval($conn->query("SELECT COALESCE(SUM(amount_paid),0) as c FROM product_purchases WHERE status='completed'")->fetch_assoc()['c']);
$totComm     = floatval($conn->query("SELECT COALESCE(SUM(commission_amount),0) as c FROM product_commissions WHERE status='credited'")->fetch_assoc()['c']);
$totFileProds = intval($conn->query("SELECT COUNT(*) as c FROM digital_products WHERE delivery_type='file' OR delivery_type IS NULL")->fetch_assoc()['c']);
$totLinkProds = intval($conn->query("SELECT COUNT(*) as c FROM digital_products WHERE delivery_type='link'")->fetch_assoc()['c']);

$msg = $_GET['msg'] ?? null;

$flash = null;
if (function_exists('getFlash')) $flash = getFlash();

$catMeta = [
    'ebook'      => ['label'=>'eBook',       'icon'=>'fa-book-open',      'grad'=>'linear-gradient(135deg,#6366f1,#8b5cf6)', 'color'=>'#8b5cf6'],
    'source_code'=> ['label'=>'Source Code',  'icon'=>'fa-code',           'grad'=>'linear-gradient(135deg,#10b981,#059669)', 'color'=>'#10b981'],
    'template'   => ['label'=>'Template',     'icon'=>'fa-layer-group',    'grad'=>'linear-gradient(135deg,#f59e0b,#f97316)', 'color'=>'#f97316'],
    'software'   => ['label'=>'Software',     'icon'=>'fa-cube',           'grad'=>'linear-gradient(135deg,#3b82f6,#6366f1)', 'color'=>'#3b82f6'],
    'course'     => ['label'=>'Course',       'icon'=>'fa-graduation-cap', 'grad'=>'linear-gradient(135deg,#ec4899,#f43f5e)', 'color'=>'#ec4899'],
    'other'      => ['label'=>'Other',        'icon'=>'fa-box-open',       'grad'=>'linear-gradient(135deg,#06b6d4,#3b82f6)', 'color'=>'#06b6d4'],
];

function fmtSz($b) {
    if (!$b) return '—';
    if ($b < 1024)    return $b.'B';
    if ($b < 1048576) return round($b/1024,1).'KB';
    return round($b/1048576,1).'MB';
}

function pgUrl($page, $cat, $status, $search, $delivery = 'all') {
    $q = http_build_query(array_filter([
        'cat'      => $cat !== 'all'      ? $cat      : '',
        'status'   => $status !== 'all'   ? $status   : '',
        'delivery' => $delivery !== 'all' ? $delivery : '',
        's'        => $search,
        'page'     => $page > 1 ? $page : '',
    ]));
    return 'admin_products.php'.($q ? '?'.$q : '');
}
?>
<style>
*,*::before,*::after { box-sizing:border-box }
.pg { padding:16px 18px; overflow-x:hidden; width:100%; max-width:100%; }
@media(max-width:480px) { .pg { padding:10px } }

/* TOAST */
.toast {
    display:flex; align-items:center; gap:10px;
    padding:11px 15px; border-radius:10px; font-size:12.5px; font-weight:600;
    margin-bottom:14px; border-left:3px solid; animation:slideIn .3s ease;
}
.toast.success { background:rgba(16,185,129,.08); border-color:#10b981; color:#059669; }
.toast.error   { background:rgba(239,68,68,.07);  border-color:#ef4444; color:#ef4444; }
.toast.info    { background:rgba(99,102,241,.07);  border-color:#6366f1; color:#6366f1; }
@keyframes slideIn { from { opacity:0; transform:translateY(-6px); } to { opacity:1; transform:none; } }

/* PAGE HEADER */
.phdr { display:flex; align-items:center; justify-content:space-between; margin-bottom:16px; gap:10px; flex-wrap:wrap; }
.phdr-l { display:flex; align-items:center; gap:10px; }
.phdr-ico {
    width:40px; height:40px; border-radius:11px; flex-shrink:0;
    background:linear-gradient(135deg,var(--a),#8b5cf6);
    display:flex; align-items:center; justify-content:center;
}
.phdr-ico i { font-size:17px; color:#fff; }
.phdr-title { font-size:18px; font-weight:900; color:var(--txt); letter-spacing:-.3px; }
.phdr-sub   { font-size:11.5px; color:var(--txt2); margin-top:2px; }
.btn-add {
    display:inline-flex; align-items:center; gap:6px; height:38px; padding:0 18px;
    background:linear-gradient(135deg,var(--a),#8b5cf6); color:#fff;
    border-radius:9px; font-size:12.5px; font-weight:700; text-decoration:none;
    transition:.15s; white-space:nowrap; box-shadow:0 4px 14px rgba(var(--ar),.3);
}
.btn-add:hover { opacity:.88; transform:translateY(-1px); }

/* STAT CARDS */
.scards { display:grid; grid-template-columns:repeat(6,1fr); gap:8px; margin-bottom:14px; }
@media(max-width:900px) { .scards { grid-template-columns:repeat(3,1fr); } }
@media(max-width:500px) { .scards { grid-template-columns:repeat(2,1fr); } }
.sc {
    background:var(--surf); border:1.5px solid var(--bdr);
    border-radius:11px; padding:12px 14px;
    display:flex; flex-direction:column; gap:5px;
    transition:.2s;
}
.sc:hover { border-color:var(--a); transform:translateY(-1px); }
.sc-ico { width:28px; height:28px; border-radius:7px; display:flex; align-items:center; justify-content:center; font-size:12px; margin-bottom:4px; }
.sc-n { font-size:19px; font-weight:900; letter-spacing:-.5px; line-height:1; }
.sc-l { font-size:10px; text-transform:uppercase; letter-spacing:.5px; color:var(--txt2); font-weight:600; }

/* CATEGORY QUICK FILTER PILLS */
.cat-pills { display:flex; gap:6px; flex-wrap:wrap; margin-bottom:8px; }
.cpill {
    display:inline-flex; align-items:center; gap:5px;
    height:30px; padding:0 12px; border-radius:20px;
    border:1.5px solid var(--bdr); background:var(--surf);
    font-size:11.5px; font-weight:600; color:var(--txt2);
    text-decoration:none; transition:.15s; white-space:nowrap;
}
.cpill:hover { border-color:var(--a); color:var(--txt); }
.cpill.on { border-color:var(--a); background:rgba(var(--ar),.1); color:var(--a); }
.cpill .dot { width:7px; height:7px; border-radius:50%; flex-shrink:0; }

/* FILTER ROW */
.frow { display:flex; gap:6px; margin-bottom:12px; flex-wrap:wrap; align-items:center; }
.frow form { display:contents; }
.fsel {
    height:36px; padding:0 10px;
    background:var(--surf); border:1.5px solid var(--bdr); border-radius:8px;
    color:var(--txt); font-size:12px; font-family:'Inter',sans-serif; flex-shrink:0;
}
.finp {
    height:36px; padding:0 12px; flex:1; min-width:150px;
    background:var(--surf); border:1.5px solid var(--bdr); border-radius:8px;
    color:var(--txt); font-size:12px; font-family:'Inter',sans-serif;
}
.fsel:focus,.finp:focus { outline:none; border-color:rgba(var(--ar),.5); }
.fsub {
    height:36px; padding:0 14px; display:inline-flex; align-items:center; gap:6px;
    background:var(--a); color:#fff; border:none; border-radius:8px;
    font-size:12px; font-weight:600; font-family:'Inter',sans-serif; cursor:pointer; white-space:nowrap;
}
.fclear {
    height:36px; padding:0 12px; display:inline-flex; align-items:center; gap:5px;
    background:transparent; color:var(--txt2); border:1.5px solid var(--bdr);
    border-radius:8px; font-size:12px; font-weight:600; font-family:'Inter',sans-serif;
    cursor:pointer; text-decoration:none; white-space:nowrap;
}
.fclear:hover { border-color:var(--txt2); color:var(--txt); }

/* TABLE WRAPPER */
.tbl-wrap {
    background:var(--surf); border:1.5px solid var(--bdr);
    border-radius:13px; overflow:hidden; margin-bottom:12px;
}
.tbl-hdr {
    display:flex; align-items:center; justify-content:space-between;
    padding:12px 16px; background:var(--surf2); border-bottom:1px solid var(--bdr);
    gap:8px; flex-wrap:wrap;
}
.tbl-hdr-t { font-size:13px; font-weight:700; color:var(--txt); display:flex; align-items:center; gap:7px; }
.tbl-hdr-r { display:flex; align-items:center; gap:8px; }
.tbl-count { font-size:11.5px; color:var(--txt2); }

/* PRODUCT ROWS */
.prow {
    display:flex; align-items:center; gap:12px; padding:12px 16px;
    border-bottom:1px solid var(--bdr); transition:background .1s;
}
.prow:last-child { border-bottom:none; }
.prow:hover { background:var(--surf2); }
.pthumb {
    width:46px; height:46px; border-radius:10px; flex-shrink:0;
    display:flex; align-items:center; justify-content:center;
    font-size:19px; color:rgba(255,255,255,.9); position:relative; overflow:hidden;
}
.pthumb img { width:46px; height:46px; border-radius:10px; object-fit:cover; }
.pbody { flex:1; min-width:0; }
.ptitle {
    font-size:13px; font-weight:700; color:var(--txt);
    white-space:nowrap; overflow:hidden; text-overflow:ellipsis; margin-bottom:4px;
}
.pmeta { display:flex; gap:8px; 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.green i, .pm.green { color:#10b981; }
.pm.gold  i, .pm.gold  { color:#f59e0b; }
.pm.blue  i, .pm.blue  { color:#3b82f6; }

/* RIGHT ACTIONS */
.pright { display:flex; align-items:center; gap:5px; flex-shrink:0; flex-wrap:wrap; justify-content:flex-end; }

/* BADGES */
.badge {
    display:inline-flex; align-items:center; gap:3px; padding:3px 8px;
    border-radius:20px; font-size:10px; font-weight:700; text-transform:uppercase;
    transition:.15s; white-space:nowrap;
}
.badge.clk { cursor:pointer; }
.badge.clk:hover { opacity:.75; transform:scale(.97); }
.badge.active   { background:rgba(16,185,129,.1);  color:#059669; }
.badge.inactive { background:rgba(239,68,68,.08);  color:#ef4444; }
.badge.draft    { background:rgba(156,163,175,.1); color:#9ca3af; }
.badge.featured { background:rgba(245,158,11,.12); color:#d97706; }
.badge.bfile    { background:rgba(59,130,246,.1);  color:#3b82f6; }
.badge.blink    { background:rgba(16,185,129,.1);  color:#059669; }
[data-theme=dark] .badge.active   { background:rgba(16,185,129,.18);  color:#34d399; }
[data-theme=dark] .badge.featured { background:rgba(245,158,11,.18);  color:#fbbf24; }
[data-theme=dark] .badge.bfile    { background:rgba(59,130,246,.15);  color:#60a5fa; }
[data-theme=dark] .badge.blink    { background:rgba(16,185,129,.18);  color:#34d399; }

/* ACTION BUTTONS */
.act-btn {
    width:30px; height:30px; border-radius:8px;
    display:flex; align-items:center; justify-content:center;
    font-size:12px; text-decoration:none; transition:.15s; border:none; cursor:pointer;
    position:relative;
}
.act-btn.edit { background:rgba(99,102,241,.1);  color:#6366f1; }
.act-btn.feat { background:rgba(245,158,11,.1);  color:#d97706; }
.act-btn.feat.on { background:rgba(245,158,11,.22); color:#f59e0b; }
.act-btn.del  { background:rgba(239,68,68,.08);  color:#ef4444; }
.act-btn:hover { transform:scale(1.12); }
.act-btn[title]:hover::after {
    content:attr(title); position:absolute; bottom:calc(100% + 5px); left:50%;
    transform:translateX(-50%); background:#111; color:#fff; font-size:10px;
    white-space:nowrap; padding:3px 7px; border-radius:5px; pointer-events:none;
    font-family:'Inter',sans-serif; font-weight:600;
}

/* PAGINATION */
.pag { display:flex; justify-content:center; align-items:center; gap:4px; padding:12px; }
.pbtn {
    min-width:30px; height:30px; padding:0 6px; border-radius:7px;
    display:flex; align-items:center; justify-content:center;
    background:var(--surf); border:1px solid var(--bdr); color:var(--txt2);
    font-size:12px; text-decoration:none; transition:.12s; font-weight:600;
}
.pbtn.on  { background:var(--a); color:#fff; border-color:transparent; }
.pbtn:not(.on):hover { border-color:var(--a); color:var(--a); }
.pag-info { font-size:11.5px; color:var(--txt2); margin:0 8px; }

/* EMPTY STATE */
.empty { text-align:center; padding:40px 16px; }
.empty-ico { font-size:40px; color:var(--txt3); margin-bottom:10px; }
.empty-t { font-size:14px; font-weight:800; color:var(--txt); margin-bottom:5px; }
.empty-s { font-size:12px; color:var(--txt2); margin-bottom:18px; }
.empty-cta {
    display:inline-flex; align-items:center; gap:7px; height:38px; padding:0 20px;
    background:linear-gradient(135deg,var(--a),#8b5cf6); color:#fff;
    border-radius:9px; font-size:12.5px; font-weight:700; text-decoration:none;
}

/* MOBILE */
@media(max-width:600px) {
    .prow { padding:10px 12px; gap:9px; }
    .pthumb { width:38px; height:38px; }
    .pthumb img { width:38px; height:38px; }
    .ptitle { font-size:12.5px; }
    .pmeta .pm:nth-child(n+4) { display:none; }
    .act-btn { width:28px; height:28px; }
}
</style>

<div class="pg">

<?php if ($flash && isset($flash['type'], $flash['msg'])): ?>
<div class="toast <?php echo htmlspecialchars($flash['type']); ?>">
    <i class="fa-solid fa-<?php echo $flash['type']==='success' ? 'circle-check' : 'circle-exclamation'; ?>"></i>
    <?php echo htmlspecialchars($flash['msg']); ?>
</div>
<?php endif; ?>
<?php if ($msg === 'deleted'): ?>
<div class="toast success"><i class="fa-solid fa-trash-can"></i> Product deleted successfully.</div>
<?php elseif ($msg === 'saved'): ?>
<div class="toast success"><i class="fa-solid fa-circle-check"></i> Product saved successfully.</div>
<?php endif; ?>

<!-- PAGE HEADER -->
<div class="phdr">
  <div class="phdr-l">
    <div class="phdr-ico"><i class="fa-solid fa-store"></i></div>
    <div>
      <div class="phdr-title">Digital Products</div>
      <div class="phdr-sub">
        <?php echo number_format($totAll); ?> products &middot;
        <?php echo number_format($totActive); ?> active &middot;
        <?php echo number_format($totFileProds); ?> file &middot;
        <?php echo number_format($totLinkProds); ?> link
      </div>
    </div>
  </div>
  <a href="admin_product_form.php" class="btn-add">
    <i class="fa-solid fa-plus"></i> Add Product
  </a>
</div>

<!-- STAT CARDS -->
<div class="scards">
  <div class="sc">
    <div class="sc-ico" style="background:rgba(var(--ar),.15)"><i class="fa-solid fa-store" style="color:var(--a)"></i></div>
    <div class="sc-n" style="color:var(--a)"><?php echo $totAll; ?></div>
    <div class="sc-l">Total</div>
  </div>
  <div class="sc">
    <div class="sc-ico" style="background:rgba(16,185,129,.12)"><i class="fa-solid fa-circle-check" style="color:#10b981"></i></div>
    <div class="sc-n" style="color:#10b981"><?php echo $totActive; ?></div>
    <div class="sc-l">Active</div>
  </div>
  <div class="sc">
    <div class="sc-ico" style="background:rgba(59,130,246,.12)"><i class="fa-solid fa-file-zipper" style="color:#3b82f6"></i></div>
    <div class="sc-n" style="color:#3b82f6"><?php echo $totFileProds; ?></div>
    <div class="sc-l">File Products</div>
  </div>
  <div class="sc">
    <div class="sc-ico" style="background:rgba(16,185,129,.12)"><i class="fa-solid fa-link" style="color:#10b981"></i></div>
    <div class="sc-n" style="color:#10b981"><?php echo $totLinkProds; ?></div>
    <div class="sc-l">Link Products</div>
  </div>
  <div class="sc">
    <div class="sc-ico" style="background:rgba(16,185,129,.12)"><i class="fa-solid fa-money-bill-wave" style="color:#10b981"></i></div>
    <div class="sc-n" style="color:#10b981;font-size:15px">KSh <?php echo number_format($totRevenue, 0); ?></div>
    <div class="sc-l">Revenue</div>
  </div>
  <div class="sc">
    <div class="sc-ico" style="background:rgba(236,72,153,.12)"><i class="fa-solid fa-hand-holding-dollar" style="color:#ec4899"></i></div>
    <div class="sc-n" style="color:#ec4899;font-size:15px">KSh <?php echo number_format($totComm, 0); ?></div>
    <div class="sc-l">Commissions</div>
  </div>
</div>

<!-- CATEGORY PILLS -->
<div class="cat-pills">
  <a href="admin_products.php<?php echo $fstatus!=='all'||$fsearch||$fdeliv!=='all' ? '?status='.urlencode($fstatus).'&delivery='.urlencode($fdeliv).'&s='.urlencode($fsearch) : ''; ?>"
     class="cpill <?php echo $fcat==='all'?'on':''; ?>">
    <span class="dot" style="background:var(--a)"></span> All
    <strong style="margin-left:2px"><?php echo $totAll; ?></strong>
  </a>
  <?php foreach($catMeta as $ck=>$cv):
    $cnt = intval($conn->query("SELECT COUNT(*) as c FROM digital_products WHERE category='".$conn->real_escape_string($ck)."'")->fetch_assoc()['c']);
    if (!$cnt) continue;
  ?>
  <a href="admin_products.php?cat=<?php echo $ck; ?><?php echo $fstatus!=='all'?'&status='.urlencode($fstatus):''; ?><?php echo $fdeliv!=='all'?'&delivery='.urlencode($fdeliv):''; ?><?php echo $fsearch?'&s='.urlencode($fsearch):''; ?>"
     class="cpill <?php echo $fcat===$ck?'on':''; ?>">
    <span class="dot" style="background:<?php echo $cv['color']; ?>"></span>
    <?php echo $cv['label']; ?> <strong style="margin-left:2px"><?php echo $cnt; ?></strong>
  </a>
  <?php endforeach; ?>
</div>

<!-- FILTERS -->
<div class="frow">
  <form method="GET" id="filterForm">
    <?php if ($fcat !== 'all'): ?>
    <input type="hidden" name="cat" value="<?php echo htmlspecialchars($fcat); ?>">
    <?php endif; ?>
    <select name="status" class="fsel" onchange="this.form.submit()">
      <option value="all"      <?php echo $fstatus==='all'     ?'selected':''; ?>>All Status</option>
      <option value="active"   <?php echo $fstatus==='active'  ?'selected':''; ?>>✅ Active</option>
      <option value="inactive" <?php echo $fstatus==='inactive'?'selected':''; ?>>❌ Inactive</option>
      <option value="draft"    <?php echo $fstatus==='draft'   ?'selected':''; ?>>✏️ Draft</option>
    </select>
    <select name="delivery" class="fsel" onchange="this.form.submit()">
      <option value="all"  <?php echo $fdeliv==='all' ?'selected':''; ?>>All Delivery</option>
      <option value="file" <?php echo $fdeliv==='file'?'selected':''; ?>>📁 File Upload</option>
      <option value="link" <?php echo $fdeliv==='link'?'selected':''; ?>>🔗 External Link</option>
    </select>
    <input type="text" name="s" class="finp" placeholder="🔍 Search products…"
           value="<?php echo htmlspecialchars($fsearch); ?>" id="searchInp">
    <button type="submit" class="fsub"><i class="fa-solid fa-magnifying-glass"></i> Search</button>
    <?php if ($fcat!=='all' || $fstatus!=='all' || $fdeliv!=='all' || $fsearch): ?>
    <a href="admin_products.php" class="fclear"><i class="fa-solid fa-xmark"></i> Clear</a>
    <?php endif; ?>
  </form>
</div>

<!-- PRODUCTS TABLE -->
<div class="tbl-wrap">
  <div class="tbl-hdr">
    <div class="tbl-hdr-t">
      <i class="fa-solid fa-list" style="color:var(--a);font-size:11px"></i>
      <?php
      if ($fcat !== 'all') echo htmlspecialchars($catMeta[$fcat]['label'] ?? $fcat).' Products';
      elseif ($fstatus !== 'all') echo ucfirst($fstatus).' Products';
      elseif ($fdeliv !== 'all') echo ($fdeliv==='link'?'Link-based':'File-based').' Products';
      else echo 'All Products';
      ?>
    </div>
    <div class="tbl-hdr-r">
      <?php if ($totalPages > 1): ?>
      <span style="font-size:10.5px;color:var(--txt3)">Page <?php echo $page; ?> of <?php echo $totalPages; ?></span>
      <?php endif; ?>
      <span class="tbl-count"><?php echo number_format($totalCount); ?> result<?php echo $totalCount!==1?'s':''; ?></span>
    </div>
  </div>

  <?php if (empty($products)): ?>
  <div class="empty">
    <div class="empty-ico"><i class="fa-solid fa-store"></i></div>
    <div class="empty-t">No products found</div>
    <div class="empty-s">
      <?php if ($fsearch || $fcat!=='all' || $fstatus!=='all' || $fdeliv!=='all'): ?>
        Try adjusting your filters or <a href="admin_products.php" style="color:var(--a)">clear all</a>.
      <?php else: ?>
        Add your first digital product to start selling.
      <?php endif; ?>
    </div>
    <?php if (!$fsearch && $fcat==='all' && $fstatus==='all'): ?>
    <a href="admin_product_form.php" class="empty-cta"><i class="fa-solid fa-plus"></i> Add First Product</a>
    <?php endif; ?>
  </div>

  <?php else: foreach ($products as $p):
    $cm  = $catMeta[$p['category']] ?? $catMeta['other'];
    $isFeatured = !empty($p['featured']);
    $isLink = ($p['delivery_type'] ?? 'file') === 'link';
  ?>
  <div class="prow">

    <!-- Thumbnail -->
    <div class="pthumb" style="background:<?php echo $cm['grad']; ?>">
      <?php if (!empty($p['cover_image']) && file_exists('../'.$p['cover_image'])): ?>
        <img src="/<?php echo htmlspecialchars($p['cover_image']); ?>" alt="">
      <?php else: ?>
        <i class="fa-solid <?php echo $cm['icon']; ?>"></i>
      <?php endif; ?>
    </div>

    <!-- Main body -->
    <div class="pbody">
      <div class="ptitle"><?php echo htmlspecialchars($p['title']); ?></div>
      <div class="pmeta">
        <span class="pm">
          <i class="fa-solid fa-tag" style="color:<?php echo $cm['color']; ?>"></i>
          <?php echo $cm['label']; ?>
        </span>
        <span class="pm">
          <i class="fa-solid fa-money-bill"></i>
          KSh <?php echo number_format($p['price'], 0); ?>
          <?php if (!empty($p['original_price']) && $p['original_price'] > $p['price']): ?>
            <span style="text-decoration:line-through;opacity:.55;font-size:10px;margin-left:2px">
              <?php echo number_format($p['original_price'],0); ?>
            </span>
          <?php endif; ?>
        </span>
        <span class="pm green">
          <i class="fa-solid fa-hand-holding-dollar"></i>
          <?php echo $p['commission_percent']; ?>% comm
        </span>
        <!-- Delivery type indicator -->
        <?php if ($isLink): ?>
        <span class="pm blue">
          <i class="fa-solid fa-link"></i> Link delivery
        </span>
        <?php else: ?>
        <span class="pm">
          <i class="fa-solid fa-file-zipper"></i>
          <?php echo fmtSz($p['file_size']); ?>
        </span>
        <?php endif; ?>
        <span class="pm">
          <i class="fa-solid fa-cart-shopping"></i>
          <?php echo number_format($p['sales_count']); ?> sold
        </span>
        <span class="pm" style="color:var(--txt3)">
          <i class="fa-regular fa-clock"></i>
          <?php echo date('d M Y', strtotime($p['created_at'])); ?>
        </span>
      </div>
    </div>

    <!-- Right actions -->
    <div class="pright">

      <!-- Delivery type badge -->
      <?php if ($isLink): ?>
      <span class="badge blink"><i class="fa-solid fa-link" style="font-size:8px"></i> Link</span>
      <?php else: ?>
      <span class="badge bfile"><i class="fa-solid fa-file-zipper" style="font-size:8px"></i> File</span>
      <?php endif; ?>

      <!-- Featured badge -->
      <?php if ($isFeatured): ?>
      <span class="badge featured"><i class="fa-solid fa-fire" style="font-size:8px"></i> Hot</span>
      <?php endif; ?>

      <!-- Status toggle badge -->
      <a href="?toggle=<?php echo $p['id']; ?>&cat=<?php echo urlencode($fcat); ?>&status=<?php echo urlencode($fstatus); ?>&delivery=<?php echo urlencode($fdeliv); ?>&s=<?php echo urlencode($fsearch); ?>&page=<?php echo $page; ?>"
         class="badge clk <?php echo $p['status']; ?>"
         title="Click to toggle status"
         onclick="return confirm('Toggle status for \'<?php echo htmlspecialchars(addslashes($p['title'])); ?>\'?')">
        <?php
          $statusIcons = ['active'=>'●','inactive'=>'○','draft'=>'◌'];
          echo ($statusIcons[$p['status']] ?? '●').' '.ucfirst($p['status']);
        ?>
      </a>

      <!-- Feature toggle -->
      <a href="?feat=<?php echo $p['id']; ?>&cat=<?php echo urlencode($fcat); ?>&status=<?php echo urlencode($fstatus); ?>&delivery=<?php echo urlencode($fdeliv); ?>&s=<?php echo urlencode($fsearch); ?>&page=<?php echo $page; ?>"
         class="act-btn feat <?php echo $isFeatured ? 'on' : ''; ?>"
         title="<?php echo $isFeatured ? 'Unfeature' : 'Feature'; ?>">
        <i class="fa-solid fa-fire"></i>
      </a>

      <!-- Edit -->
      <a href="admin_product_form.php?id=<?php echo $p['id']; ?>"
         class="act-btn edit" title="Edit product">
        <i class="fa-solid fa-pen"></i>
      </a>

      <!-- Delete -->
      <a href="?del=<?php echo $p['id']; ?>"
         class="act-btn del" title="Delete product"
         onclick="return confirm('Permanently delete \'<?php echo htmlspecialchars(addslashes($p['title'])); ?>\'?\n\nThis cannot be undone.')">
        <i class="fa-solid fa-trash"></i>
      </a>

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

  <!-- PAGINATION -->
  <?php if ($totalPages > 1): ?>
  <div class="pag">
    <?php if ($page > 1): ?>
    <a href="<?php echo pgUrl(1, $fcat, $fstatus, $fsearch, $fdeliv); ?>" class="pbtn" title="First">
      <i class="fa-solid fa-angles-left" style="font-size:9px"></i>
    </a>
    <a href="<?php echo pgUrl($page-1, $fcat, $fstatus, $fsearch, $fdeliv); ?>" class="pbtn">
      <i class="fa-solid fa-chevron-left" style="font-size:10px"></i>
    </a>
    <?php endif; ?>
    <?php
    $rangeStart = max(1, $page - 2);
    $rangeEnd   = min($totalPages, $page + 2);
    if ($rangeStart > 1) echo '<span class="pag-info">…</span>';
    for ($i = $rangeStart; $i <= $rangeEnd; $i++):
    ?>
    <a href="<?php echo pgUrl($i, $fcat, $fstatus, $fsearch, $fdeliv); ?>"
       class="pbtn <?php echo $i === $page ? 'on' : ''; ?>">
      <?php echo $i; ?>
    </a>
    <?php endfor;
    if ($rangeEnd < $totalPages) echo '<span class="pag-info">…</span>'; ?>
    <?php if ($page < $totalPages): ?>
    <a href="<?php echo pgUrl($page+1, $fcat, $fstatus, $fsearch, $fdeliv); ?>" class="pbtn">
      <i class="fa-solid fa-chevron-right" style="font-size:10px"></i>
    </a>
    <a href="<?php echo pgUrl($totalPages, $fcat, $fstatus, $fsearch, $fdeliv); ?>" class="pbtn" title="Last">
      <i class="fa-solid fa-angles-right" style="font-size:9px"></i>
    </a>
    <?php endif; ?>
    <span class="pag-info">
      <?php $from = $off+1; $to = min($off+$pp,$totalCount); echo "$from–$to of ".number_format($totalCount); ?>
    </span>
  </div>
  <?php endif; ?>

</div><!-- .tbl-wrap -->
</div><!-- .pg -->

<script>
document.getElementById('searchInp').addEventListener('keydown', function(e) {
    if (e.key === 'Escape') { this.value = ''; this.form.submit(); }
});
document.querySelectorAll('.toast').forEach(function(t) {
    setTimeout(function() {
        t.style.transition = 'opacity .4s, transform .4s';
        t.style.opacity = '0'; t.style.transform = 'translateY(-6px)';
        setTimeout(function() { t.remove(); }, 400);
    }, 4000);
});
</script>

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