<?php
// admin/stok.php — Manajemen Stok Massal
require_once '../includes/config.php';
require_once '../includes/auth.php';
requireAdmin();

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

// ── SIMPAN BULK UPDATE STOK ──
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_stok'])) {
    $updates  = $_POST['stok']   ?? [];
    $tipe     = $_POST['tipe']   ?? [];   // 'set' atau 'tambah'
    $berhasil = 0;

    $stmt = $pdo->prepare("UPDATE barang SET stok = ? WHERE id = ? AND aktif = 1");
    $stmtTambah = $pdo->prepare("UPDATE barang SET stok = stok + ? WHERE id = ? AND aktif = 1");

    foreach ($updates as $id => $nilai) {
        $id    = (int)$id;
        $nilai = (int)$nilai;
        $mode  = $tipe[$id] ?? 'tambah';

        if ($nilai === 0) continue; // skip yang tidak diubah

        if ($mode === 'set') {
            $stmt->execute([$nilai, $id]);
        } else {
            $stmtTambah->execute([$nilai, $id]);
        }
        $berhasil++;
    }

    // Redirect agar tidak resubmit form saat refresh
    $qs = http_build_query(array_filter([
        'msg'    => "Stok diperbarui untuk $berhasil barang",
        'filter' => $_POST['filter'] ?? 'semua',
        'q'      => $_POST['q']      ?? '',
        'kat'    => $_POST['kat']    ?? '',
        'page'   => $_POST['page']   ?? 1,
    ]));
    header("Location: stok.php?$qs");
    exit;
}

// ── FILTER & PAGINATION ──
$filter   = $_GET['filter'] ?? 'semua';
if ($filter === 'semua') $filter = 'semua'; // normalize
$search   = trim($_GET['q'] ?? '');
$kat_id   = (int)($_GET['kat'] ?? 0);
$perPage  = 100;
$page     = max(1, (int)($_GET['page'] ?? 1));
$offset   = ($page - 1) * $perPage;

// Bangun kondisi WHERE
$where  = "b.aktif = 1";
$params = [];

if ($search) {
    $where   .= " AND (b.nama LIKE ? OR b.kode LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}
if ($kat_id) {
    $where   .= " AND b.kategori_id = ?";
    $params[] = $kat_id;
}
if ($filter === 'habis') {
    $where .= " AND b.stok = 0";
} elseif ($filter === 'rendah') {
    $where .= " AND b.stok > 0 AND b.stok <= 50";
} elseif ($filter === 'aman') {
    $where .= " AND b.stok > 50";
}

// Total untuk pagination
$stmtCount = $pdo->prepare("SELECT COUNT(*) FROM barang b WHERE $where");
$stmtCount->execute($params);
$totalItem = (int)$stmtCount->fetchColumn();
$totalPage = max(1, (int)ceil($totalItem / $perPage));
$page      = min($page, $totalPage); // jangan melebihi total halaman

// Data dengan LIMIT
$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 $where
         ORDER BY b.stok ASC, b.nama ASC
         LIMIT $perPage OFFSET $offset";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$barangList = $stmt->fetchAll();

// Helper URL untuk pagination (pertahankan semua filter)
function pageUrl($p, $filter, $search, $kat_id) {
    $q = http_build_query(array_filter([
        'filter' => $filter !== 'semua' ? $filter : null,
        'q'      => $search ?: null,
        'kat'    => $kat_id ?: null,
        'page'   => $p,
    ]));
    return 'stok.php' . ($q ? "?$q" : '');
}

// Statistik stok — pakai query langsung tanpa JOIN agar akurat
$statHabis  = (int)$pdo->query("SELECT COUNT(*) FROM barang WHERE aktif=1 AND stok=0")->fetchColumn();
$statRendah = (int)$pdo->query("SELECT COUNT(*) FROM barang WHERE aktif=1 AND stok>0 AND stok<=50")->fetchColumn();
$statAman   = (int)$pdo->query("SELECT COUNT(*) FROM barang WHERE aktif=1 AND stok>50")->fetchColumn();
$statTotal  = (int)$pdo->query("SELECT COUNT(*) FROM barang WHERE aktif=1")->fetchColumn();

// Kategori pakai LEFT JOIN juga
$kategoriList = $pdo->query("
    SELECT DISTINCT k.id, k.nama
    FROM kategori k
    INNER JOIN barang b ON b.kategori_id = k.id
    WHERE b.aktif = 1
    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>Manajemen Stok — <?= 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>
    /* ── Stok Input ── */
    .stok-input {
      width: 80px; text-align: center; padding: 7px 8px;
      border: 1.5px solid var(--border); border-radius: 8px;
      font-size: 14px; font-weight: 600; font-family: inherit;
      outline: none; transition: border-color .2s;
    }
    .stok-input:focus { border-color: var(--primary); background: rgba(212,175,55,.05); }
    .stok-input.changed { border-color: var(--primary) !important; background: rgba(212,175,55,.08) !important; }

    .tipe-select {
      padding: 7px 8px; border: 1.5px solid var(--border);
      border-radius: 8px; font-size: 12px; font-family: inherit;
      outline: none; background: var(--bg); cursor: pointer;
    }
    .tipe-select:focus { border-color: var(--primary); }

    /* ── Filter chips ── */
    .filter-chips { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 16px; }
    .chip {
      padding: 7px 16px; border-radius: 20px; font-size: 13px;
      font-weight: 600; border: none; cursor: pointer;
      font-family: inherit; text-decoration: none;
      display: inline-flex; align-items: center; gap: 6px;
      transition: all .2s;
    }
    .chip-all    { background: var(--white); color: var(--muted); border: 1px solid var(--border); }
    .chip-habis  { background: rgba(231,76,60,.12); color: #e87070; border: 1px solid rgba(231,76,60,.25); }
    .chip-rendah { background: rgba(212,175,55,.12); color: #c9a227; border: 1px solid rgba(212,175,55,.25); }
    .chip-aman   { background: rgba(46,204,113,.12); color: #4bcf80; border: 1px solid rgba(46,204,113,.25); }
    .chip.active { box-shadow: 0 0 0 2px currentColor; filter: brightness(1.15); }

    /* ── Sticky bar ── */
    .sticky-bar {
      position: sticky; bottom: 0; left: 0; right: 0;
      background: var(--white); border-top: 2px solid var(--primary);
      padding: 14px 24px; display: flex; align-items: center;
      justify-content: space-between; gap: 16px; z-index: 50;
      box-shadow: 0 -4px 20px rgba(0,0,0,.08);
    }
    .changed-count {
      font-size: 14px; font-weight: 600; color: var(--muted);
    }

    /* ── Scan ── */
    .scan-btn {
      background: rgba(212,175,55,.15); color: var(--primary);
      border: 1px solid rgba(212,175,55,.35);
      border-radius: 10px; padding: 9px 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; }
    #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;
    }

    /* ── Row highlight ── */
    tr.row-highlight td { background: rgba(212,175,55,.08) !important; }
    tr.row-scanned  td { background: #ecfdf5 !important; animation: flashGreen .5s ease; }
    /* Pagination tetap terlihat saat scroll */
    .pagination-wrap { position: sticky; bottom: var(--nav-h, 68px); background: var(--white); z-index: 10; border-top: 1px solid var(--border); }

    @keyframes flashGreen {
      0%   { background: #6ee7b7 !important; }
      100% { background: #ecfdf5 !important; }
    }

    /* ── Import CSV ── */
    .import-area {
      border: 2px dashed var(--border); border-radius: 14px;
      padding: 24px; text-align: center; cursor: pointer;
      transition: border-color .2s;
    }
    .import-area:hover { border-color: var(--primary); }
    .import-area input { display: none; }
  </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 Stok</div>
      <button class="scan-btn" onclick="openScanner()">📷 Scan Barcode</button>
      <button class="topbar-btn secondary" style="margin-left:8px" onclick="document.getElementById('modalImport').classList.add('open')">
        📥 Import CSV
      </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; ?>

      <!-- Stat Cards -->
      <div class="stat-grid" style="margin-bottom:20px">
        <div class="stat-card sc-red" style="cursor:pointer" onclick="setFilter('habis')">
          <div class="sc-label">Stok Habis</div>
          <div class="sc-val" style="color:var(--red)"><?= $statHabis ?></div>
          <div class="sc-sub">barang stok = 0</div>
        </div>
        <div class="stat-card sc-amber" style="cursor:pointer" onclick="setFilter('rendah')">
          <div class="sc-label">Stok Rendah</div>
          <div class="sc-val" style="color:var(--amber)"><?= $statRendah ?></div>
          <div class="sc-sub">stok 1 – 50</div>
        </div>
        <div class="stat-card sc-green" style="cursor:pointer" onclick="setFilter('aman')">
          <div class="sc-label">Stok Aman</div>
          <div class="sc-val" style="color:var(--green)"><?= $statAman ?></div>
          <div class="sc-sub">stok > 100</div>
        </div>
        <div class="stat-card sc-blue">
          <div class="sc-label">Total Barang</div>
          <div class="sc-val" style="color:var(--primary)"><?= $statTotal ?></div>
          <div class="sc-sub">item aktif</div>
        </div>
      </div>

      <!-- Filter & Search (FORM GET terpisah, di luar form POST) -->
      <div class="card" style="margin-bottom:16px">
        <div class="card-body" style="padding:14px 20px">
          <form method="GET" id="filterForm" style="display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin-bottom:12px">
            <input type="hidden" name="filter" value="<?= htmlspecialchars($filter) ?>">
            <input type="hidden" name="page" value="1">
              <input type="text" name="q" id="searchInput" class="form-control"
                     style="max-width:280px" placeholder="Cari nama / kode barang..."
                     value="<?= htmlspecialchars($search) ?>">
              <select name="kat" id="katFilter" class="form-control" style="width:auto" onchange="this.form.submit()">
                <option value="">Semua Kategori</option>
                <?php foreach ($kategoriList as $k): ?>
                <option value="<?= $k['id'] ?>" <?= $kat_id == $k['id'] ? 'selected':'' ?>>
                  <?= htmlspecialchars($k['nama']) ?>
                </option>
                <?php endforeach; ?>
              </select>
              <button type="submit" class="btn btn-primary btn-sm">🔍 Cari</button>
              <a href="stok.php" class="btn btn-ghost btn-sm">Reset</a>
          </form>
          <div class="filter-chips">
              <?php
              $qBase = http_build_query(array_filter(['q'=>$search,'kat'=>$kat_id?:null]));
              $qBase = $qBase ? "&$qBase" : '';
              ?>
              <a href="?filter=semua<?= $qBase ?>"  class="chip chip-all    <?= $filter==='semua'  ?'active':'' ?>">📋 Semua (<?= $statTotal ?>)</a>
              <a href="?filter=habis<?= $qBase ?>"  class="chip chip-habis  <?= $filter==='habis'  ?'active':'' ?>">🔴 Habis (<?= $statHabis ?>)</a>
              <a href="?filter=rendah<?= $qBase ?>" class="chip chip-rendah <?= $filter==='rendah' ?'active':'' ?>">🟡 Rendah (<?= $statRendah ?>)</a>
              <a href="?filter=aman<?= $qBase ?>"   class="chip chip-aman   <?= $filter==='aman'   ?'active':'' ?>">🟢 Aman (<?= $statAman ?>)</a>
            </div>
          </div>
        </div>

      <!-- FORM POST untuk simpan stok -->
      <form method="POST" id="formStok">
        <input type="hidden" name="bulk_stok" value="1">
        <input type="hidden" name="page" value="<?= $page ?>">
        <input type="hidden" name="filter" value="<?= htmlspecialchars($filter) ?>">
        <input type="hidden" name="q" value="<?= htmlspecialchars($search) ?>">
        <input type="hidden" name="kat" value="<?= $kat_id ?>">

        <!-- Panduan -->
        <div style="background:rgba(212,175,55,.08);border:1px solid rgba(212,175,55,.2);border-radius:12px;padding:12px 16px;margin-bottom:16px;font-size:13px;">
          💡 <strong style="color:var(--primary)">Cara pakai:</strong>
          <span style="color:var(--text-body)">Pilih mode</span>
          <strong style="color:var(--primary)">Tambah</strong>
          <span style="color:var(--text-body)">(menambah ke stok saat ini) atau</span>
          <strong style="color:var(--primary)">Set</strong>
          <span style="color:var(--text-body)">(ganti stok ke angka baru). Isi kolom jumlah lalu klik</span>
          <strong style="color:var(--primary)">Simpan Semua</strong><span style="color:var(--text-body)">. Baris kosong/nol akan dilewati.</span>
        </div>

        <!-- Tabel Stok -->
        <div class="card">
          <div class="card-header">
            <h3>
              Daftar Stok
              <span style="font-weight:400;color:var(--muted);font-size:13px">
                — Hal <?= $page ?>/<?= $totalPage ?> (<?= $totalItem ?> total)
              </span>
            </h3>
            <div style="display:flex;gap:8px">
              <button type="button" class="btn btn-ghost btn-sm" onclick="setAllMode('tambah')">Semua: Tambah</button>
              <button type="button" class="btn btn-ghost btn-sm" onclick="setAllMode('set')">Semua: Set</button>
              <button type="button" class="btn btn-ghost btn-sm" style="border:1px solid var(--border)" onclick="fillAll()">Isi Semua: <span id="fillVal">0</span></button>
              <input type="number" id="fillAmount" class="form-control" style="width:70px;padding:6px 8px;font-size:13px"
                     value="0" min="0" oninput="document.getElementById('fillVal').textContent=this.value">
            </div>
          </div>
          <div class="table-wrap">
            <table id="stokTable">
              <thead>
                <tr>
                  <th style="width:36px">
                    <input type="checkbox" id="checkAll" onchange="toggleAll(this.checked)" title="Pilih semua">
                  </th>
                  <th>Kode</th>
                  <th>Nama Barang</th>
                  <th class="hide-mobile">Kategori</th>
                  <th>Stok Saat Ini</th>
                  <th style="width:100px">Mode</th>
                  <th style="width:100px">Jumlah</th>
                  <th>Stok Baru</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($barangList as $b): ?>
                <tr id="row-<?= $b['id'] ?>"
                    data-nama="<?= strtolower(htmlspecialchars($b['nama'])) ?>"
                    data-kode="<?= strtolower(htmlspecialchars($b['kode'])) ?>"
                    data-kat="<?= $b['kategori_id'] ?>"
                    data-stok="<?= $b['stok'] ?>">
                  <td>
                    <input type="checkbox" class="row-check" data-id="<?= $b['id'] ?>">
                  </td>
                  <td><code style="font-size:11px"><?= htmlspecialchars($b['kode']) ?></code></td>
                  <td>
                    <strong><?= htmlspecialchars($b['nama']) ?></strong>
                    <div style="font-size:11px;color:var(--muted)"><?= htmlspecialchars($b['satuan']) ?></div>
                  </td>
                  <td><?= htmlspecialchars($b['kat_nama']) ?></td>
                  <td>
                    <span class="badge <?= $b['stok'] == 0 ? 'badge-red' : ($b['stok'] <= 50 ? 'badge-amber' : 'badge-green') ?>
                          stok-badge" id="badge-<?= $b['id'] ?>">
                      <?= $b['stok'] ?>
                    </span>
                  </td>
                  <td>
                    <select name="tipe[<?= $b['id'] ?>]"
                            class="tipe-select"
                            id="tipe-<?= $b['id'] ?>"
                            onchange="hitungBaru(<?= $b['id'] ?>, <?= $b['stok'] ?>)">
                      <option value="tambah">➕ Tambah</option>
                      <option value="set">📝 Set</option>
                    </select>
                  </td>
                  <td>
                    <input type="number"
                           name="stok[<?= $b['id'] ?>]"
                           class="stok-input"
                           id="input-<?= $b['id'] ?>"
                           value="0" min="0"
                           oninput="hitungBaru(<?= $b['id'] ?>, <?= $b['stok'] ?>)">
                  </td>
                  <td>
                    <span style="font-weight:700;color:var(--primary)" id="baru-<?= $b['id'] ?>">
                      <?= $b['stok'] ?>
                    </span>
                  </td>
                </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        </div>

        <!-- Pagination -->
        <?php if ($totalPage > 1): ?>
        <div style="display:flex;align-items:center;justify-content:center;gap:6px;padding:16px 0;flex-wrap:wrap">

          <?php if ($page > 1): ?>
          <a href="<?= pageUrl(1, $filter, $search, $kat_id) ?>"
             class="btn btn-ghost btn-sm" title="Halaman pertama">«</a>
          <a href="<?= pageUrl($page-1, $filter, $search, $kat_id) ?>"
             class="btn btn-ghost btn-sm">‹ Prev</a>
          <?php endif; ?>

          <?php
          // Tampilkan maksimal 5 nomor halaman di sekitar halaman aktif
          $start = max(1, $page - 2);
          $end   = min($totalPage, $page + 2);
          if ($start > 1): ?>
            <span style="color:var(--muted);padding:0 4px">...</span>
          <?php endif;
          for ($i = $start; $i <= $end; $i++): ?>
          <a href="<?= pageUrl($i, $filter, $search, $kat_id) ?>"
             class="btn btn-sm <?= $i === $page ? 'btn-primary' : 'btn-ghost' ?>"
             style="min-width:36px;justify-content:center">
            <?= $i ?>
          </a>
          <?php endfor;
          if ($end < $totalPage): ?>
            <span style="color:var(--muted);padding:0 4px">...</span>
          <?php endif; ?>

          <?php if ($page < $totalPage): ?>
          <a href="<?= pageUrl($page+1, $filter, $search, $kat_id) ?>"
             class="btn btn-ghost btn-sm">Next ›</a>
          <a href="<?= pageUrl($totalPage, $filter, $search, $kat_id) ?>"
             class="btn btn-ghost btn-sm" title="Halaman terakhir">»</a>
          <?php endif; ?>

          <span style="font-size:12px;color:var(--muted);margin-left:8px">
            Item <?= $offset+1 ?>–<?= min($offset+$perPage, $totalItem) ?> dari <?= $totalItem ?>
          </span>
        </div>
        <?php endif; ?>

        <!-- Sticky Save Bar -->
        <div class="sticky-bar">
          <div class="changed-count" id="changedCount">0 barang diubah</div>
          <div style="display:flex;gap:10px;align-items:center">
            <button type="button" class="btn btn-ghost" onclick="resetForm()">↩ Reset</button>
            <button type="submit" class="btn btn-primary" style="padding:12px 28px;font-size:15px">
              💾 Simpan Semua Perubahan
            </button>
          </div>
        </div>

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

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

<!-- ── Modal Import CSV ── -->
<div class="modal-overlay" id="modalImport">
  <div class="modal" style="max-width:500px">
    <div class="modal-header">
      <h4>📥 Import Stok dari CSV</h4>
      <button class="modal-close" onclick="document.getElementById('modalImport').classList.remove('open')">×</button>
    </div>
    <div class="modal-body">
      <p style="font-size:14px;color:var(--muted);margin-bottom:16px">
        Upload file CSV dengan format: <strong>kode_barang, jumlah_tambah</strong>
      </p>
      <div style="background:var(--bg);border-radius:10px;padding:12px 16px;font-size:12px;font-family:monospace;margin-bottom:16px;line-height:1.8">
        kode_barang,jumlah<br>
        8992221088320,50<br>
        BRG001,100<br>
        (90)MD023767000101285,25
      </div>
      <div class="import-area" onclick="document.getElementById('csvFile').click()">
        <input type="file" id="csvFile" accept=".csv" onchange="handleCSV(this)">
        <div style="font-size:32px;margin-bottom:8px">📄</div>
        <div style="font-size:14px;font-weight:600">Klik untuk pilih file CSV</div>
        <div style="font-size:12px;color:var(--muted);margin-top:4px">Format: kode_barang, jumlah</div>
      </div>
      <div id="csvPreview" style="margin-top:16px;display:none">
        <div style="font-size:13px;font-weight:600;margin-bottom:8px">Preview data CSV:</div>
        <div id="csvPreviewTable" style="max-height:200px;overflow-y:auto"></div>
        <div style="margin-top:12px;display:flex;gap:10px">
          <button type="button" class="btn btn-ghost" onclick="cancelCSV()">Batal</button>
          <button type="button" class="btn btn-primary" onclick="applyCSV()">✅ Terapkan ke Form</button>
        </div>
      </div>
    </div>
  </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 lastScanned = '';
let lastScannedTime = 0;
let csvData = [];

// ══════════════════════════════════════
//  HITUNG STOK BARU
// ══════════════════════════════════════
function hitungBaru(id, stokSaatIni) {
  const input  = document.getElementById('input-' + id);
  const tipe   = document.getElementById('tipe-' + id).value;
  const jumlah = parseInt(input.value) || 0;
  const baru   = tipe === 'tambah' ? stokSaatIni + jumlah : jumlah;

  document.getElementById('baru-' + id).textContent = baru;

  // Highlight baris kalau ada perubahan
  const row = document.getElementById('row-' + id);
  if (jumlah !== 0) {
    row.classList.add('row-highlight');
    input.classList.add('changed');
  } else {
    row.classList.remove('row-highlight');
    input.classList.remove('changed');
  }

  updateChangedCount();
}

function updateChangedCount() {
  const n = document.querySelectorAll('.stok-input.changed').length;
  document.getElementById('changedCount').textContent =
    n > 0 ? `${n} barang diubah — jangan lupa simpan!` : '0 barang diubah';
  document.getElementById('changedCount').style.color = n > 0 ? 'var(--primary)' : 'var(--muted)';
}

// ══════════════════════════════════════
//  BULK ACTIONS
// ══════════════════════════════════════
function setAllMode(mode) {
  document.querySelectorAll('.tipe-select').forEach(sel => {
    const row = sel.closest('tr');
    if (row.style.display !== 'none') sel.value = mode;
  });
  // Recalculate semua
  document.querySelectorAll('.stok-input').forEach(input => {
    const id    = input.name.match(/\d+/)[0];
    const stok  = parseInt(input.closest('tr').dataset.stok);
    hitungBaru(parseInt(id), stok);
  });
}

function fillAll() {
  const val = parseInt(document.getElementById('fillAmount').value) || 0;
  document.querySelectorAll('.stok-input').forEach(input => {
    const row = input.closest('tr');
    if (row.style.display === 'none') return;
    // Hanya isi yang sudah dicentang, atau semua jika tidak ada yang dicentang
    const checked = document.querySelectorAll('.row-check:checked').length > 0;
    const rowCheck = row.querySelector('.row-check');
    if (!checked || rowCheck.checked) {
      input.value = val;
      const id   = parseInt(input.name.match(/\d+/)[0]);
      const stok = parseInt(row.dataset.stok);
      hitungBaru(id, stok);
    }
  });
}

function toggleAll(checked) {
  document.querySelectorAll('.row-check').forEach(cb => {
    const row = cb.closest('tr');
    if (row.style.display !== 'none') cb.checked = checked;
  });
}

function resetForm() {
  document.querySelectorAll('.stok-input').forEach(input => {
    input.value = 0;
    input.classList.remove('changed');
  });
  document.querySelectorAll('tr[id^="row-"]').forEach(row => {
    row.classList.remove('row-highlight');
    const id   = parseInt(row.id.replace('row-', ''));
    const stok = parseInt(row.dataset.stok);
    document.getElementById('baru-' + id).textContent = stok;
  });
  updateChangedCount();
}

// ══════════════════════════════════════
//  FILTER TABEL (CLIENT-SIDE)
// ══════════════════════════════════════
function filterTable() {
  const q   = document.getElementById('searchInput').value.toLowerCase();
  const kat = document.getElementById('katFilter').value;

  document.querySelectorAll('#stokTable tbody tr').forEach(row => {
    const nama    = row.dataset.nama || '';
    const kode    = row.dataset.kode || '';
    const katId   = row.dataset.kat  || '';
    const qMatch  = !q   || nama.includes(q) || kode.includes(q);
    const katMatch= !kat || katId === kat;
    row.style.display = (qMatch && katMatch) ? '' : 'none';
  });
}

function resetFilter() {
  document.getElementById('searchInput').value = '';
  document.getElementById('katFilter').value   = '';
  filterTable();
}

function setFilter(f) {
  window.location.href = '?filter=' + f;
}

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

  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');
}

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';

  // Cari baris berdasarkan kode
  const kodeClean = decodedText.toLowerCase().trim();
  let foundRow = null;
  document.querySelectorAll('#stokTable tbody tr').forEach(row => {
    if (row.dataset.kode === kodeClean) foundRow = row;
  });

  if (foundRow) {
    const id    = parseInt(foundRow.id.replace('row-', ''));
    const nama  = foundRow.querySelector('strong').textContent;
    const stok  = parseInt(foundRow.dataset.stok);

    resultEl.className = 'found';
    resultEl.innerHTML = `✅ <strong>${nama}</strong><br>Stok saat ini: ${stok}`;
    document.getElementById('scanner-status').textContent = '✅ Barang ditemukan!';

    // Scroll ke baris & highlight
    foundRow.scrollIntoView({ behavior: 'smooth', block: 'center' });
    foundRow.classList.add('row-scanned');
    setTimeout(() => foundRow.classList.remove('row-scanned'), 2000);

    // Reset filter agar baris terlihat
    document.getElementById('searchInput').value = decodedText;
    filterTable();

    // Fokus ke input stok
    setTimeout(() => {
      const inputEl = document.getElementById('input-' + id);
      if (inputEl) inputEl.focus();
    }, 400);

    setTimeout(() => {
      document.getElementById('scanner-status').textContent = '📷 Scan barcode barang...';
      resultEl.style.display = 'none';
    }, 2000);

  } else {
    resultEl.className = 'notfound';
    resultEl.innerHTML = `❌ Barcode tidak ditemukan:<br><code>${decodedText}</code>`;
    document.getElementById('scanner-status').textContent = '❌ Barang tidak ditemukan';
    setTimeout(() => {
      document.getElementById('scanner-status').textContent = '📷 Scan barcode barang...';
      resultEl.style.display = 'none';
    }, 2500);
  }
}

// ══════════════════════════════════════
//  IMPORT CSV
// ══════════════════════════════════════
function handleCSV(input) {
  const file = input.files[0];
  if (!file) return;

  const reader = new FileReader();
  reader.onload = function(e) {
    const lines = e.target.result.trim().split('\n');
    csvData = [];
    let html = '<table style="width:100%;font-size:13px;border-collapse:collapse">';
    html += '<thead><tr><th style="padding:6px;text-align:left;border-bottom:1px solid var(--border)">Kode</th><th style="padding:6px;text-align:left;border-bottom:1px solid var(--border)">Jumlah</th><th style="padding:6px;text-align:left;border-bottom:1px solid var(--border)">Status</th></tr></thead><tbody>';

    lines.forEach((line, i) => {
      if (i === 0 && line.toLowerCase().includes('kode')) return; // skip header
      const parts = line.split(',');
      if (parts.length < 2) return;
      const kode   = parts[0].trim().replace(/"/g, '');
      const jumlah = parseInt(parts[1].trim()) || 0;

      // Cek apakah kode ada di tabel
      const kodeClean = kode.toLowerCase();
      let found = false;
      document.querySelectorAll('#stokTable tbody tr').forEach(row => {
        if (row.dataset.kode === kodeClean) found = true;
      });

      csvData.push({ kode, jumlah, found });
      const status = found
        ? '<span style="color:#065f46;font-weight:600">✅ Ditemukan</span>'
        : '<span style="color:#991b1b">❌ Tidak ada</span>';
      html += `<tr><td style="padding:5px 6px;border-bottom:1px solid var(--border)">${kode}</td><td style="padding:5px 6px;border-bottom:1px solid var(--border)">${jumlah}</td><td style="padding:5px 6px;border-bottom:1px solid var(--border)">${status}</td></tr>`;
    });

    html += '</tbody></table>';
    document.getElementById('csvPreviewTable').innerHTML = html;
    document.getElementById('csvPreview').style.display = 'block';
  };
  reader.readAsText(file);
}

function applyCSV() {
  csvData.forEach(item => {
    if (!item.found || item.jumlah <= 0) return;
    const kodeClean = item.kode.toLowerCase();
    document.querySelectorAll('#stokTable tbody tr').forEach(row => {
      if (row.dataset.kode === kodeClean) {
        const id    = parseInt(row.id.replace('row-', ''));
        const stok  = parseInt(row.dataset.stok);
        const input = document.getElementById('input-' + id);
        input.value = item.jumlah;
        hitungBaru(id, stok);
      }
    });
  });

  document.getElementById('modalImport').classList.remove('open');
  cancelCSV();

  // Scroll ke atas tabel
  document.getElementById('stokTable').scrollIntoView({ behavior: 'smooth' });
}

function cancelCSV() {
  csvData = [];
  document.getElementById('csvPreview').style.display = 'none';
  document.getElementById('csvFile').value = '';
}
</script>
</body>
</html>