<?php
session_start();
include_once "server/conn.php";
require "server/controller.php";
include_once "telegram_log_global.php";
validate::checkSession();

$user_id = $_SESSION["user_id"];
$user = Control::fetchDetail($conn, $user_id);

// Fetch user's JVB transactions
$sql = $conn->prepare("SELECT * FROM jvb_transactions WHERE unique_id = ? ORDER BY created_at DESC");
$sql->bind_param("s", $user_id);
$sql->execute();
$res = $sql->get_result();
$transactions = [];
while ($row = $res->fetch_assoc()) {
    $transactions[] = $row;
}
?>

<?php if ($user["is_restricted"] == "0"): ?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
  <title>JustVerifyBoost Store</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
  <link href="https://api.fontshare.com/v2/css?f[]=clash-display@500,600,700&display=swap" rel="stylesheet">
  <script src="msj.js"></script>
  <style>
    :root{
      --bg:#ffffff;
      --text:#0f172a;
      --muted:#6b7280;
      --border:#eceef2;
      --surface:#ffffff;
      --surface-2:#f5f6f8;
      --primary:#f97316;
      --primary-light:#fff7ed;
      --accent:#3b5bdb;
      --success:#22c55e;
      --danger:#ef4444;
      --warning:#f59e0b;
      --shadow: 0 1px 2px rgba(15,23,42,.04), 0 1px 1px rgba(15,23,42,.03);
      --max-width:480px;
      --safe-bottom: env(safe-area-inset-bottom, 0px);
      --safe-top: env(safe-area-inset-top, 0px);
    }

    @font-face {
      font-family: 'Delight';
      src: url('fonts/delight-bold.otf') format('opentype');
      font-weight: 700;
      font-style: normal;
    }
    @font-face {
      font-family: 'Delight1';
      src: url('fonts/delight-medium.otf') format('opentype');
      font-weight: 700;
      font-style: normal;
    }

    *{box-sizing:border-box;margin:0;padding:0;-webkit-tap-highlight-color:transparent;}
    html,body{height:100%;-webkit-text-size-adjust:100%;}
    body{
      font-family: 'Delight1', sans-serif;
      background:var(--surface-2);
      color:var(--text);
      -webkit-font-smoothing:antialiased;
      font-size:10px;
      line-height:1.45;
    }

    .app{
      max-width:var(--max-width);margin:0 auto;min-height:100vh;
      background:var(--bg);position:relative;
    }

    /* ===== TOPBAR ===== */
    .topbar {
      display:flex;align-items:center;justify-content:space-between;
      padding:calc(6px + var(--safe-top)) 15px 6px 15px;
      position:sticky;top:0;background:var(--bg);z-index:190;
      border-bottom:1px solid transparent;
      font-family: 'Delight', sans-serif !important;
    }
    .btn-icon {
      width:40px;height:40px;display:inline-flex;align-items:center;justify-content:center;
      background:transparent;border:0;border-radius:5px;cursor:pointer;color:var(--text);
      font-size:19px;transition:background .15s;margin-left:-5px;
      text-decoration:none;
    }
    .btn-icon:hover{background:var(--surface-2)}
    .btn-icon:active{background:var(--surface-2);transform:scale(.95)}
    .top-title {
      display: flex;
      flex-direction: column;
      line-height: 1;
      text-align: center;
    }
    .top-title .title {
      font-family: 'Clash Display', sans-serif;
      font-weight: 600;
      font-size: 14px;
      letter-spacing: -.01em;
    }
    .top-title .subtitle { font-size:10px; color:var(--muted); margin-top:2px; }

    /* ===== CONTENT ===== */
    .content {
      padding: 8px 16px calc(80px + var(--safe-bottom));
    }

    .card {
      background:var(--surface); border:1px solid var(--border); border-radius:14px;
      padding:14px; margin-bottom:10px; box-shadow:none;
    }
    .muted { color:var(--muted); font-size:10px; }

    /* ===== SECTION HEADER ===== */
    .section-header {
      font-weight:800; font-size:11px; font-family:'Delight',sans-serif;
      margin-bottom:8px; margin-top:4px;
    }

    /* ===== INFO BOX ===== */
    .info-box {
      background:var(--surface-2); border-radius:10px; padding:10px;
      display:flex; gap:8px; align-items:flex-start; margin-bottom:12px;
    }
    .info-box-text { font-size:10px; color:var(--muted); line-height:1.5; }

    /* ===== CATEGORY TABS ===== */
    .category-tabs {
      display: flex;
      gap: 8px;
      margin-bottom: 12px;
      background: var(--surface-2);
      border-radius: 10px;
      padding: 4px;
      overflow-x: auto;
      scrollbar-width: none;
    }
    .category-tabs::-webkit-scrollbar { display:none; }
    .category-tab {
      flex: 1;
      min-width: 80px;
      padding: 8px 12px;
      border: none;
      border-radius: 8px;
      background: transparent;
      color: var(--muted);
      font-size: 10px;
      font-weight: 600;
      font-family: 'Delight', sans-serif;
      cursor: pointer;
      transition: all 0.2s;
      text-align: center;
      white-space: nowrap;
    }
    .category-tab.active {
      background: #ffffff;
      color: var(--text);
      box-shadow: 0 1px 3px rgba(0,0,0,0.08);
    }
    .category-tab i { font-size: 12px; margin-right: 4px; }

    /* ===== ITEM CARD ===== */
    .item-card {
      border:1px solid var(--border); border-radius:12px; padding:14px;
      margin-bottom:10px; background:var(--surface);
      display:flex; gap:12px; align-items:flex-start;
      transition:all .15s; cursor:pointer;
    }
    .item-card:hover { border-color:#dcdfe5; background:#fcfcfd; }
    .item-card:active { transform:scale(.99); }
    .item-card.hidden { display: none !important; }

    .item-icon {
      width:42px; height:42px; background:var(--surface-2);
      border-radius:10px; display:flex; align-items:center; justify-content:center;
      color:var(--primary); flex-shrink:0; font-size:18px;
    }
    .item-info { flex:1; }
    .item-category { font-size:9px; color:var(--muted); margin-bottom:3px; text-transform:uppercase; letter-spacing:0.5px; }
    .item-title { font-size:13px; font-weight:700; color:var(--text); margin-bottom:3px; }
    .item-desc { font-size:10px; color:var(--muted); line-height:1.4; margin-bottom:6px; }
    .item-price { font-size:14px; font-weight:700; color:var(--primary); }
    .item-price .original { font-size:10px; color:var(--muted); text-decoration:line-through; margin-left:6px; font-weight:500; }

    /* ===== TRANSACTION CARD ===== */
    .tx-card {
      border:1px solid var(--border); border-radius:12px; padding:14px;
      margin-bottom:10px; background:var(--surface);
      display:flex; gap:12px; align-items:flex-start;
      transition:all .15s;
    }
    .tx-card:hover { border-color:#dcdfe5; background:#fcfcfd; }
    .tx-icon {
      width:38px; height:38px; background:var(--surface-2);
      border-radius:50%; display:flex; align-items:center; justify-content:center;
      color:var(--text); flex-shrink:0; font-size:16px;
    }
    .tx-info { flex:1; }
    .tx-category { font-size:9px; color:var(--muted); margin-bottom:2px; text-transform:uppercase; letter-spacing:0.5px; }
    .tx-title { font-size:11px; font-weight:700; color:var(--text); margin-bottom:2px; }
    .tx-ref { font-size:9px; color:var(--muted); font-family:monospace; }
    .tx-status {
      display:inline-block; padding:2px 8px; border-radius:8px; font-size:8px; font-weight:700; margin-top:6px;
    }
    .tx-status.pending { background:#fef3c7; color:#f97316; }
    .tx-status.success { background:#dcfce7; color:#16a34a; }
    .tx-status.failed { background:#fee2e2; color:#dc2626; }
    .tx-status.cancelled { background:#f3f4f6; color:#6b7280; }
    .tx-amount { font-size:12px; font-weight:700; color:var(--text); text-align:right; }
    .tx-date { font-size:9px; color:var(--muted); text-align:right; margin-top:2px; }

    /* ===== ACCESS LINK BUTTON ===== */
    .access-link-btn {
      display:inline-flex; align-items:center; gap:4px;
      padding:6px 12px; border-radius:6px; border:none;
      background:var(--primary); color:#fff; font-size:10px; font-weight:600;
      cursor:pointer; margin-top:8px; text-decoration:none;
      font-family:'Delight1',sans-serif;
    }
    .access-link-btn:active { opacity:.9; }

    /* ===== STATUS TOGGLE ===== */
    .status-toggle {
      display: flex;
      gap: 8px;
      margin-bottom: 12px;
      background: var(--surface-2);
      border-radius: 10px;
      padding: 4px;
    }
    .status-toggle-btn {
      flex: 1;
      padding: 8px 12px;
      border: none;
      border-radius: 8px;
      background: transparent;
      color: var(--muted);
      font-size: 10px;
      font-weight: 600;
      font-family: 'Delight', sans-serif;
      cursor: pointer;
      transition: all 0.2s;
      text-align: center;
    }
    .status-toggle-btn.active {
      background: #ffffff;
      color: var(--text);
      box-shadow: 0 1px 3px rgba(0,0,0,0.08);
    }

    /* ===== EMPTY STATE ===== */
    .empty-state {
      display:flex; flex-direction:column; align-items:center; justify-content:center;
      padding:30px 20px; text-align:center;
    }
    .empty-state svg { margin-bottom:16px; }
    .empty-state .title { font-size:13px; font-weight:700; color:var(--text); margin-bottom:6px; font-family:'Delight',sans-serif; }
    .empty-state .text { font-size:11px; color:var(--muted); line-height:1.5; max-width:220px; margin-bottom:16px; }

    /* ===== LOADING ROW ===== */
    .loading-row {
      display:flex; align-items:center; justify-content:center;
      padding:20px; color:var(--muted); font-size:11px; gap:8px;
    }
    .spinner {
      display:inline-block; animation:spin 1s linear infinite;
    }
    .spinner i { font-size:14px; }
    @keyframes spin { 0%{transform:rotate(0deg);} 100%{transform:rotate(360deg);} }

    /* ===== SPINNER ===== */
    button:disabled { opacity:0.7; cursor:not-allowed; }
    .button-text, .spinner { display:inline-block; }

    /* ===== BUY BUTTON BAR ===== */
    .buy-btn-bar {
      position: fixed;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 100%;
      max-width: var(--max-width);
      background: var(--bg);
      border-top: 1px solid var(--border);
      padding: 8px 16px calc(8px + var(--safe-bottom));
      z-index: 180;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .buy-btn {
      width: 100%;
      padding: 14px;
      background: var(--primary);
      color: #fff;
      border: none;
      border-radius: 6px;
      font-size: 12px;
      font-weight: 600;
      font-family: 'Delight', sans-serif;
      cursor: pointer;
      transition: opacity .15s;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 6px;
    }
    .buy-btn:active { opacity: .9; }
    .buy-btn i { font-size: 14px; }

    body.no-scroll { height:100vh; overflow:hidden; position:fixed; width:100%; }

    :focus, button:focus, a:focus { outline:none !important; box-shadow:none !important; }
    a, button { -webkit-tap-highlight-color: transparent !important; }

    /* ===== BACKDROP & SHEET ===== */
    .backdrop {
      position:fixed; left:0; top:0; right:0; bottom:0;
      background:rgba(15,23,42,0.35); display:none;
      -webkit-backdrop-filter: blur(4px); backdrop-filter: blur(4px);
      z-index:260;
    }
    .backdrop.show { display:block; }

    .sheet {
      position:fixed; left:0; right:0; bottom:0;
      width:100%; max-width:var(--max-width); margin:0 auto;
      max-height:85vh; z-index:270; background:var(--surface);
      border-radius:20px 20px 0 0;
      padding:0 16px calc(16px + var(--safe-bottom)) 16px;
      box-shadow:none;
      display:none; overflow-y:auto; overflow-x:hidden;
      border:1px solid var(--border); border-bottom:0;
      transform: translateY(100%);
      transition: transform 0.35s cubic-bezier(0.32, 0.72, 0, 1);
      box-sizing:border-box;
    }
    .sheet.show { display:block; transform: translateY(0); }
    .sheet.closing { transform: translateY(100%); }
    .sheet::-webkit-scrollbar { display:none; }
    .sheet { scrollbar-width: none; }
    .sheet-handle { display:flex; justify-content:center; padding:10px 0 6px 0; position:sticky; top:0; background:var(--surface); z-index:2; }
    .sheet-handle-bar { width:40px; height:5px; background:var(--border); border-radius:5px; }

    .close-sheet { position:absolute; right:14px; top:12px; background:transparent; border:none; font-size:16px; color:var(--muted); cursor:pointer; width:28px; height:28px; display:flex; align-items:center; justify-content:center; border-radius:8px; }
    .close-sheet:hover { background:var(--surface-2); }
    .close-sheet:active { transform:scale(.95); }

    .sheet-title {
      font-weight:800; font-size:14px; font-family:'Delight',sans-serif;
      margin-bottom:2px; text-align:center;
    }
    .sheet-subtitle {
      font-size:10px; color:var(--muted); text-align:center; margin-bottom:14px;
    }

    /* ===== SELECT OPTION IN SHEET ===== */
    .select-option {
      display:flex; align-items:center; padding:10px 12px;
      border:1px solid var(--border); border-radius:10px;
      margin-bottom:8px; font-size:11px; cursor:pointer;
      transition:all .15s; background:var(--surface);
    }
    .select-option:hover { border-color:#dcdfe5; background:var(--surface-2); }
    .select-option.selected {
      border:1.5px solid #fdba74; background:#fff7ed;
    }
    .select-icon {
      width:32px; height:32px; border-radius:50%; background:var(--surface-2);
      display:flex; align-items:center; justify-content:center;
      margin-right:10px; overflow:hidden; flex-shrink:0;
      font-size:14px; color:var(--muted);
    }
    .select-name { flex:1; font-size:11px; color:var(--text); font-weight:600; }
    .select-desc { font-size:9px; color:var(--muted); display:block; margin-top:1px; }
    .select-radio {
      width:16px; height:16px; border:2px solid var(--border);
      border-radius:50%; margin-left:10px; display:flex;
      align-items:center; justify-content:center; background:#fff;
      transition:border .2s; flex-shrink:0;
    }
    .select-option.selected .select-radio { border:1.5px solid #fdba74; }
    .select-radio::after {
      content:''; display:block; width:7px; height:7px;
      border-radius:50%; background:#fdba74; opacity:0; transition:opacity .2s;
    }
    .select-option.selected .select-radio::after { opacity:1; }

    .gen-error { color:#ef4444; font-size:10px; margin-top:6px; text-align:center; }

    /* ===== PRICE TAG ===== */
    .price-tag {
      display:inline-block; padding:2px 8px; border-radius:8px; font-size:9px;
      font-weight:700; background:#fef3c7; color:#f97316; margin-left:auto;
    }

    /* ===== SEARCH INPUT ===== */
    .search-input {
      width:100%; padding:10px 12px; border:1px solid var(--border); border-radius:10px;
      font-size:11px; font-family:'Delight1',sans-serif; background:var(--surface);
      margin-bottom:10px; color:var(--text);
    }
    .search-input:focus { border-color:#fdba74; }

    /* ===== STICKY SEARCH + SCROLLABLE LIST ===== */
    .step-content {
      display: flex;
      flex-direction: column;
      height: calc(85vh - 180px);
      overflow: hidden;
    }
    .step-search {
      flex-shrink: 0;
      position: sticky;
      top: 0;
      background: var(--surface);
      z-index: 5;
      padding-bottom: 4px;
    }
    .step-list {
      flex: 1;
      overflow-y: auto;
      overflow-x: hidden;
      -webkit-overflow-scrolling: touch;
    }
    .step-list::-webkit-scrollbar { display:none; }
    .step-list { scrollbar-width: none; }

    /* ===== STEPS INDICATOR ===== */
    .steps { display:flex; align-items:center; gap:6px; margin-bottom:14px; }
    .step { flex:1; height:3px; background:var(--border); border-radius:3px; transition:background .3s; }
    .step.active { background:var(--primary); }

    /* ===== CONFIRM CARD ===== */
    .confirm-card {
      background:var(--surface-2); border-radius:10px; padding:12px;
      margin-bottom:12px;
    }
    .confirm-row {
      display:flex; justify-content:space-between; align-items:center;
      padding:6px 0; border-bottom:1px solid var(--border);
    }
    .confirm-row:last-child { border-bottom:none; }
    .confirm-label { font-size:10px; color:var(--muted); }
    .confirm-value { font-size:11px; font-weight:700; color:var(--text); }
    .confirm-value.price { color:var(--primary); font-size:14px; }

    /* ===== GENERATE BUTTON ===== */
    .generate-btn {
      width:100%; padding:14px; background:#f97316; color:#fff; border:none;
      border-radius:6px; font-size:12px; font-weight:600; cursor:pointer;
      margin-top:10px; font-family:'Delight',sans-serif;
      transition:opacity .15s;
    }
    .generate-btn:active { opacity:.9; }

    /* ===== ITEM IMAGE ===== */
    .item-image {
      width:100%; height:160px; object-fit:cover; border-radius:10px; margin-bottom:10px;
    }

    /* ===== QUANTITY SELECTOR ===== */
    .qty-selector {
      display:flex; align-items:center; gap:8px; margin-top:8px;
    }
    .qty-btn {
      width:32px; height:32px; border:1px solid var(--border); border-radius:8px;
      background:var(--surface); color:var(--text); font-size:14px; font-weight:700;
      cursor:pointer; display:flex; align-items:center; justify-content:center;
    }
    .qty-btn:active { background:var(--surface-2); }
    .qty-value {
      min-width:40px; text-align:center; font-size:14px; font-weight:700;
      font-family:'Delight',sans-serif;
    }

    /* ===== ACCESS LINK MODAL ===== */
    .access-modal-content {
      text-align:center; padding:20px 10px;
    }
    .access-modal-content i {
      font-size:48px; color:var(--success); margin-bottom:12px;
    }
    .access-modal-content .title {
      font-family:'Delight',sans-serif; font-size:16px; font-weight:700;
      margin-bottom:8px;
    }
    .access-modal-content .text {
      font-size:11px; color:var(--muted); line-height:1.5; margin-bottom:16px;
    }
    .access-link-box {
      background:var(--surface-2); border:1px solid var(--border); border-radius:10px;
      padding:12px; margin-bottom:16px; word-break:break-all; font-size:11px;
      font-family:monospace; color:var(--primary);
    }


    .tx-section-header {
      font-family: 'Delight', sans-serif;
      font-size: 11px;
      font-weight: 700;
      color: var(--text);
      padding: 8px 4px 4px 4px;
      margin-top: 4px;
      border-bottom: 1px solid var(--border);
      text-transform: uppercase;
      letter-spacing: 0.5px;
    }
    /* ===== TRANSACTION OVERLAY ===== */
    .tx-overlay {
      position: fixed;
      top: 0; left: 0; right: 0; bottom: 0;
      width: 100%; max-width: var(--max-width); margin: 0 auto;
      background: var(--bg);
      z-index: 300;
      display: none;
      flex-direction: column;
      overflow: hidden;
    }
    .tx-overlay.show { display: flex; }
    .tx-overlay-header {
      display: flex; align-items: center; justify-content: space-between;
      padding: calc(6px + var(--safe-top)) 15px 6px 15px;
      position: sticky; top: 0; background: var(--bg); z-index: 190;
      border-bottom: 1px solid var(--border);
      font-family: 'Delight', sans-serif !important;
    }
    .tx-overlay-content {
      flex: 1;
      overflow-y: auto;
      overflow-x: hidden;
      padding: 8px 16px calc(16px + var(--safe-bottom));
    }
    .tx-overlay-content::-webkit-scrollbar { display: none; }
    .tx-overlay-content { scrollbar-width: none; }


    /* ===== TX DETAIL MODAL ===== */
    .tx-detail-backdrop {
      z-index: 310 !important;
    }
    .tx-detail-sheet {
      z-index: 320 !important;
    }
    .tx-detail-sheet .confirm-card {
      margin-bottom: 8px;
    }
    .tx-detail-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 0;
      border-bottom: 1px solid var(--border);
    }
    .tx-detail-row:last-child {
      border-bottom: none;
    }
    .tx-detail-label {
      font-size: 10px;
      color: var(--muted);
    }
    .tx-detail-value {
      font-size: 11px;
      font-weight: 700;
      color: var(--text);
      text-align: right;
      max-width: 60%;
      word-break: break-word;
    }
    .tx-detail-value.link {
      color: var(--primary);
      text-decoration: none;
    }
    .tx-detail-value.link:hover {
      text-decoration: underline;
    }
    .tx-detail-value.mono {
      font-family: monospace;
      font-size: 10px;
    }
    .tx-detail-badge {
      display: inline-block;
      padding: 3px 10px;
      border-radius: 8px;
      font-size: 9px;
      font-weight: 700;
    }
    .tx-detail-badge.pending { background: #fef3c7; color: #f97316; }
    .tx-detail-badge.success { background: #dcfce7; color: #16a34a; }
    .tx-detail-badge.failed { background: #fee2e2; color: #dc2626; }
    .tx-detail-badge.cancelled { background: #f3f4f6; color: #6b7280; }
    .tx-detail-icon {
      width: 48px;
      height: 48px;
      border-radius: 50%;
      background: var(--surface-2);
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 0 auto 12px;
      font-size: 22px;
      color: var(--primary);
    }
    .tx-detail-title {
      font-family: 'Delight', sans-serif;
      font-size: 14px;
      font-weight: 700;
      text-align: center;
      margin-bottom: 2px;
    }
    .tx-detail-subtitle {
      font-size: 10px;
      color: var(--muted);
      text-align: center;
      margin-bottom: 16px;
    }
    .tx-detail-access-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 6px;
      width: 100%;
      padding: 12px;
      background: var(--primary);
      color: #fff;
      border: none;
      border-radius: 6px;
      font-size: 12px;
      font-weight: 600;
      font-family: 'Delight', sans-serif;
      cursor: pointer;
      text-decoration: none;
      margin-top: 8px;
    }
    .tx-detail-access-btn:active { opacity: .9; }
    .tx-detail-access-btn.disabled {
      background: var(--border);
      color: var(--muted);
      cursor: not-allowed;
    }
    .tx-detail-note {
      background: var(--surface-2);
      border-radius: 8px;
      padding: 10px;
      font-size: 10px;
      color: var(--muted);
      line-height: 1.5;
      margin-top: 8px;
    }
    .tx-detail-note-label {
      font-weight: 700;
      color: var(--text);
      margin-bottom: 4px;
      font-size: 10px;
    }

  </style>
</head>
<body>
  <div class="app">

    <!-- Top Bar -->
    <header class="topbar">
      <a href="javascript:history.back()" class="btn-icon" aria-label="Back">
        <i class="bi bi-chevron-left"></i>
      </a>
      <div class="top-title">
        <div class="title">Tools Store</div>
        <div class="subtitle">Working Pics, Tools & Accounts</div>
      </div>
      <button type="button" class="btn-icon" onclick="openTxOverlay()" aria-label="Transactions">
        <i class="bi bi-receipt"></i>
      </button>
    </header>

    <main class="content">

      <!-- Info Card -->
      <div style="border:1.5px dashed #fdba74; border-radius:12px; padding:12px 14px; margin-bottom:12px; background:#fff7ed;">
        <div style="display:flex; align-items:flex-start; gap:8px;">
          <i class="bi bi-info-circle" style="color:#f97316; font-size:12px; flex-shrink:0; margin-top:1px;"></i>
          <div>
            <div style="font-weight:700; font-size:10px; color:#c2410c; margin-bottom:3px; font-family:'Delight',sans-serif;">How it works</div>
            <div style="font-size:9px; color:#92400e; line-height:1.5;">
              Browse working pictures, tools & updates, and verified accounts. Purchase with your balance and get instant access to private links. All purchases are secured with PIN verification.
            </div>
          </div>
        </div>
      </div>

      <!-- Category Tabs -->
      <div class="category-tabs" id="categoryTabs">
        <button type="button" class="category-tab active" data-category="all" onclick="switchCategory('all')">
          <i class="bi bi-grid"></i> All
        </button>
        <button type="button" class="category-tab" data-category="working_pictures" onclick="switchCategory('working_pictures')">
          <i class="bi bi-image"></i> Pics
        </button>
        <button type="button" class="category-tab" data-category="tools_updates" onclick="switchCategory('tools_updates')">
          <i class="bi bi-tools"></i> Tools
        </button>
        <button type="button" class="category-tab" data-category="accounts" onclick="switchCategory('accounts')">
          <i class="bi bi-person-badge"></i> Accounts
        </button>
      </div>

      <!-- Items Section -->
      <div class="section-header">Available Items</div>
      <div id="itemsList" class="loading-row">
        <span class="spinner"><i class="bi bi-arrow-clockwise"></i></span> Loading items...
      </div>



    </main>

  <!-- Transaction Overlay -->
  <div id="txOverlay" class="tx-overlay">
    <div class="tx-overlay-header">
      <button type="button" class="btn-icon" onclick="closeTxOverlay()" aria-label="Back">
        <i class="bi bi-chevron-left"></i>
      </button>
      <div class="top-title">
        <div class="title">My Purchases</div>
        <div class="subtitle">Transaction History</div>
      </div>
      <div style="width:40px;"></div>
    </div>
    <div class="tx-overlay-content">
      <div class="status-toggle" id="statusToggle">
        <button type="button" class="status-toggle-btn active" data-filter="all" onclick="filterTransactions('all')">All</button>
        <button type="button" class="status-toggle-btn" data-filter="pending" onclick="filterTransactions('pending')">Pending</button>
        <button type="button" class="status-toggle-btn" data-filter="success" onclick="filterTransactions('success')">Success</button>
        <button type="button" class="status-toggle-btn" data-filter="failed" onclick="filterTransactions('failed')">Failed</button>
      </div>
      <!-- Status Count Summary -->
      <div style="display:flex; gap:10px; margin-bottom:12px; flex-wrap:wrap;" id="statusSummary">
        <div style="flex:1; min-width:70px; background:var(--surface); border:1px solid var(--border); border-radius:10px; padding:10px; text-align:center;">
          <div style="font-family:Delight,sans-serif; font-size:16px; font-weight:700; color:var(--text);" id="count-all"><?php echo count($transactions); ?></div>
          <div style="font-size:9px; color:var(--muted); margin-top:2px;">All</div>
        </div>
        <div style="flex:1; min-width:70px; background:var(--surface); border:1px solid var(--border); border-radius:10px; padding:10px; text-align:center;">
          <div style="font-family:Delight,sans-serif; font-size:16px; font-weight:700; color:var(--primary);" id="count-pending">0</div>
          <div style="font-size:9px; color:var(--muted); margin-top:2px;">Pending</div>
        </div>
        <div style="flex:1; min-width:70px; background:var(--surface); border:1px solid var(--border); border-radius:10px; padding:10px; text-align:center;">
          <div style="font-family:Delight,sans-serif; font-size:16px; font-weight:700; color:var(--success);" id="count-success">0</div>
          <div style="font-size:9px; color:var(--muted); margin-top:2px;">Success</div>
        </div>
        <div style="flex:1; min-width:70px; background:var(--surface); border:1px solid var(--border); border-radius:10px; padding:10px; text-align:center;">
          <div style="font-family:Delight,sans-serif; font-size:16px; font-weight:700; color:var(--danger);" id="count-failed">0</div>
          <div style="font-size:9px; color:var(--muted); margin-top:2px;">Failed</div>
        </div>
      </div>
      <div id="transactionList">
        <?php if (count($transactions) > 0): ?>
          <?php foreach ($transactions as $tx): ?>
            <?php
              $status_class = 'pending';
              if (strtoupper($tx['status']) === 'SUCCESS') $status_class = 'success';
              elseif (strtoupper($tx['status']) === 'FAILED') $status_class = 'failed';
              elseif (strtoupper($tx['status']) === 'CANCELLED') $status_class = 'cancelled';

              $cat_icon = 'bi-bag';
              $cat_label = 'Purchase';
              if ($tx['category'] === 'working_pictures') { $cat_icon = 'bi-image'; $cat_label = 'Picture'; }
              elseif ($tx['category'] === 'tools_updates') { $cat_icon = 'bi-tools'; $cat_label = 'Tools'; }
              elseif ($tx['category'] === 'accounts') { $cat_icon = 'bi-person-badge'; $cat_label = 'Account'; }
            ?>
            <div class="tx-card" data-ref="<?php echo htmlspecialchars($tx['reference']); ?>" data-status="<?php echo strtolower($status_class); ?>" data-item="<?php echo htmlspecialchars($tx['item_name'] ?? 'Unknown'); ?>" data-category="<?php echo $cat_label; ?>" data-amount="<?php echo number_format($tx['amount'], 2); ?>" data-qty="<?php echo $tx['quantity']; ?>" data-oldbal="<?php echo number_format($tx['old_bal'], 2); ?>" data-newbal="<?php echo number_format($tx['new_bal'], 2); ?>" data-desc="<?php echo htmlspecialchars($tx['description'] ?? ''); ?>" data-note="<?php echo htmlspecialchars($tx['note'] ?? ''); ?>" data-link="<?php echo htmlspecialchars($tx['accessible_link'] ?? ''); ?>" data-date="<?php echo date('M d, Y 	 H:i', strtotime($tx['created_at'])); ?>" data-providerref="<?php echo htmlspecialchars($tx['provider_ref'] ?? ''); ?>" onclick="openTxDetailSheet(this)">
              <div class="tx-icon">
                <i class="bi <?php echo $cat_icon; ?>"></i>
              </div>
              <div class="tx-info">
                <div class="tx-category"><?php echo $cat_label; ?></div>
                <div class="tx-title"><?php echo htmlspecialchars($tx['item_name'] ?? 'Unknown'); ?></div>
                <div class="tx-ref"><?php echo htmlspecialchars(substr($tx['reference'], 0, 20)); ?>...</div>
                <span class="tx-status <?php echo $status_class; ?>"><?php echo htmlspecialchars($tx['status']); ?></span>
                <?php if (!empty($tx['accessible_link']) && strtoupper($tx['status']) === 'SUCCESS'): ?>
                  <a href="<?php echo htmlspecialchars($tx['accessible_link']); ?>" class="access-link-btn" target="_blank">
                    <i class="bi bi-box-arrow-up-right"></i> Access Content
                  </a>
                <?php endif; ?>
              </div>
              <div style="text-align:right;">
                <div class="tx-amount">₦<?php echo number_format($tx['amount'], 2); ?></div>
                <div class="tx-date"><?php echo date('M d, H:i', strtotime($tx['created_at'])); ?></div>
                <?php if ($tx['quantity'] > 1): ?>
                  <div style="font-size:9px; color:var(--muted); margin-top:2px;">x<?php echo $tx['quantity']; ?></div>
                <?php endif; ?>
              </div>
            </div>
          <?php endforeach; ?>
        <?php else: ?>
          <div class="card">
            <div class="empty-state">
              <svg width="80" height="80" viewBox="0 0 80 80" fill="none">
                <circle cx="40" cy="40" r="36" stroke="var(--border)" stroke-width="2" fill="var(--surface-2)"/>
                <rect x="26" y="30" width="28" height="20" rx="4" stroke="var(--muted)" stroke-width="2" fill="none"/>
                <path d="M30 38h20M30 42h14" stroke="var(--border)" stroke-width="2" stroke-linecap="round"/>
                <circle cx="55" cy="24" r="6" fill="var(--surface-2)" stroke="var(--border)" stroke-width="2"/>
                <path d="M53 24h4M55 22v4" stroke="var(--muted)" stroke-width="2" stroke-linecap="round"/>
              </svg>
              <div class="title">No Purchases Yet</div>
              <div class="text">Browse the store and make your first purchase. All items come with instant access.</div>
            </div>
          </div>
        <?php endif; ?>
      </div>
    </div>
  </div>

  </div>

  <!-- Purchase Bottom Sheet -->
  <div id="purchaseBackdrop" class="backdrop" onclick="closePurchaseSheet()"></div>
  <div id="purchaseSheet" class="sheet">
    <div class="sheet-handle"><div class="sheet-handle-bar"></div></div>
    <div style="position:relative;padding:0 16px 10px;text-align:center;">
      <button type="button" id="sheet-back-btn" onclick="goBackStep()" style="background:transparent;border:none;color:var(--text);font-size:18px;cursor:pointer;padding:4px;width:32px;height:32px;display:flex;align-items:center;justify-content:center;border-radius:6px;opacity:0;visibility:hidden;transition:opacity .2s;position:absolute;left:16px;top:0;">
        <i class="bi bi-chevron-left"></i>
      </button>
      <div class="sheet-title">Purchase Item</div>
      <div class="sheet-subtitle" id="sheet-step-subtitle">Select an item to purchase</div>
      <button type="button" class="close-sheet" onclick="closePurchaseSheet()" aria-label="Close" style="position:absolute;right:0;top:0;"><i class="bi bi-x-lg"></i></button>
    </div>

    <div id="buySteps" class="steps">
      <div class="step active" id="step1-bar"></div>
      <div class="step" id="step2-bar"></div>
      <div class="step" id="step3-bar"></div>
    </div>

    <!-- Step 1: Select Item -->
    <div id="step1">
      <div class="step-content">
        <div class="step-search">
          <div class="section-header">Select Item</div>
          <input type="text" class="search-input" id="itemSearch" placeholder="Search items..." oninput="filterItems(this.value)">
        </div>
        <div id="itemList" class="step-list loading-row">
          <span class="spinner"><i class="bi bi-arrow-clockwise"></i></span> Loading items...
        </div>
      </div>
    </div>

    <!-- Step 2: Confirm Details -->
    <div id="step2" style="display:none;">
      <div class="section-header">Confirm Details</div>
      <div id="itemPreview"></div>
      <div class="confirm-card">
        <div class="confirm-row">
          <span class="confirm-label">Item</span>
          <span class="confirm-value" id="confirmItemName">-</span>
        </div>
        <div class="confirm-row">
          <span class="confirm-label">Category</span>
          <span class="confirm-value" id="confirmCategory">-</span>
        </div>
        <div class="confirm-row">
          <span class="confirm-label">Quantity</span>
          <div class="qty-selector" style="margin:0;">
            <button type="button" class="qty-btn" onclick="changeQty(-1)"><i class="bi bi-dash"></i></button>
            <span class="qty-value" id="qtyValue">1</span>
            <button type="button" class="qty-btn" onclick="changeQty(1)"><i class="bi bi-plus"></i></button>
          </div>
        </div>
        <div class="confirm-row">
          <span class="confirm-label">Unit Price</span>
          <span class="confirm-value" id="confirmUnitPrice">-</span>
        </div>
        <div class="confirm-row">
          <span class="confirm-label">Total</span>
          <span class="confirm-value price" id="confirmTotal">-</span>
        </div>
      </div>
      <button class="generate-btn" onclick="showStep(3)">
        <span class="button-text"><b>Continue to PIN</b></span>
      </button>
    </div>

    <!-- Step 3: PIN & Pay -->
    <div id="step3" style="display:none;">
      <div class="section-header">Enter PIN</div>
      <div style="font-size:10px; color:var(--muted); margin-bottom:6px;">Enter your transaction PIN to complete purchase</div>
      <input type="password" class="search-input" id="txPin" placeholder="****" maxlength="4" inputmode="numeric" pattern="[0-9]*" style="text-align:center; letter-spacing:8px; font-size:16px; margin-bottom:12px;">
      <div id="buyError" class="gen-error"></div>
      <div class="confirm-card" style="margin-top:8px;">
        <div class="confirm-row">
          <span class="confirm-label">Item</span>
          <span class="confirm-value" id="pinItemName">-</span>
        </div>
        <div class="confirm-row">
          <span class="confirm-label">Total</span>
          <span class="confirm-value price" id="pinTotal">-</span>
        </div>
      </div>
      <button id="confirmBuyBtn" class="generate-btn" style="margin-top:10px;" onclick="confirmPurchase()">
        <span class="button-text"><b>Confirm & Pay</b></span>
        <span class="spinner" style="display:none;"><i class="bi bi-arrow-clockwise"></i></span>
      </button>
    </div>
  </div>

  <!-- Success Modal (inline sheet) -->
  <div id="successBackdrop" class="backdrop" onclick="closeSuccessSheet()"></div>
  <div id="successSheet" class="sheet">
    <div class="sheet-handle"><div class="sheet-handle-bar"></div></div>
    <div class="access-modal-content">
      <i class="bi bi-check-circle-fill"></i>
      <div class="title">Purchase Successful!</div>
      <div class="text">Your purchase has been completed successfully. You can now access your content.</div>
      <div id="successAccessLink"></div>
      <button class="generate-btn" onclick="closeSuccessSheet()" style="margin-top:8px;">
        <b>Done</b>
      </button>
    </div>
  </div>

  <script>
    // ===== STATE =====
    let currentCategory = 'all';
    let currentStep = 1;
    let selectedItem = null;
    let itemsData = [];
    let purchaseQty = 1;

    // ===== CATEGORY SWITCH =====
    function switchCategory(cat) {
      currentCategory = cat;
      document.querySelectorAll('.category-tab').forEach(el => {
        el.classList.toggle('active', el.dataset.category === cat);
      });
      loadItems(cat);
    }

    // ===== LOAD ITEMS =====
    function loadItems(category) {
      const container = document.getElementById('itemsList');
      container.innerHTML = '<div class="loading-row"><span class="spinner"><i class="bi bi-arrow-clockwise"></i></span> Loading items...</div>';

      let endpoints = [];
      if (category === 'all' || category === 'working_pictures') {
        endpoints.push({ url: 'server/jvb_single.php?action=get-working-pictures', type: 'working_pictures', key: 'workingPictures' });
      }
      if (category === 'all' || category === 'tools_updates') {
        endpoints.push({ url: 'server/jvb_single.php?action=get-tools-updates', type: 'tools_updates', key: 'celebUpdates' });
      }
      if (category === 'all' || category === 'accounts') {
        endpoints.push({ url: 'server/jvb_single.php?action=get-accounts', type: 'accounts', key: 'accounts' });
      }

      itemsData = [];
      let completed = 0;

      endpoints.forEach(ep => {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', ep.url, true);
        xhr.setRequestHeader('Accept', 'application/json');
        xhr.timeout = 15000;

        xhr.onload = function() {
          completed++;
          if (xhr.status >= 200 && xhr.status < 300) {
            let data;
            try { data = JSON.parse(xhr.responseText); } catch (e) { data = null; }
            if (data && data.status === 'success') {
              const rawItems = data.data || data[ep.key] || [];
              rawItems.forEach(item => {
                item._category = ep.type;
                item._category_label = ep.type === 'working_pictures' ? 'Picture' : ep.type === 'tools_updates' ? 'Tools' : 'Account';
                item._icon = ep.type === 'working_pictures' ? 'bi-image' : ep.type === 'tools_updates' ? 'bi-tools' : 'bi-person-badge';
                itemsData.push(item);
              });
            }
          }
          if (completed === endpoints.length) {
            renderItems();
          }
        };

        xhr.onerror = xhr.ontimeout = function() {
          completed++;
          if (completed === endpoints.length) {
            renderItems();
          }
        };

        xhr.send();
      });
    }

    function renderItems(filter = '') {
      const container = document.getElementById('itemsList');
      container.classList.remove('loading-row');

      let list = itemsData;
      if (filter) {
        const f = filter.toLowerCase();
        list = itemsData.filter(i => (i.title || i.name || '').toLowerCase().includes(f) || (i.description || '').toLowerCase().includes(f));
      }

      if (list.length === 0) {
        container.innerHTML = '<div class="card"><div class="empty-state"><div class="title">No Items Found</div><div class="text">No items available in this category right now.</div></div></div>';
        return;
      }

      let html = '';
      list.forEach(item => {
        const title = item.title || item.name || 'Unknown';
        const desc = item.description || '';
        const price = item.display_price_str || item.display_price || item.price || '0';
        const originalPrice = item.provider_price || item.price || '0';
        const image = item.picture || '';
        const id = item._id || item.id || '';

        html += `<div class="item-card" data-item-id="${id}" data-item-category="${item._category}" onclick="openPurchaseSheet('${id}', '${item._category}')">`;
        html += `<div class="item-icon"><i class="bi ${item._icon}"></i></div>`;
        html += `<div class="item-info">`;
        html += `<div class="item-category">${item._category_label}</div>`;
        html += `<div class="item-title">${title}</div>`;
        if (desc) html += `<div class="item-desc">${desc.substring(0, 80)}${desc.length > 80 ? '...' : ''}</div>`;
        html += `<div class="item-price">₦${price}`;
        if (parseFloat(originalPrice) < parseFloat(price)) {
          html += `<span class="original">₦${originalPrice}</span>`;
        }
        html += `</div>`;
        html += `</div>`;
        html += `</div>`;
      });

      container.innerHTML = html;
    }

    function filterItems(val) {
      renderItems(val);
    }

    // ===== SHEET LOGIC =====
    function openPurchaseSheet(itemId, category) {
      selectedItem = itemsData.find(i => i._id === itemId && i._category === category);
      if (!selectedItem) return;

      purchaseQty = 1;

      var backdrop = document.getElementById('purchaseBackdrop');
      var sheet = document.getElementById('purchaseSheet');
      backdrop.classList.add('show');
      sheet.classList.remove('closing');
      sheet.classList.add('show');
      document.body.classList.add('no-scroll');

      resetPurchaseFlow();
      setTimeout(() => {
        showStep(1);
        loadSheetItems();
      }, 100);
    }

    function closePurchaseSheet() {
      const sheet = document.getElementById('purchaseSheet');
      sheet.classList.add('closing');
      setTimeout(() => {
        document.getElementById('purchaseBackdrop').classList.remove('show');
        sheet.classList.remove('show');
        sheet.classList.remove('closing');
        document.body.classList.remove('no-scroll');
      }, 320);
    }

    function resetPurchaseFlow() {
      purchaseQty = 1;
      document.getElementById('txPin').value = '';
      document.getElementById('buyError').textContent = '';
      document.getElementById('qtyValue').textContent = '1';
    }

    function showStep(n) {
      for (var i = 1; i <= 3; i++) {
        var stepDiv = document.getElementById('step' + i);
        var stepBar = document.getElementById('step' + i + '-bar');
        if (stepDiv) stepDiv.style.display = (i === n) ? 'block' : 'none';
        if (stepBar) stepBar.classList.toggle('active', i <= n);
      }
      var backBtn = document.getElementById('sheet-back-btn');
      if (backBtn) {
        backBtn.style.opacity = (n > 1) ? '1' : '0';
        backBtn.style.visibility = (n > 1) ? 'visible' : 'hidden';
      }
      var subtitle = document.getElementById('sheet-step-subtitle');
      if (subtitle) {
        var subtitles = { 1: 'Select an item', 2: 'Review your order', 3: 'Enter PIN to pay' };
        subtitle.textContent = subtitles[n] || 'Complete your purchase';
      }
      currentStep = n;

      if (n === 2 && selectedItem) {
        updateConfirmDetails();
      }
      if (n === 3 && selectedItem) {
        document.getElementById('pinItemName').textContent = selectedItem.title || selectedItem.name || 'Unknown';
        document.getElementById('pinTotal').textContent = '₦' + calculateTotal();
      }
    }

    function goBackStep() {
      if (currentStep > 1) {
        showStep(currentStep - 1);
      }
    }

    function loadSheetItems() {
      const container = document.getElementById('itemList');
      container.classList.remove('loading-row');

      // Show same items as main list but in select-option style
      let list = itemsData;
      if (selectedItem) {
        // Pre-select the clicked item
      }

      if (list.length === 0) {
        container.innerHTML = '<div style="text-align:center; color:var(--muted); font-size:11px; padding:20px;">No items available</div>';
        return;
      }

      let html = '';
      list.forEach(item => {
        const title = item.title || item.name || 'Unknown';
        const price = item.display_price_str || item.display_price || item.price || '0';
        const isSelected = selectedItem && item._id === selectedItem._id;

        html += `<div class="select-option ${isSelected ? 'selected' : ''}" data-item-id="${item._id}" data-item-category="${item._category}">`;
        html += `<span class="select-icon"><i class="bi ${item._icon}"></i></span>`;
        html += `<span class="select-name">${title}<span class="select-desc">${item._category_label} • ₦${price}</span></span>`;
        html += `<span class="price-tag">₦${price}</span>`;
        html += `<span class="select-radio"></span>`;
        html += `</div>`;
      });
      container.innerHTML = html;

      container.querySelectorAll('.select-option').forEach(el => {
        el.addEventListener('click', function() {
          const id = this.dataset.itemId;
          const cat = this.dataset.itemCategory;
          selectedItem = itemsData.find(i => i._id === id && i._category === cat);
          container.querySelectorAll('.select-option').forEach(opt => opt.classList.remove('selected'));
          this.classList.add('selected');
          setTimeout(() => showStep(2), 200);
        });
      });
    }

    function updateConfirmDetails() {
      if (!selectedItem) return;
      const title = selectedItem.title || selectedItem.name || 'Unknown';
      const price = selectedItem.display_price_str || selectedItem.display_price || selectedItem.price || '0';
      const categoryLabel = selectedItem._category_label || 'Item';

      document.getElementById('confirmItemName').textContent = title;
      document.getElementById('confirmCategory').textContent = categoryLabel;
      document.getElementById('confirmUnitPrice').textContent = '₦' + price;
      document.getElementById('confirmTotal').textContent = '₦' + calculateTotal();

      // Preview image if available
      const previewDiv = document.getElementById('itemPreview');
      if (selectedItem.picture) {
        previewDiv.innerHTML = `<img src="${selectedItem.picture}" class="item-image" alt="${title}">`;
      } else {
        previewDiv.innerHTML = '';
      }
    }

    function changeQty(delta) {
      purchaseQty = Math.max(1, purchaseQty + delta);
      document.getElementById('qtyValue').textContent = purchaseQty;
      document.getElementById('confirmTotal').textContent = '₦' + calculateTotal();
      if (document.getElementById('pinTotal')) {
        document.getElementById('pinTotal').textContent = '₦' + calculateTotal();
      }
    }

    function calculateTotal() {
      if (!selectedItem) return '0.00';
      const price = parseFloat(selectedItem.display_price || selectedItem.display_price_str || selectedItem.price || 0);
      return (price * purchaseQty).toFixed(2);
    }

    // ===== SAFE JSON PARSER =====
    function safeJsonParse(text) {
      try {
        return { data: JSON.parse(text), raw: text };
      } catch (e) {
        var match = text.match(/\{[\s\S]*"status"\s*:\s*"[^"]+"[\s\S]*\}/);
        if (match) {
          try { return { data: JSON.parse(match[0]), raw: text }; } catch (e2) {}
        }
        return { data: null, raw: text, error: e.message };
      }
    }

    // ===== CONFIRM PURCHASE =====
    function confirmPurchase() {
      var pin = document.getElementById('txPin').value.trim();
      var error = document.getElementById('buyError');
      var btn = document.getElementById('confirmBuyBtn');
      var btnText = btn.querySelector('.button-text');
      var spinner = btn.querySelector('.spinner');

      if (!pin || pin.length < 3) {
        error.textContent = 'Please enter a valid PIN.';
        return;
      }
      if (!selectedItem) {
        error.textContent = 'No item selected.';
        return;
      }
      error.textContent = '';

      btnText.style.display = 'none';
      spinner.style.display = 'inline-block';
      btn.disabled = true;

      var actionMap = {
        'working_pictures': 'purchase-working-picture',
        'tools_updates': 'purchase-tools-update',
        'accounts': 'purchase-account'
      };

      var payload = {
        action: actionMap[selectedItem._category],
        item_id: selectedItem._id,
        quantity: purchaseQty,
        pin: pin
      };

      var xhr = new XMLHttpRequest();
      xhr.open('POST', 'server/jvb_single.php', true);
      xhr.setRequestHeader('Content-Type', 'application/json');
      xhr.timeout = 30000;

      xhr.onload = function() {
        btnText.style.display = 'inline-block';
        spinner.style.display = 'none';
        btn.disabled = false;

        var text = xhr.responseText;
        var result = safeJsonParse(text);
        var data = result.data;

        if (!data) {
          var preview = result.raw.substring(0, 200).replace(/</g, '&lt;');
          error.innerHTML = '<b>Server Error:</b> Could not parse response.<br><span style="font-size:9px;color:#999;">' + preview + '</span>';
          return;
        }

        if (data.status === 'success') {
          closePurchaseSheet();
          showSuccessModal(data);
          addTransactionToList(data);
        } else {
          var msg = data.message || 'Purchase failed. Please try again.';
          if (data.remaining_minutes) {
            msg += ' (' + data.remaining_minutes + ' min remaining)';
          }
          if (data.remaining_attempts !== undefined) {
            msg += ' (' + data.remaining_attempts + ' attempts left)';
          }
          error.textContent = msg;
        }
      };

      xhr.onerror = function() {
        btnText.style.display = 'inline-block';
        spinner.style.display = 'none';
        btn.disabled = false;
        error.textContent = 'Network error. Please check your connection.';
      };

      xhr.ontimeout = function() {
        btnText.style.display = 'inline-block';
        spinner.style.display = 'none';
        btn.disabled = false;
        error.textContent = 'Request timed out. Please check your purchases before trying again.';
      };

      xhr.send(JSON.stringify(payload));
    }

    // ===== SUCCESS MODAL =====
    function showSuccessModal(data) {
      var backdrop = document.getElementById('successBackdrop');
      var sheet = document.getElementById('successSheet');
      var linkDiv = document.getElementById('successAccessLink');

      var accessLink = data.data && data.data.accessible_link ? data.data.accessible_link : null;
      if (accessLink) {
        linkDiv.innerHTML = '<div class="access-link-box">' + accessLink + '</div><a href="' + accessLink + '" class="access-link-btn" target="_blank" style="width:100%; justify-content:center;"><i class="bi bi-box-arrow-up-right"></i> Open Link</a>';
      } else {
        linkDiv.innerHTML = '<div class="text" style="margin-bottom:0;">Your purchase is being processed. Check your transactions for updates.</div>';
      }

      backdrop.classList.add('show');
      sheet.classList.remove('closing');
      sheet.classList.add('show');
    }

    function closeSuccessSheet() {
      const sheet = document.getElementById('successSheet');
      sheet.classList.add('closing');
      setTimeout(() => {
        document.getElementById('successBackdrop').classList.remove('show');
        sheet.classList.remove('show');
        sheet.classList.remove('closing');
      }, 320);
    }

    // ===== ADD TRANSACTION TO LIST =====
    function addTransactionToList(data) {
      var container = document.getElementById('transactionList');
      var emptyState = container.querySelector('.empty-state');
      if (emptyState) {
        emptyState.parentElement.remove();
      }

      var d = data.data || {};
      var itemName = selectedItem ? (selectedItem.title || selectedItem.name || 'Unknown') : 'Unknown';
      var ref = data.ref_id || '';
      var amount = d.amount || calculateTotal();
      var category = selectedItem ? selectedItem._category : 'working_pictures';
      var catIcon = category === 'working_pictures' ? 'bi-image' : category === 'tools_updates' ? 'bi-tools' : 'bi-person-badge';
      var catLabel = category === 'working_pictures' ? 'Picture' : category === 'tools_updates' ? 'Tools' : 'Account';
      var accessLink = d.accessible_link || '';
      var now = new Date();
      var dateStr = now.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) + ' at ' + now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false });

      var card = document.createElement('div');
      card.className = 'tx-card';
      card.setAttribute('data-ref', ref);
      card.setAttribute('data-status', 'pending');
      card.setAttribute('data-item', itemName);
      card.setAttribute('data-category', catLabel);
      card.setAttribute('data-amount', amount);
      card.setAttribute('data-qty', purchaseQty);
      card.setAttribute('data-oldbal', '0.00');
      card.setAttribute('data-newbal', '0.00');
      card.setAttribute('data-desc', '');
      card.setAttribute('data-note', '');
      card.setAttribute('data-link', accessLink);
      card.setAttribute('data-date', dateStr);
      card.setAttribute('data-providerref', '');
      card.setAttribute('onclick', 'openTxDetailSheet(this)');
      card.innerHTML =
        '<div class="tx-icon"><i class="bi ' + catIcon + '"></i></div>' +
        '<div class="tx-info">' +
          '<div class="tx-category">' + catLabel + '</div>' +
          '<div class="tx-title">' + itemName + '</div>' +
          '<div class="tx-ref">' + ref.substring(0, 20) + '...</div>' +
          '<span class="tx-status pending">PENDING</span>' +
        '</div>' +
        '<div style="text-align:right;">' +
          '<div class="tx-amount">₦' + amount + '</div>' +
          '<div class="tx-date">Just now</div>' +
          (purchaseQty > 1 ? '<div style="font-size:9px; color:var(--muted); margin-top:2px;">x' + purchaseQty + '</div>' : '') +
        '</div>';

      container.insertBefore(card, container.firstChild);
      updateTxCounts();
    }

    // ===== TRANSACTION FILTERS =====
    function filterTransactions(status) {
      document.querySelectorAll('.status-toggle-btn').forEach(function(btn) {
        btn.classList.toggle('active', btn.dataset.filter === status);
      });

      var listContainer = document.getElementById('transactionList');
      var cards = document.querySelectorAll('.tx-card');
      var visibleCount = 0;

      // Remove empty state if exists
      var existingEmpty = listContainer.querySelector('.empty-state-filter');
      if (existingEmpty) existingEmpty.remove();

      // Remove existing section headers
      listContainer.querySelectorAll('.tx-section-header').forEach(function(el) { el.remove(); });

      // First pass: determine visibility using inline style (most reliable)
      cards.forEach(function(card) {
        var cardStatus = (card.getAttribute('data-status') || 'pending').toLowerCase().trim();
        var show = false;
        if (status === 'all') {
          show = true;
        } else if (status === 'failed') {
          show = (cardStatus === 'failed' || cardStatus === 'cancelled');
        } else {
          show = (cardStatus === status);
        }
        // Use inline style for maximum reliability
        card.style.display = show ? 'flex' : 'none';
        if (show) visibleCount++;
      });

      if (visibleCount === 0 && cards.length > 0) {
        var emptyDiv = document.createElement('div');
        emptyDiv.className = 'empty-state empty-state-filter';
        emptyDiv.innerHTML = '<div class="title">No ' + status + ' purchases</div><div class="text">Switch to another tab to see your purchases.</div>';
        listContainer.appendChild(emptyDiv);
      } else if (status === 'all') {
        // Group by status: Pending, Success, Failed/Cancelled
        var groups = { pending: [], success: [], failed: [] };
        cards.forEach(function(card) {
          if (card.style.display === 'none') return;
          var st = (card.getAttribute('data-status') || 'pending').toLowerCase().trim();
          if (st === 'pending') groups.pending.push(card);
          else if (st === 'success') groups.success.push(card);
          else groups.failed.push(card); // failed or cancelled
        });

        var order = ['pending', 'success', 'failed'];
        var labels = { pending: 'Pending', success: 'Success', failed: 'Failed / Cancelled' };

        // Reorder DOM: insert section headers then cards in groups
        order.forEach(function(key) {
          if (groups[key].length > 0) {
            var header = document.createElement('div');
            header.className = 'tx-section-header';
            header.innerHTML = labels[key] + ' <span style="color:var(--muted);font-weight:400;">(' + groups[key].length + ')</span>';
            listContainer.appendChild(header);
            groups[key].forEach(function(card) {
              listContainer.appendChild(card);
            });
          }
        });
      }
    }

    function updateTxCounts() {
      var cards = document.querySelectorAll('.tx-card');
      var counts = { all: 0, pending: 0, success: 0, failed: 0, cancelled: 0 };
      cards.forEach(function(card) {
        var st = card.getAttribute('data-status');
        counts.all++;
        if (counts[st] !== undefined) counts[st]++;
      });
      document.getElementById('count-all').textContent = counts.all;
      document.getElementById('count-pending').textContent = counts.pending;
      document.getElementById('count-success').textContent = counts.success;
      document.getElementById('count-failed').textContent = counts.failed + counts.cancelled;
    }

    // ===== TRANSACTION OVERLAY =====
    function openTxOverlay() {
      var overlay = document.getElementById('txOverlay');
      overlay.classList.add('show');
      document.body.classList.add('no-scroll');
      // Apply current filter
      var activeBtn = document.querySelector('.status-toggle-btn.active');
      if (activeBtn) {
        filterTransactions(activeBtn.dataset.filter);
      }
    }
    function closeTxOverlay() {
      var overlay = document.getElementById('txOverlay');
      overlay.classList.remove('show');
      document.body.classList.remove('no-scroll');
    }

    // ===== TX DETAIL SHEET =====
    function openTxDetailSheet(card) {
      var backdrop = document.getElementById('txDetailBackdrop');
      var sheet = document.getElementById('txDetailSheet');

      // Populate data from card attributes
      var itemName = card.getAttribute('data-item') || 'Unknown';
      var category = card.getAttribute('data-category') || 'Purchase';
      var amount = card.getAttribute('data-amount') || '0.00';
      var qty = card.getAttribute('data-qty') || '1';
      var ref = card.getAttribute('data-ref') || '-';
      var status = card.getAttribute('data-status') || 'pending';
      var oldBal = card.getAttribute('data-oldbal') || '0.00';
      var newBal = card.getAttribute('data-newbal') || '0.00';
      var desc = card.getAttribute('data-desc') || '';
      var note = card.getAttribute('data-note') || '';
      var link = card.getAttribute('data-link') || '';
      var date = card.getAttribute('data-date') || '-';
      var providerRef = card.getAttribute('data-providerref') || '';

      // Set icon based on category
      var iconMap = { 'Picture': 'bi-image', 'Tools': 'bi-tools', 'Account': 'bi-person-badge' };
      var iconClass = iconMap[category] || 'bi-receipt';
      document.getElementById('txDetailIcon').innerHTML = '<i class="bi ' + iconClass + '"></i>';

      document.getElementById('txDetailItemName').textContent = itemName;
      document.getElementById('txDetailCategory').textContent = category;
      document.getElementById('txDetailRef').textContent = ref;

      // Status badge
      var statusBadge = document.getElementById('txDetailStatus');
      statusBadge.textContent = status.toUpperCase();
      statusBadge.className = 'tx-detail-badge ' + status;

      document.getElementById('txDetailAmount').textContent = '₦' + amount;
      document.getElementById('txDetailQty').textContent = qty;
      document.getElementById('txDetailReference').textContent = ref;
      document.getElementById('txDetailDate').textContent = date;
      document.getElementById('txDetailOldBal').textContent = '₦' + oldBal;
      document.getElementById('txDetailNewBal').textContent = '₦' + newBal;

      // Description
      var descBox = document.getElementById('txDetailDescBox');
      if (desc && desc.trim().length > 0) {
        document.getElementById('txDetailDesc').textContent = desc;
        descBox.style.display = 'block';
      } else {
        descBox.style.display = 'none';
      }

      // Note
      var noteBox = document.getElementById('txDetailNoteBox');
      if (note && note.trim().length > 0) {
        document.getElementById('txDetailNote').textContent = note;
        noteBox.style.display = 'block';
      } else {
        noteBox.style.display = 'none';
      }

      // Access link button
      var accessBtn = document.getElementById('txDetailAccessBtn');
      var accessDisabled = document.getElementById('txDetailAccessDisabled');
      if (link && link.trim().length > 0 && status === 'success') {
        accessBtn.href = link;
        accessBtn.style.display = 'flex';
        accessDisabled.style.display = 'none';
      } else {
        accessBtn.style.display = 'none';
        accessDisabled.style.display = 'flex';
      }

      // Show sheet
      backdrop.classList.add('show');
      sheet.classList.remove('closing');
      sheet.classList.add('show');
      document.body.classList.add('no-scroll');
    }

    function closeTxDetailSheet() {
      var sheet = document.getElementById('txDetailSheet');
      var backdrop = document.getElementById('txDetailBackdrop');
      sheet.classList.add('closing');
      setTimeout(function() {
        backdrop.classList.remove('show');
        sheet.classList.remove('show');
        sheet.classList.remove('closing');
        document.body.classList.remove('no-scroll');
      }, 320);
    }

    // ===== INIT =====
    document.addEventListener('DOMContentLoaded', function() {
      loadItems('all');
      updateTxCounts();
    });
  </script>

  <!-- Transaction Detail Sheet -->
  <div id="txDetailBackdrop" class="backdrop tx-detail-backdrop" onclick="closeTxDetailSheet()"></div>
  <div id="txDetailSheet" class="sheet tx-detail-sheet">
    <div class="sheet-handle"><div class="sheet-handle-bar"></div></div>
    <div style="position:relative; padding: 0 16px 10px; text-align: center;">
      <div class="sheet-title">Transaction Details</div>
      <div class="sheet-subtitle" id="txDetailRef">-</div>
      <button type="button" class="close-sheet" onclick="closeTxDetailSheet()" aria-label="Close" style="position:absolute; right:0; top:0;"><i class="bi bi-x-lg"></i></button>
    </div>

    <div id="txDetailContent">
      <div class="tx-detail-icon" id="txDetailIcon"><i class="bi bi-receipt"></i></div>
      <div class="tx-detail-title" id="txDetailItemName">-</div>
      <div class="tx-detail-subtitle" id="txDetailCategory">-</div>

      <div class="confirm-card">
        <div class="tx-detail-row">
          <span class="tx-detail-label">Status</span>
          <span class="tx-detail-value"><span class="tx-detail-badge" id="txDetailStatus">-</span></span>
        </div>
        <div class="tx-detail-row">
          <span class="tx-detail-label">Amount Paid</span>
          <span class="tx-detail-value" id="txDetailAmount">-</span>
        </div>
        <div class="tx-detail-row">
          <span class="tx-detail-label">Quantity</span>
          <span class="tx-detail-value" id="txDetailQty">-</span>
        </div>
        <div class="tx-detail-row">
          <span class="tx-detail-label">Reference</span>
          <span class="tx-detail-value mono" id="txDetailReference">-</span>
        </div>
        <div class="tx-detail-row">
          <span class="tx-detail-label">Date</span>
          <span class="tx-detail-value" id="txDetailDate">-</span>
        </div>
      </div>

      <div class="confirm-card">
        <div class="tx-detail-row">
          <span class="tx-detail-label">Balance Before</span>
          <span class="tx-detail-value" id="txDetailOldBal">-</span>
        </div>
        <div class="tx-detail-row">
          <span class="tx-detail-label">Balance After</span>
          <span class="tx-detail-value" id="txDetailNewBal">-</span>
        </div>
      </div>

      <div class="tx-detail-note" id="txDetailDescBox" style="display:none;">
        <div class="tx-detail-note-label">Description</div>
        <div id="txDetailDesc">-</div>
      </div>

      <div class="tx-detail-note" id="txDetailNoteBox" style="display:none;">
        <div class="tx-detail-note-label">Note</div>
        <div id="txDetailNote">-</div>
      </div>

      <a href="#" id="txDetailAccessBtn" class="tx-detail-access-btn" target="_blank" style="display:none;">
        <i class="bi bi-box-arrow-up-right"></i> Access Content
      </a>
      <button type="button" id="txDetailAccessDisabled" class="tx-detail-access-btn disabled" style="display:none;" disabled>
        <i class="bi bi-lock"></i> Content Not Available
      </button>
    </div>
  </div>

</body>
</html>

<?php endif; ?>

<?php if ($user["is_restricted"] == "1"): ?>
  <?php include "restriction.php"; ?>
<?php endif; ?>