<?php
// admin/barang.php — CRUD Barang + Scan Barcode
require_once '../includes/config.php';
require_once '../includes/auth.php';
requireAdmin();

$msg   = htmlspecialchars($_GET['msg'] ?? '');
$error = '';
$editBarangTemp = null;

if (isset($_GET['hapus'])) {
    $pdo->prepare("UPDATE barang SET aktif=0 WHERE id=?")->execute([(int)$_GET['hapus']]);
    $msg = 'Barang berhasil dihapus.';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id          = (int)($_POST['id'] ?? 0);
    $kode        = trim($_POST['kode']         ?? '');
    $nama        = trim($_POST['nama']         ?? '');
    $kategori_id = (int)($_POST['kategori_id'] ?? 0);
    $harga_beli  = (float)($_POST['harga_beli'] ?? 0);
    $harga_jual  = (float)($_POST['harga_jual'] ?? 0);
    $stok        = (int)($_POST['stok']         ?? 0);
    $satuan      = trim($_POST['satuan']        ?? 'pcs');

    if (!$kode || !$nama || !$kategori_id) {
        $error = 'Kode, nama, dan kategori wajib diisi.';
        // Simpan data sementara agar modal tidak kosong
        $editBarangTemp = compact('id','kode','nama','kategori_id','harga_beli','harga_jual','stok','satuan');
    } else {
        if ($id > 0) {
            $pdo->prepare("UPDATE barang SET kode=?,nama=?,kategori_id=?,harga_beli=?,harga_jual=?,stok=?,satuan=? WHERE id=?")
                ->execute([$kode, $nama, $kategori_id, $harga_beli, $harga_jual, $stok, $satuan, $id]);
            // PRG: redirect setelah simpan agar tidak double submit & modal tidak muncul lagi
            $sort = $_POST['sort'] ?? 'nama';
            $dir  = $_POST['dir']  ?? 'asc';
            header("Location: barang.php?msg=" . urlencode('Barang berhasil diperbarui.') . "&sort=$sort&dir=$dir");
            exit;
        } else {
            $pdo->prepare("INSERT INTO barang(kode,nama,kategori_id,harga_beli,harga_jual,stok,satuan) VALUES(?,?,?,?,?,?,?)")
                ->execute([$kode, $nama, $kategori_id, $harga_beli, $harga_jual, $stok, $satuan]);
            $sort = $_POST['sort'] ?? 'nama';
            $dir  = $_POST['dir']  ?? 'asc';
            header("Location: barang.php?msg=" . urlencode('Barang berhasil ditambahkan.') . "&sort=$sort&dir=$dir");
            exit;
        }
    }
}

$search       = trim($_GET['q'] ?? '');
$kategoriList = $pdo->query("SELECT * FROM kategori ORDER BY nama")->fetchAll();

$sql    = "SELECT b.*, COALESCE(k.nama,'Tanpa Kategori') AS kat_nama FROM barang b LEFT JOIN kategori k ON b.kategori_id=k.id WHERE b.aktif=1";
$params = [];
if ($search) {
    $sql    .= " AND (b.nama LIKE ? OR b.kode LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}
// ── SORTING ──
$sortAllow  = ["kode"=>"b.kode","nama"=>"b.nama","kategori"=>"k.nama","stok"=>"b.stok","harga_jual"=>"b.harga_jual"];
$sortBy     = isset($_GET["sort"]) && array_key_exists($_GET["sort"], $sortAllow) ? $_GET["sort"] : "nama";
$sortDir    = ($_GET["dir"] ?? "asc") === "desc" ? "DESC" : "ASC";
$sortDirNext = $sortDir === "ASC" ? "desc" : "asc";
$sql .= " ORDER BY " . $sortAllow[$sortBy] . " " . $sortDir . " LIMIT 100";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$barangList = $stmt->fetchAll();

// Jika POST error, pakai data yang sudah diisi user
$editBarang = $editBarangTemp ?? null;
// Jika GET edit, ambil dari database
if (!$editBarang && isset($_GET['edit'])) {
    $s = $pdo->prepare("SELECT * FROM barang WHERE id=? AND aktif=1");
    $s->execute([(int)$_GET['edit']]);
    $editBarang = $s->fetch() ?: null;
}
?>
<!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>Manajemen Barang — <?= 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>
    .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: inline-flex; align-items: center; gap: 6px;
      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); }
  </style>
</head>
<body>
<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">📦 Manajemen Barang</div>
      <button class="scan-btn" onclick="openScanner()">📷 Scan Cari Barang</button>
      <button class="topbar-btn" style="margin-left:8px" onclick="openModal()">+ Tambah Barang</button>
    </div>

    <div class="page-body">
      <?php if ($msg):   ?><div class="alert alert-success"><?= htmlspecialchars($msg) ?></div><?php endif; ?>
      <?php if ($error): ?><div class="alert alert-error"><?= htmlspecialchars($error) ?></div><?php endif; ?>

      <!-- Search AJAX -->
      <div class="card" style="margin-bottom:20px">
        <div class="card-body" style="padding:14px 20px">
          <div class="barang-search-row" style="display:flex;gap:10px;align-items:center;flex-wrap:wrap">
            <input type="text" id="searchInput" class="form-control"
                   style="max-width:320px" placeholder="Cari nama / kode barang..."
                   oninput="cariBarang()" autocomplete="off"
                   value="<?= htmlspecialchars($search) ?>">
            <select id="filterKatAdmin" class="form-control" style="width:auto" onchange="cariBarang()">
              <option value="">Semua Kategori</option>
              <?php foreach ($kategoriList as $k): ?>
              <option value="<?= $k['id'] ?>"><?= htmlspecialchars($k['nama']) ?></option>
              <?php endforeach; ?>
            </select>
            <button type="button" class="btn btn-ghost" onclick="resetCari()">Reset</button>
          </div>
          <div id="searchInfoAdmin" style="display:none;font-size:12px;color:var(--muted);margin-top:8px;font-weight:500"></div>
        </div>
      </div>

      <!-- Tabel -->
      <div class="card">
        <div class="card-header">
          <h3>Daftar Barang (<span id="jumlahBarang"><?= count($barangList) ?></span>)</h3>
        </div>
        <div class="table-wrap">
          <table id="tabelBarang">
            <thead>
              <?php
              // Helper fungsi URL sort
              function sortUrl($kolom, $sortBy, $sortDirNext, $search) {
                $dir = ($sortBy === $kolom) ? $sortDirNext : 'asc';
                return '?sort=' . $kolom . '&dir=' . $dir . ($search ? '&q=' . urlencode($search) : '');
              }
              function sortIcon($kolom, $sortBy, $sortDir) {
                if ($sortBy !== $kolom) return '<span style="opacity:.3;margin-left:4px">⇅</span>';
                return $sortDir === 'ASC'
                  ? '<span style="color:var(--primary);margin-left:4px">↑</span>'
                  : '<span style="color:var(--primary);margin-left:4px">↓</span>';
              }
              $thStyle = 'cursor:pointer;user-select:none;white-space:nowrap';
              $thActiveStyle = $thStyle . ';color:var(--primary)';
              ?>
              <tr>
                <th style="<?= $sortBy==='kode' ? $thActiveStyle : $thStyle ?>">
                  <a href="<?= sortUrl('kode',$sortBy,$sortDirNext,$search) ?>" style="color:inherit;text-decoration:none">
                    Kode <?= sortIcon('kode',$sortBy,$sortDir) ?>
                  </a>
                </th>
                <th style="<?= $sortBy==='nama' ? $thActiveStyle : $thStyle ?>">
                  <a href="<?= sortUrl('nama',$sortBy,$sortDirNext,$search) ?>" style="color:inherit;text-decoration:none">
                    Nama <?= sortIcon('nama',$sortBy,$sortDir) ?>
                  </a>
                </th>
                <th style="<?= $sortBy==='kategori' ? $thActiveStyle : $thStyle ?>">
                  <a href="<?= sortUrl('kategori',$sortBy,$sortDirNext,$search) ?>" style="color:inherit;text-decoration:none">
                    Kategori <?= sortIcon('kategori',$sortBy,$sortDir) ?>
                  </a>
                </th>
                <th class="hide-mobile">Harga Beli</th>
                <th style="<?= $sortBy==='harga_jual' ? $thActiveStyle : $thStyle ?>">
                  <a href="<?= sortUrl('harga_jual',$sortBy,$sortDirNext,$search) ?>" style="color:inherit;text-decoration:none">
                    Harga Jual <?= sortIcon('harga_jual',$sortBy,$sortDir) ?>
                  </a>
                </th>
                <th style="<?= $sortBy==='stok' ? $thActiveStyle : $thStyle ?>">
                  <a href="<?= sortUrl('stok',$sortBy,$sortDirNext,$search) ?>" style="color:inherit;text-decoration:none">
                    Stok <?= sortIcon('stok',$sortBy,$sortDir) ?>
                  </a>
                </th>
                <th class="hide-mobile">Satuan</th>
                <th>Aksi</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($barangList as $b): ?>
              <tr data-id="<?= $b['id'] ?>" data-kat="<?= $b['kategori_id'] ?>">
                <td><code><?= htmlspecialchars($b['kode']) ?></code></td>
                <td><strong><?= htmlspecialchars($b['nama']) ?></strong></td>
                <td><?= htmlspecialchars($b['kat_nama']) ?></td>
                <td class="hide-mobile"><?= formatRp((float)$b['harga_beli']) ?></td>
                <td><?= formatRp((float)$b['harga_jual']) ?></td>
                <td><span class="badge <?= $b['stok'] <= 5 ? 'badge-red' : ($b['stok'] <= 20 ? 'badge-amber' : 'badge-green') ?>"><?= $b['stok'] ?></span></td>
                <td class="hide-mobile"><?= htmlspecialchars($b['satuan']) ?></td>
                <td>
                  <div style="display:flex;gap:6px">
                    <a href="?edit=<?= $b['id'] ?>&amp;sort=<?= $sortBy ?>&amp;dir=<?= strtolower($sortDir) ?>" class="btn btn-primary btn-sm">Edit</a>
                    <a href="?hapus=<?= $b['id'] ?>" class="btn btn-red btn-sm" onclick="return confirm('Hapus barang ini?')">Hapus</a>
                  </div>
                </td>
              </tr>
              <?php endforeach; ?>
              <?php if (empty($barangList)): ?>
              <tr><td colspan="8" style="text-align:center;color:var(--muted);padding:30px">Tidak ada barang</td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </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">📷 Arahkan kamera ke barcode barang...</div>
  <div id="scanner-result"></div>
  <button class="scanner-close" onclick="closeScanner()">✕ Tutup Scanner</button>
</div>

<!-- Modal Form Barang -->
<div class="modal-overlay <?= ($editBarang || ($error && $_SERVER['REQUEST_METHOD']==='POST')) ? 'open':'' ?>" id="modal">
  <div class="modal">
    <div class="modal-header">
      <h4 id="modal-title"><?= $editBarang ? 'Edit Barang' : 'Tambah Barang Baru' ?></h4>
      <button class="modal-close" onclick="closeModal()">×</button>
    </div>
    <form method="POST">
      <div class="modal-body">
        <input type="hidden" name="id" value="<?= $editBarang['id'] ?? '' ?>">
        <input type="hidden" name="sort" value="<?= htmlspecialchars($sortBy) ?>">
        <input type="hidden" name="dir" value="<?= strtolower($sortDir) ?>">
        <div class="form-row">
          <div class="form-group">
            <label>Kode / Barcode *</label>
            <div style="display:flex;gap:8px">
              <input type="text" name="kode" id="kodeInput" class="form-control" required
                     value="<?= htmlspecialchars($editBarang['kode'] ?? '') ?>"
                     placeholder="Scan atau ketik kode">
              <button type="button" class="scan-btn" style="padding:10px 12px;border-radius:10px"
                      onclick="openScannerForForm()" title="Scan barcode ke form">📷</button>
            </div>
          </div>
          <div class="form-group">
            <label>Satuan</label>
            <input type="text" name="satuan" class="form-control"
                   value="<?= htmlspecialchars($editBarang['satuan'] ?? 'pcs') ?>">
          </div>
        </div>
        <div class="form-group">
          <label>Nama Barang *</label>
          <input type="text" name="nama" class="form-control" required
                 value="<?= htmlspecialchars($editBarang['nama'] ?? '') ?>">
        </div>
        <div class="form-group">
          <label>Kategori *</label>
          <select name="kategori_id" class="form-control" required>
            <option value="">-- Pilih Kategori --</option>
            <?php foreach ($kategoriList as $kat): ?>
            <option value="<?= $kat['id'] ?>" <?= ($editBarang['kategori_id'] ?? '') == $kat['id'] ? 'selected':'' ?>>
              <?= htmlspecialchars($kat['nama']) ?>
            </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="form-row">
          <div class="form-group">
            <label>Harga Beli (Rp)</label>
            <input type="number" name="harga_beli" class="form-control" min="0"
                   value="<?= $editBarang['harga_beli'] ?? 0 ?>">
          </div>
          <div class="form-group">
            <label>Harga Jual (Rp) *</label>
            <input type="number" name="harga_jual" class="form-control" min="0" required
                   value="<?= $editBarang['harga_jual'] ?? 0 ?>">
          </div>
        </div>
        <div class="form-group">
          <label>Stok</label>
          <input type="number" name="stok" class="form-control" min="0"
                 value="<?= $editBarang['stok'] ?? 0 ?>">
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-ghost" onclick="closeModal()">Batal</button>
        <button type="submit" class="btn btn-primary">Simpan</button>
      </div>
    </form>
  </div>
</div>

<script src="https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js"></script>
<script src="<?= BASE_URL ?>js/app.js"></script>
<script>
let html5QrCode  = null;
let scannerOpen  = false;
let scanMode     = 'search';   // 'search' atau 'form'
let lastScanned  = '';
let lastScannedTime = 0;

function openScanner() {
  scanMode = 'search';
  startScanner('📷 Scan barcode untuk mencari barang...');
}

function openScannerForForm() {
  scanMode = 'form';
  startScanner('📷 Scan barcode untuk mengisi kode barang...');
}

function startScanner(statusText) {
  document.getElementById('scanner-modal-overlay').classList.add('open');
  document.getElementById('scanner-result').style.display = 'none';
  document.getElementById('scanner-status').textContent = statusText;

  html5QrCode = new Html5Qrcode("reader");
  html5QrCode.start(
    { facingMode: "environment" },
    { fps: 10, qrbox: { width: 260, height: 160 } },
    onScanSuccess,
    () => {}
  ).catch(err => {
    document.getElementById('scanner-status').textContent = '⚠️ Kamera tidak bisa diakses: ' + 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) {
  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';

  if (scanMode === 'form') {
    // Isi input kode di form
    document.getElementById('kodeInput').value = decodedText;
    resultEl.className = 'found';
    resultEl.innerHTML = `✅ Kode diisi: <strong>${decodedText}</strong>`;
    setTimeout(() => {
      closeScanner();
      // Buka modal form jika belum terbuka
      document.getElementById('modal').classList.add('open');
    }, 1000);
  } else {
    // Mode cari — AJAX langsung, tidak perlu redirect
    resultEl.className = 'found';
    resultEl.innerHTML = `🔍 Mencari: <strong>${decodedText}</strong>`;
    document.getElementById('scanner-status').textContent = '🔍 Mencari di database...';

    try {
      const url  = `<?= BASE_URL ?>admin/api_cari_barang_admin.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());

      closeScanner();

      if (barang) {
        // Isi kolom cari dengan kode hasil scan
        document.getElementById('searchInput').value = decodedText;
        doSearchAdmin();
        document.getElementById('searchInfoAdmin').textContent =
          `✅ Ditemukan: ${barang.nama}`;
        document.getElementById('searchInfoAdmin').style.display = 'block';
      } else {
        // Tidak ditemukan — tetap cari dengan teks
        document.getElementById('searchInput').value = decodedText;
        doSearchAdmin();
      }
    } catch(e) {
      closeScanner();
      document.getElementById('searchInput').value = decodedText;
      doSearchAdmin();
    }
  }
}

<?php if ($editBarang): ?>
document.addEventListener('DOMContentLoaded', () => openModal());
<?php endif; ?>
</script>

<script>
const BASE_URL = "<?= BASE_URL ?>";
let timerAdmin = null;

function cariBarang() {
  clearTimeout(timerAdmin);
  timerAdmin = setTimeout(doSearchAdmin, 350);
}

async function doSearchAdmin() {
  const q   = document.getElementById('searchInput').value.trim();
  const kat = document.getElementById('filterKatAdmin').value;
  const info = document.getElementById('searchInfoAdmin');

  // Kosong & tanpa kat → tampilkan semua PHP row
  if (!q && !kat) {
    document.querySelectorAll('#tabelBarang tbody tr.api-row').forEach(el => el.remove());
    document.querySelectorAll('#tabelBarang tbody tr.php-row').forEach(el => el.style.display = '');
    document.getElementById('jumlahBarang').textContent =
      document.querySelectorAll('#tabelBarang tbody tr:not(.empty-row)').length;
    info.style.display = 'none';
    return;
  }

  // Hanya kat tanpa teks → filter DOM
  if (!q && kat) {
    document.querySelectorAll('#tabelBarang tbody tr.api-row').forEach(el => el.remove());
    let n = 0;
    document.querySelectorAll('#tabelBarang tbody tr.php-row').forEach(el => {
      const show = el.dataset.kat === kat;
      el.style.display = show ? '' : 'none';
      if (show) n++;
    });
    document.getElementById('jumlahBarang').textContent = n;
    info.style.display = 'none';
    return;
  }

  // Ada teks → AJAX
  info.style.display = 'block';
  info.textContent = '🔍 Mencari...';

  try {
    const url  = `${BASE_URL}admin/api_cari_barang_admin.php?q=${encodeURIComponent(q)}&kat=${kat}`;
    const res  = await fetch(url);
    const data = await res.json();

    renderRowsFromAPI(data);
    document.getElementById('jumlahBarang').textContent = data.length;
    info.textContent = data.length > 0
      ? `Menampilkan ${data.length} hasil untuk "${q}"`
      : `❌ Tidak ada barang untuk "${q}"`;
  } catch(e) {
    // Fallback DOM filter
    let n = 0;
    document.querySelectorAll('#tabelBarang tbody tr.php-row').forEach(el => {
      const nama = (el.dataset.nama || '').toLowerCase();
      const kode = (el.dataset.kode || '').toLowerCase();
      const show = nama.includes(q.toLowerCase()) || kode.includes(q.toLowerCase());
      el.style.display = show ? '' : 'none';
      if (show) n++;
    });
    document.getElementById('jumlahBarang').textContent = n;
    info.style.display = 'none';
  }
}

function resetCari() {
  document.getElementById('searchInput').value = '';
  document.getElementById('filterKatAdmin').value = '';
  document.querySelectorAll('#tabelBarang tbody tr.api-row').forEach(el => el.remove());
  document.querySelectorAll('#tabelBarang tbody tr.php-row').forEach(el => el.style.display = '');
  const total = document.querySelectorAll('#tabelBarang tbody tr.php-row').length;
  document.getElementById('jumlahBarang').textContent = total;
  document.getElementById('searchInfoAdmin').style.display = 'none';
}

function renderRowsFromAPI(items) {
  const tbody = document.querySelector('#tabelBarang tbody');

  // Hapus api-row lama, sembunyikan php-row
  tbody.querySelectorAll('.api-row').forEach(el => el.remove());
  tbody.querySelectorAll('.php-row').forEach(el => el.style.display = 'none');

  if (items.length === 0) return;

  items.forEach(b => {
    // Cek sudah ada sebagai php-row
    const existing = tbody.querySelector(`.php-row[data-id="${b.id}"]`);
    if (existing) { existing.style.display = ''; return; }

    // Buat row baru
    const badgeClass = b.stok == 0 ? 'badge-red' : (b.stok <= 5 ? 'badge-amber' : 'badge-green');
    const tr = document.createElement('tr');
    tr.className = 'api-row';
    tr.dataset.id  = b.id;
    tr.dataset.nama = b.nama.toLowerCase();
    tr.dataset.kode = b.kode.toLowerCase();
    tr.dataset.kat  = b.kategori_id;
    tr.innerHTML = `
      <td><code style="font-size:11px">${escHtml(b.kode)}</code></td>
      <td><strong>${escHtml(b.nama)}</strong></td>
      <td>${escHtml(b.kat_nama)}</td>
      <td class="hide-mobile">${formatRp(parseFloat(b.harga_beli))}</td>
      <td>${formatRp(parseFloat(b.harga_jual))}</td>
      <td><span class="badge ${badgeClass}">${b.stok}</span></td>
      <td class="hide-mobile">${escHtml(b.satuan)}</td>
      <td>
        <div style="display:flex;gap:6px">
          <a href="barang.php?edit=${b.id}" class="btn btn-primary btn-sm">Edit</a>
          <a href="barang.php?hapus=${b.id}" class="btn btn-red btn-sm"
             onclick="return confirm('Hapus barang ini?')">Hapus</a>
        </div>
      </td>`;
    tbody.appendChild(tr);
  });
}

function escHtml(str) {
  return String(str)
    .replace(/&/g,'&amp;').replace(/</g,'&lt;')
    .replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}

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

// Init: tandai semua PHP row agar bisa dibedakan dari API row
document.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll('#tabelBarang tbody tr').forEach(tr => {
    tr.classList.add('php-row');
    // Ambil data dari td untuk filter
    const kode = tr.querySelector('td:first-child code');
    const nama = tr.querySelector('td:nth-child(2) strong');
    const kat  = tr.querySelector('td:nth-child(3)');
    if (kode) tr.dataset.kode = kode.textContent.toLowerCase();
    if (nama) tr.dataset.nama = nama.textContent.toLowerCase();
  });

  // Jika ada nilai search awal dari PHP, jalankan search
  const q = document.getElementById('searchInput').value.trim();
  if (q) doSearchAdmin();
});
</script>

</body>
</html>
