<?php
// kasir/penjualan.php — halaman POS utama
require_once '../includes/config.php';
require_once '../includes/auth.php';
requireKasir();

$user = currentUser();

$barangList = $pdo->query("
    SELECT b.*, k.nama AS kat_nama
    FROM barang b
    LEFT JOIN kategori k ON b.kategori_id = k.id
    WHERE b.aktif=1 AND b.stok > 0
    ORDER BY k.nama, b.nama
    LIMIT 100
")->fetchAll();

$kategoriList = $pdo->query("SELECT DISTINCT k.id, k.nama FROM kategori k JOIN barang b ON b.kategori_id=k.id WHERE b.aktif=1 AND b.stok>0 ORDER BY k.nama")->fetchAll();
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <title>Penjualan — <?= NAMA_TOKO ?></title>
  <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="<?= BASE_URL ?>css/style.css?v=<?= time() ?>">
  <style>
    /* ── Barcode Scanner ── */
    .scan-btn {
      background: rgba(212,175,55,.15); color: var(--primary);
      border: 1px solid rgba(212,175,55,.35);
      border-radius: 10px; padding: 10px 16px; font-size: 13px;
      font-weight: 600; cursor: pointer; font-family: inherit;
      display: flex; align-items: center; gap: 6px; white-space: nowrap;
      transition: all .2s;
    }
    .scan-btn:hover { background: rgba(212,175,55,.25); border-color: var(--primary); }
    #scanner-modal-overlay {
      display: none; position: fixed; inset: 0;
      background: rgba(0,0,0,.85); z-index: 2000;
      align-items: center; justify-content: center; flex-direction: column;
    }
    #scanner-modal-overlay.open { display: flex; }
    #scanner-box {
      background: #000; border-radius: 16px; overflow: hidden;
      width: 320px; max-width: 90vw;
    }
    #reader { width: 100%; }
    #scanner-status {
      color: #fff; font-size: 14px; font-weight: 600;
      margin-top: 16px; text-align: center; min-height: 22px;
    }
    #scanner-result {
      background: rgba(255,255,255,.1); color: #fff;
      border-radius: 10px; padding: 10px 16px; margin-top: 10px;
      font-size: 13px; text-align: center; min-width: 280px;
      display: none;
    }
    #scanner-result.found  { background: rgba(16,185,129,.3); }
    #scanner-result.notfound { background: rgba(239,68,68,.3); }
    .scanner-close {
      margin-top: 20px; background: rgba(255,255,255,.15);
      border: none; color: #fff; border-radius: 10px;
      padding: 10px 28px; font-size: 14px; font-weight: 600;
      cursor: pointer; font-family: inherit;
    }
    .scanner-close:hover { background: rgba(255,255,255,.25); }
    .scan-pulse {
      animation: pulse 1s ease-in-out infinite;
    }
    @keyframes pulse {
      0%, 100% { opacity: 1; }
      50% { opacity: .5; }
    }
  </style>
</head>
<body class="pos-page">
<div class="layout">
  <?php include '../includes/sidebar.php'; ?>

  <div class="main-content">
    <div class="topbar">
      <button class="hamburger" id="hamburgerBtn" aria-label="Menu">☰</button>
      <div class="topbar-title">🛒 Penjualan</div>
      <span style="font-size:13px;color:var(--muted)"><?= htmlspecialchars($user['nama']) ?> — <?= date('d/m/Y H:i') ?></span>
    </div>

    <!-- Tab bar mobile -->
    <div class="pos-tab-bar" style="display:none">
      <button class="pos-tab active" id="tabProduk" onclick="switchTab('produk')">📦 Produk</button>
      <button class="pos-tab" id="tabKeranjang" onclick="switchTab('keranjang')">🛒 Keranjang <span id="cartBadge" style="background:var(--primary);color:#fff;border-radius:20px;padding:1px 7px;font-size:11px;margin-left:4px;display:none">0</span></button>
    </div>

    <div class="pos-layout">

      <!-- Produk -->
      <div class="pos-products tab-active" id="panelProduk">
        <!-- Search + Filter + Scan -->
        <div style="display:flex;gap:8px;margin-bottom:12px;flex-wrap:wrap;align-items:center">
          <input type="text" id="searchBarang" class="form-control"
                 placeholder="Cari barang..."
                 style="flex:1;min-width:120px" oninput="filterBarang()">
          <select id="filterKat" class="form-control" style="width:auto;max-width:130px" onchange="filterBarang()">
            <option value="">Semua</option>
            <?php foreach ($kategoriList as $k): ?>
            <option value="<?= $k['id'] ?>"><?= htmlspecialchars($k['nama']) ?></option>
            <?php endforeach; ?>
          </select>
          <button class="scan-btn" onclick="openScanner()" style="padding:9px 10px">📷</button>
        </div>
        <!-- Info hasil pencarian -->
        <div id="searchInfo" style="display:none;font-size:12px;color:var(--muted);padding:4px 0 8px;font-weight:500"></div>

        <!-- Tombol Bayar cepat (mobile only) -->
        <div class="mobile-quick-bayar" id="quickBayar" style="display:none">
          <button onclick="openBayar()" style="width:100%;padding:12px;background:var(--primary);color:#fff;border:none;border-radius:12px;font-size:14px;font-weight:700;cursor:pointer;font-family:inherit;display:flex;align-items:center;justify-content:center;gap:8px">
            💳 Bayar — <span id="quickTotal">Rp 0</span>
          </button>
        </div>

        <div class="product-grid" id="productGrid">
          <?php foreach ($barangList as $b): ?>
          <div class="product-card"
               data-id="<?= $b['id'] ?>"
               data-nama="<?= htmlspecialchars($b['nama']) ?>"
               data-harga="<?= $b['harga_jual'] ?>"
               data-stok="<?= $b['stok'] ?>"
               data-kat="<?= $b['kategori_id'] ?>"
               data-kode="<?= htmlspecialchars($b['kode']) ?>"
               onclick="addToCart(this)">
            <div class="p-icon">
              <?php
              $icons = ['Minuman'=>'🧃','Makanan'=>'🍜','Snack'=>'🍟','Rokok'=>'🚬'];
              echo $icons[$b['kat_nama']] ?? '📦';
              ?>
            </div>
            <div class="p-name"><?= htmlspecialchars($b['nama']) ?></div>
            <div class="p-price"><?= formatRp((float)$b['harga_jual']) ?></div>
            <div class="p-stok">Stok: <?= $b['stok'] ?></div>
          </div>
          <?php endforeach; ?>
        </div>

        <?php if (empty($barangList)): ?>
        <div style="text-align:center;color:var(--muted);padding:60px 20px">
          <div style="font-size:48px;margin-bottom:12px">📦</div>
          <div>Tidak ada barang tersedia</div>
        </div>
        <?php endif; ?>
      </div>

      <!-- Keranjang -->
      <div class="pos-cart" id="panelKeranjang">
        <div class="pos-cart-header">
          🛒 Keranjang
          <span id="cartCount" style="background:var(--primary);color:#fff;border-radius:20px;padding:2px 8px;font-size:12px;margin-left:8px">0</span>
        </div>

        <div class="cart-items" id="cartItems">
          <div class="cart-empty" id="cartEmpty">
            <div style="font-size:40px;margin-bottom:8px">🛒</div>
            <div>Keranjang kosong</div>
            <div style="font-size:12px;margin-top:4px">Klik barang atau scan barcode</div>
          </div>
        </div>

        <div class="cart-total">
          <div class="total-row"><span>Subtotal</span><span id="subtotal">Rp 0</span></div>
          <div class="total-row grand"><span>TOTAL</span><span id="grandTotal">Rp 0</span></div>
        </div>

        <div class="cart-actions">
          <button class="btn-bayar" onclick="openBayar()">💳 Bayar</button>
          <button class="btn-clear" onclick="clearCart()">🗑️ Kosongkan</button>
        </div>
      </div>

    </div>
  </div>
</div>

<!-- ── Modal Scanner ── -->
<div id="scanner-modal-overlay">
  <div id="scanner-box">
    <div id="reader"></div>
  </div>
  <div id="scanner-status" class="scan-pulse">📷 Arahkan kamera ke barcode...</div>
  <div id="scanner-result"></div>
  <button class="scanner-close" onclick="closeScanner()">✕ Tutup Scanner</button>
</div>

<!-- Modal Pembayaran -->
<div class="modal-overlay" id="modalBayar">
  <div class="modal">
    <div class="modal-header">
      <h4>💳 Pembayaran</h4>
      <button class="modal-close" onclick="closeBayar()">×</button>
    </div>
    <div class="modal-body">
      <div style="background:var(--primary-l);border-radius:12px;padding:16px;margin-bottom:20px;text-align:center">
        <div style="font-size:13px;color:var(--primary);font-weight:600">TOTAL BAYAR</div>
        <div style="font-size:32px;font-weight:700;color:var(--primary)" id="modalTotal">Rp 0</div>
      </div>
      <div class="form-group">
        <label>Metode Pembayaran</label>
        <select id="metode" class="form-control" onchange="hitungKembalian()">
          <option value="tunai">💵 Tunai</option>
          <option value="qris">📱 QRIS</option>
        </select>
      </div>
      <div id="tunaiSection">
        <div class="form-group">
          <label>Uang Diterima (Rp)</label>
          <input type="number" id="uangDiterima" class="form-control" placeholder="0" oninput="hitungKembalian()" min="0">
        </div>
        <div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:16px">
          <?php foreach ([5000,10000,20000,50000,100000] as $nom): ?>
          <button class="btn btn-ghost btn-sm" onclick="setNominal(<?= $nom ?>)"><?= formatRp($nom) ?></button>
          <?php endforeach; ?>
        </div>
        <div style="background:var(--green-l);border-radius:12px;padding:14px;display:flex;justify-content:space-between;align-items:center">
          <span style="font-size:14px;color:#065f46;font-weight:600">Kembalian</span>
          <span style="font-size:22px;font-weight:700;color:#065f46" id="kembalian">Rp 0</span>
        </div>
      </div>
    </div>
    <div class="modal-footer">
      <button class="btn btn-ghost" onclick="closeBayar()">Batal</button>
      <button class="btn btn-green" onclick="prosesTransaksi()" id="btnProses">✅ Proses</button>
    </div>
  </div>
</div>

<!-- Modal Struk -->
<div class="modal-overlay" id="modalStruk">
  <div class="modal" style="max-width:360px">
    <div class="modal-header">
      <h4>🧾 Struk Transaksi</h4>
      <button class="modal-close" onclick="closeStruk()">×</button>
    </div>
    <div class="modal-body">
      <div class="struk" id="strukContent"></div>
    </div>
    <div class="modal-footer">
      <button class="btn btn-ghost" onclick="closeStruk()">Tutup</button>
      <button class="btn btn-primary" onclick="window.print()">🖨️ Cetak</button>
    </div>
  </div>
</div>

<!-- html5-qrcode library -->
<script src="https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js"></script>
<script src="<?= BASE_URL ?>js/app.js"></script>
<script>
const KASIR_ID  = <?= $user['id'] ?>;
const NAMA_TOKO = "<?= addslashes(NAMA_TOKO) ?>";
const ALAMAT    = "<?= addslashes(ALAMAT_TOKO) ?>";
const TELEPON   = "<?= addslashes(TELEPON_TOKO) ?>";

let cart = [];
let html5QrCode = null;
let scannerOpen = false;
let lastScanned = '';
let lastScannedTime = 0;

function formatRp(n) {
  return 'Rp ' + Math.round(n).toLocaleString('id-ID');
}

// ══════════════════════════════════════
//  SCANNER
// ══════════════════════════════════════
function openScanner() {
  document.getElementById('scanner-modal-overlay').classList.add('open');
  document.getElementById('scanner-result').style.display = 'none';
  document.getElementById('scanner-status').textContent = '📷 Arahkan kamera ke barcode...';

  html5QrCode = new Html5Qrcode("reader");
  html5QrCode.start(
    { facingMode: "environment" },   // kamera belakang HP
    { fps: 10, qrbox: { width: 260, height: 160 } },
    onScanSuccess,
    () => {}  // abaikan error frame kosong
  ).catch(err => {
    document.getElementById('scanner-status').textContent = '⚠️ Tidak bisa akses kamera: ' + err;
  });

  scannerOpen = true;
}

function closeScanner() {
  if (html5QrCode && scannerOpen) {
    html5QrCode.stop().catch(() => {});
    scannerOpen = false;
  }
  document.getElementById('scanner-modal-overlay').classList.remove('open');
}

async function onScanSuccess(decodedText) {
  // Hindari scan berulang dalam 2 detik
  const now = Date.now();
  if (decodedText === lastScanned && now - lastScannedTime < 2000) return;
  lastScanned     = decodedText;
  lastScannedTime = now;

  const resultEl = document.getElementById('scanner-result');
  resultEl.style.display = 'block';
  document.getElementById('scanner-status').textContent = '🔍 Mencari...';

  // 1. Cek dulu di DOM (barang yang sudah tampil)
  const card = document.querySelector(`.product-card[data-kode="${CSS.escape(decodedText)}"]`);

  if (card) {
    // Ditemukan di DOM
    tambahDariCard(card, resultEl);
  } else {
    // Tidak ada di DOM → cari ke database via AJAX
    try {
      const url = `<?= BASE_URL ?>kasir/api_cari_barang.php?q=${encodeURIComponent(decodedText)}`;
      const res  = await fetch(url);
      const data = await res.json();

      // Cari yang kodenya persis sama
      const barang = data.find(b =>
        b.kode.toLowerCase() === decodedText.toLowerCase()
      );

      if (barang) {
        // Buat card sementara di memori lalu tambah ke keranjang
        const tempCard = document.createElement('div');
        tempCard.dataset.id    = barang.id;
        tempCard.dataset.nama  = barang.nama;
        tempCard.dataset.harga = barang.harga_jual;
        tempCard.dataset.stok  = barang.stok;
        tempCard.dataset.kat   = barang.kategori_id;
        tempCard.dataset.kode  = barang.kode;

        resultEl.className = 'found';
        resultEl.innerHTML = `✅ <strong>${barang.nama}</strong><br>Rp ${parseInt(barang.harga_jual).toLocaleString('id-ID')} — Stok: ${barang.stok}`;
        document.getElementById('scanner-status').textContent = '✅ Barang ditemukan!';
        addToCart(tempCard);

        setTimeout(() => {
          document.getElementById('scanner-status').textContent = '📷 Arahkan kamera ke barcode...';
          resultEl.style.display = 'none';
        }, 1800);
      } else {
        // Benar-benar tidak ada
        resultEl.className = 'notfound';
        resultEl.innerHTML = `❌ Barcode tidak ditemukan:<br><code>${decodedText}</code>`;
        document.getElementById('scanner-status').textContent = '❌ Barang tidak ada di database';
        setTimeout(() => {
          document.getElementById('scanner-status').textContent = '📷 Arahkan kamera ke barcode...';
          resultEl.style.display = 'none';
        }, 2500);
      }
    } catch(e) {
      resultEl.className = 'notfound';
      resultEl.innerHTML = `⚠️ Gagal cek database:<br><small>${e.message}</small>`;
      document.getElementById('scanner-status').textContent = '⚠️ Error koneksi';
      setTimeout(() => {
        document.getElementById('scanner-status').textContent = '📷 Arahkan kamera ke barcode...';
        resultEl.style.display = 'none';
      }, 2500);
    }
  }
}

function tambahDariCard(card, resultEl) {
  const nama = card.dataset.nama;
  resultEl.className = 'found';
  resultEl.innerHTML = `✅ <strong>${nama}</strong><br>Ditambahkan ke keranjang`;
  document.getElementById('scanner-status').textContent = '✅ Barang ditemukan!';
  card.style.border = '2px solid var(--green)';
  setTimeout(() => card.style.border = '', 1500);
  addToCart(card);
  setTimeout(() => {
    document.getElementById('scanner-status').textContent = '📷 Arahkan kamera ke barcode...';
    resultEl.style.display = 'none';
  }, 1500);
}

// ══════════════════════════════════════
//  FILTER BARANG
// ══════════════════════════════════════
// ── Cari barang: AJAX jika ada teks, DOM filter jika hanya kategori ──
let searchTimer = null;

function filterBarang() {
  clearTimeout(searchTimer);
  searchTimer = setTimeout(doSearch, 350);
}

async function doSearch() {
  const q   = document.getElementById('searchBarang').value.trim();
  const kat = document.getElementById('filterKat').value;
  const info = document.getElementById('searchInfo');

  // Kosong & tidak ada kat → tampilkan semua DOM card
  if (!q && !kat) {
    document.querySelectorAll('.product-card').forEach(el => el.style.display = '');
    document.querySelectorAll('.api-card').forEach(el => el.remove());
    if (info) info.style.display = 'none';
    return;
  }

  // Hanya filter kategori → filter DOM
  if (!q && kat) {
    document.querySelectorAll('.api-card').forEach(el => el.remove());
    document.querySelectorAll('.product-card').forEach(el => {
      el.style.display = el.dataset.kat === kat ? '' : 'none';
    });
    if (info) info.style.display = 'none';
    return;
  }

  // Ada teks → AJAX ke database
  if (info) { info.style.display = 'block'; info.textContent = '🔍 Mencari...'; }

  try {
    const url  = `<?= BASE_URL ?>kasir/api_cari_barang.php?q=${encodeURIComponent(q)}&kat=${kat}`;
    const res  = await fetch(url);
    const data = await res.json();
    renderBarangFromAPI(data, q);
    if (info) info.textContent = data.length > 0
      ? `Menampilkan ${data.length} hasil untuk "${q}"`
      : `❌ Tidak ada barang untuk "${q}"`;
  } catch(e) {
    // Fallback DOM filter
    document.querySelectorAll('.product-card').forEach(el => {
      const ok = el.dataset.nama.toLowerCase().includes(q.toLowerCase())
               || el.dataset.kode.toLowerCase().includes(q.toLowerCase());
      el.style.display = ok ? '' : 'none';
    });
    if (info) info.style.display = 'none';
  }
}

function renderBarangFromAPI(items, q) {
  const grid  = document.getElementById('productGrid');
  const icons = {'Minuman':'🧃','Makanan':'🍜','Snack':'🍟','Rokok':'🚬'};

  // Hapus api-card lama, sembunyikan PHP card
  grid.querySelectorAll('.api-card').forEach(el => el.remove());
  grid.querySelectorAll('.product-card').forEach(el => el.style.display = 'none');

  items.forEach(b => {
    // Jika PHP card sudah ada, tampilkan saja
    const existing = grid.querySelector(`.product-card[data-id="${b.id}"]`);
    if (existing) { existing.style.display = ''; return; }

    // Buat card baru dari API
    const icon = icons[b.kat_nama] || '📦';
    const div  = document.createElement('div');
    div.className    = 'product-card api-card';
    div.dataset.id   = b.id;
    div.dataset.nama = b.nama;
    div.dataset.harga= b.harga_jual;
    div.dataset.stok = b.stok;
    div.dataset.kat  = b.kategori_id;
    div.dataset.kode = b.kode;
    div.onclick = function() { addToCart(this); };
    div.innerHTML = `
      <div class="p-icon">${icon}</div>
      <div class="p-name">${b.nama}</div>
      <div class="p-price">${formatRp(parseFloat(b.harga_jual))}</div>
      <div class="p-stok">Stok: ${b.stok}</div>
    `;
    grid.appendChild(div);
  });
}

// ══════════════════════════════════════
//  KERANJANG
// ══════════════════════════════════════
function addToCart(el) {
  const id    = parseInt(el.dataset.id);
  const nama  = el.dataset.nama;
  const harga = parseFloat(el.dataset.harga);
  const stok  = parseInt(el.dataset.stok);
  const exist = cart.find(x => x.id === id);

  if (exist) {
    if (exist.qty >= stok) { alert('Stok tidak mencukupi!'); return; }
    exist.qty++;
  } else {
    cart.push({ id, nama, harga, stok, qty: 1 });
  }
  renderCart();
}

function renderCart() {
  const container = document.getElementById('cartItems');
  const empty     = document.getElementById('cartEmpty');
  const count     = document.getElementById('cartCount');

  container.querySelectorAll('.cart-item').forEach(e => e.remove());

  if (cart.length === 0) {
    empty.style.display = 'block';
    count.textContent   = 0;
    document.getElementById('subtotal').textContent   = 'Rp 0';
    document.getElementById('grandTotal').textContent = 'Rp 0';
    return;
  }

  empty.style.display = 'none';
  let total = 0;

  cart.forEach(item => {
    total += item.harga * item.qty;
    const div = document.createElement('div');
    div.className = 'cart-item';
    div.innerHTML = `
      <div style="flex:1">
        <div class="ci-name">${item.nama}</div>
        <div class="ci-price">${formatRp(item.harga)} / pcs</div>
      </div>
      <div class="ci-qty">
        <button class="qty-btn" onclick="changeQty(${item.id},-1)">−</button>
        <span>${item.qty}</span>
        <button class="qty-btn" onclick="changeQty(${item.id},1)">+</button>
      </div>
      <div style="min-width:80px;text-align:right;font-weight:700;font-size:13px">${formatRp(item.harga * item.qty)}</div>
      <button class="ci-del" onclick="removeItem(${item.id})">🗑️</button>
    `;
    container.insertBefore(div, empty);
  });

  count.textContent = cart.reduce((s,i) => s + i.qty, 0);
  document.getElementById('subtotal').textContent   = formatRp(total);
  document.getElementById('grandTotal').textContent = formatRp(total);
}

function changeQty(id, delta) {
  const item = cart.find(x => x.id === id);
  if (!item) return;
  item.qty += delta;
  if (item.qty <= 0)    cart = cart.filter(x => x.id !== id);
  if (item.qty > item.stok) { item.qty = item.stok; alert('Stok tidak mencukupi!'); }
  renderCart();
}

function removeItem(id) { cart = cart.filter(x => x.id !== id); renderCart(); }
function clearCart()    { cart = []; renderCart(); }

// ══════════════════════════════════════
//  PEMBAYARAN
// ══════════════════════════════════════
function getTotal() { return cart.reduce((s,i) => s + i.harga * i.qty, 0); }

function openBayar() {
  if (cart.length === 0) { alert('Keranjang masih kosong!'); return; }
  document.getElementById('modalTotal').textContent = formatRp(getTotal());
  document.getElementById('uangDiterima').value     = '';
  document.getElementById('kembalian').textContent  = 'Rp 0';
  document.getElementById('modalBayar').classList.add('open');
}
function closeBayar() { document.getElementById('modalBayar').classList.remove('open'); }

function setNominal(n) {
  document.getElementById('uangDiterima').value = n;
  hitungKembalian();
}

function hitungKembalian() {
  const metode  = document.getElementById('metode').value;
  const isTunai = metode === 'tunai';
  document.getElementById('tunaiSection').style.display = isTunai ? '' : 'none';
  if (isTunai) {
    const bayar     = parseFloat(document.getElementById('uangDiterima').value) || 0;
    const kembalian = bayar - getTotal();
    document.getElementById('kembalian').textContent  = kembalian >= 0 ? formatRp(kembalian) : '⚠️ Kurang';
    document.getElementById('btnProses').disabled     = kembalian < 0;
  } else {
    document.getElementById('btnProses').disabled = false;
  }
}

async function prosesTransaksi() {
  const metode = document.getElementById('metode').value;
  const total  = getTotal();
  let   bayar  = metode === 'tunai' ? parseFloat(document.getElementById('uangDiterima').value) || 0 : total;

  if (metode === 'tunai' && bayar < total) { alert('Uang tidak mencukupi!'); return; }

  document.getElementById('btnProses').disabled    = true;
  document.getElementById('btnProses').textContent = 'Memproses...';

  try {
    const res = await fetch('<?= BASE_URL ?>kasir/api_transaksi.php', {
      method: 'POST',
      headers: {'Content-Type':'application/json'},
      body: JSON.stringify({
        kasir_id: KASIR_ID,
        items: cart.map(i => ({ id: i.id, nama: i.nama, harga: i.harga, qty: i.qty, subtotal: i.harga * i.qty })),
        total, bayar, kembalian: bayar - total, metode
      })
    });
    const data = await res.json();
    if (data.success) {
      closeBayar();
      tampilStruk(data, bayar - total);
      cart = [];
      renderCart();
    } else {
      alert('Gagal: ' + (data.error || 'Terjadi kesalahan'));
    }
  } catch(e) {
    alert('Koneksi error: ' + e.message);
  } finally {
    document.getElementById('btnProses').disabled    = false;
    document.getElementById('btnProses').textContent = '✅ Proses';
  }
}

function tampilStruk(data, kembalian) {
  const now  = new Date().toLocaleString('id-ID');
  const rows = data.items.map(i =>
    `<tr><td>${i.nama}</td></tr>
     <tr><td>${i.qty} x ${formatRp(i.harga)}</td><td style="text-align:right">${formatRp(i.subtotal)}</td></tr>`
  ).join('');
  document.getElementById('strukContent').innerHTML = `
    <div class="s-center s-bold" style="font-size:15px">${NAMA_TOKO}</div>
    <div class="s-center" style="font-size:11px">${ALAMAT}</div>
    <div class="s-center" style="font-size:11px">${TELEPON}</div>
    <hr>
    <div>No: ${data.no_transaksi}</div>
    <div>Waktu: ${now}</div>
    <hr>
    <table style="width:100%;font-size:12px">${rows}</table>
    <hr>
    <table style="width:100%;font-size:13px">
      <tr><td>TOTAL</td><td style="text-align:right"><strong>${formatRp(data.total)}</strong></td></tr>
      <tr><td>BAYAR</td><td style="text-align:right">${formatRp(data.bayar)}</td></tr>
      <tr><td>KEMBALIAN</td><td style="text-align:right">${formatRp(kembalian >= 0 ? kembalian : 0)}</td></tr>
    </table>
    <hr>
    <div class="s-center">Terima kasih sudah berbelanja!</div>
  `;
  document.getElementById('modalStruk').classList.add('open');
}

function closeStruk() { document.getElementById('modalStruk').classList.remove('open'); }
// ── TAB SWITCHING (mobile) ──
// ── TAB SWITCHING (mobile) ──
function switchTab(tab) {
  const produk    = document.getElementById('panelProduk');
  const keranjang = document.getElementById('panelKeranjang');
  const tabP      = document.getElementById('tabProduk');
  const tabK      = document.getElementById('tabKeranjang');
  if (!produk || !keranjang) return;

  if (tab === 'produk') {
    produk.classList.add('tab-active');
    keranjang.classList.remove('tab-active');
    if (tabP) tabP.classList.add('active');
    if (tabK) tabK.classList.remove('active');
  } else {
    keranjang.classList.add('tab-active');
    produk.classList.remove('tab-active');
    if (tabK) tabK.classList.add('active');
    if (tabP) tabP.classList.remove('active');
  }
}

// Override renderCart untuk update badge & tombol bayar cepat
const _origRenderCart = renderCart;
renderCart = function() {
  _origRenderCart();
  const qty   = cart.reduce((s,i) => s + i.qty, 0);
  const total = cart.reduce((s,i) => s + i.harga * i.qty, 0);

  // Badge tab keranjang
  const badge = document.getElementById('cartBadge');
  if (badge) { badge.textContent = qty; badge.style.display = qty > 0 ? 'inline' : 'none'; }

  // Tombol bayar cepat di tab produk (mobile)
  const qb = document.getElementById('quickBayar');
  const qt = document.getElementById('quickTotal');
  if (qb && window.innerWidth <= 768) {
    qb.style.display = qty > 0 ? 'block' : 'none';
    if (qt) qt.textContent = formatRp(total);
  }
};

function initTabBar() {
  const tabBar = document.querySelector('.pos-tab-bar');
  const produk    = document.getElementById('panelProduk');
  const keranjang = document.getElementById('panelKeranjang');
  const qb        = document.getElementById('quickBayar');

  if (window.innerWidth <= 768) {
    // Mobile: tampilkan tab bar, mode tab
    if (tabBar) tabBar.style.display = 'flex';
    // Default: panel produk aktif, keranjang tersembunyi
    if (produk)    { produk.style.display = ''; produk.classList.add('tab-active'); }
    if (keranjang) { keranjang.classList.remove('tab-active'); }
    // Quick bayar update
    const qty = cart.reduce((s,i) => s + i.qty, 0);
    if (qb) qb.style.display = qty > 0 ? 'block' : 'none';
  } else {
    // Desktop: sembunyikan tab bar, tampilkan keduanya
    if (tabBar) tabBar.style.display = 'none';
    if (produk)    { produk.classList.add('tab-active'); produk.style.display = ''; }
    if (keranjang) { keranjang.classList.add('tab-active'); }
    if (qb) qb.style.display = 'none';
  }
}

window.addEventListener('resize', initTabBar);
document.addEventListener('DOMContentLoaded', initTabBar);

</script>
</body>
</html>
