<?= $this->extend('layouts/main') ?>
<?= $this->section('content') ?>

<style>
  /* ════════════════════════════════════════════
     LAPORAN PRODUKSI — style selaras Kelola Karyawan
  ════════════════════════════════════════════ */

  :root {
    --blue:     #3b82f6;
    --blue-bg:  rgba(59,130,246,.08);
    --blue-brd: rgba(59,130,246,.25);

    --green:    #10b981;
    --green-bg: rgba(16,185,129,.08);
    --green-brd:rgba(16,185,129,.25);

    --amber:    #f59e0b;
    --amber-bg: rgba(245,158,11,.08);
    --amber-brd:rgba(245,158,11,.25);

    --red:      #ef4444;
    --red-bg:   rgba(239,68,68,.08);
    --red-brd:  rgba(239,68,68,.25);

    --slate:    #6366f1;
    --slate-bg: rgba(99,102,241,.08);

    --r:  14px;
    --rs: 8px;
  }

  /* ─── PAGE HEADER ─────────────────────────────── */
  .lp-head {
    display: flex; align-items: center; justify-content: space-between;
    flex-wrap: wrap; gap: 12px; margin-bottom: 28px;
  }
  .lp-title {
    font-size: 1.4rem; font-weight: 700; color: var(--text-main);
    display: flex; align-items: center; gap: 10px;
  }
  .lp-subtitle { font-size: .8rem; color: var(--text-muted); margin-top: 2px; }
  .lp-head-right { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }

  /* ─── BUTTONS ──────────────────────────────────── */
  .btn-accent {
    background: linear-gradient(90deg, #3b82f6, #6366f1);
    border: none; color: #fff; border-radius: var(--rs);
    padding: 8px 14px; font-size: .85rem; font-weight: 600;
    cursor: pointer; display: inline-flex; align-items: center;
    gap: 6px; transition: opacity .15s; white-space: nowrap;
  }
  .btn-accent:hover { opacity: .85; }

  .btn-ghost {
    background: transparent; border: 1px solid var(--border);
    color: var(--text-muted); border-radius: var(--rs);
    padding: 4px 9px; font-size: .75rem; font-weight: 500;
    cursor: pointer; display: inline-flex; align-items: center;
    gap: 6px; transition: border-color .15s, color .15s; white-space: nowrap;
  }
  .btn-ghost:hover { border-color: var(--accent); color: var(--accent); }

  /* ─── FILTER STRIP ─────────────────────────────── */
  .lp-filter {
    background: #fff; border: 1px solid var(--border);
    border-radius: var(--r); padding: 16px 20px; margin-bottom: 22px;
    display: flex; flex-wrap: wrap; gap: 12px; align-items: flex-end;
    box-shadow: 0 1px 3px rgba(0,0,0,.05);
  }
  .f-grp { display: flex; flex-direction: column; gap: 5px; flex: 1; min-width: 130px; }
  .f-grp label {
    font-size: .72rem; font-weight: 600; letter-spacing: .06em;
    text-transform: uppercase; color: var(--text-muted);
  }
  .f-grp input, .f-grp select {
    padding: 8px 12px; border: 1px solid var(--border); border-radius: var(--rs);
    background: #fff; color: var(--text-main);
    font-size: .83rem; outline: none; transition: border-color .15s, box-shadow .15s;
    box-sizing: border-box;
  }
  .f-grp input:focus, .f-grp select:focus {
    border-color: var(--accent);
    box-shadow: 0 0 0 3px rgba(59,130,246,.1);
  }
  .f-grp select { cursor: pointer; }

  /* ─── STATS GRID ───────────────────────────────── */
  .lp-stats {
    display: grid; grid-template-columns: repeat(auto-fit, minmax(155px, 1fr));
    gap: 12px; margin-bottom: 24px;
  }
  .lp-stat {
    background: #fff; border: 1px solid var(--border);
    border-radius: var(--r); padding: 18px 18px 14px;
    position: relative; overflow: hidden;
    box-shadow: 0 1px 3px rgba(0,0,0,.05);
    transition: transform .15s, box-shadow .15s;
  }
  .lp-stat::after {
    content: ''; position: absolute; top: 0; left: 0; right: 0; height: 3px;
    background: var(--accent-line, var(--border));
  }
  .lp-stat:hover { transform: translateY(-2px); box-shadow: 0 4px 16px rgba(0,0,0,.08); }
  .stat-ico {
    width: 34px; height: 34px; border-radius: 9px; display: flex;
    align-items: center; justify-content: center; font-size: 16px; margin-bottom: 12px;
  }
  .stat-val { font-size: 1.35rem; font-weight: 700; line-height: 1; font-family: monospace; }
  .stat-lbl { font-size: .72rem; text-transform: uppercase; letter-spacing: .06em; color: var(--text-muted); font-weight: 600; margin-top: 6px; }

  .s-blue  { --accent-line: #3b82f6; }
  .s-green { --accent-line: #10b981; }
  .s-amber { --accent-line: #f59e0b; }
  .s-red   { --accent-line: #ef4444; }
  .s-slate { --accent-line: #6366f1; }

  /* ─── TABS ─────────────────────────────────────── */
  .lp-tabs { display: flex; gap: 2px; margin-bottom: 18px; background: var(--border); border-radius: 12px; padding: 3px; width: fit-content; flex-wrap: wrap; }
  .lp-tab {
    padding: 7px 16px; border-radius: 9px; font-size: .8rem; font-weight: 600;
    cursor: pointer; border: none; background: transparent; color: var(--text-muted);
    transition: all .16s; display: inline-flex; align-items: center;
    gap: 6px; white-space: nowrap;
  }
  .lp-tab:hover { color: var(--text-main); background: rgba(255,255,255,.6); }
  .lp-tab.active {
    background: #fff; color: var(--text-main);
    box-shadow: 0 1px 4px rgba(0,0,0,.1), 0 0 0 1px var(--border);
  }
  .tab-ct {
    background: var(--border); color: var(--text-muted); border-radius: 20px;
    padding: 1px 7px; font-size: .65rem;
  }
  .lp-tab.active .tab-ct { background: var(--blue-bg); color: var(--blue); }

  /* ─── PANELS ───────────────────────────────────── */
  .pane { display: none; }
  .pane.active { display: block; }

  /* ─── TABLE CARD ─────────────────────────────────── */
  .lp-card {
    background: #fff; border: 1px solid var(--border);
    border-radius: var(--r); overflow: hidden; margin-bottom: 20px;
    box-shadow: 0 1px 3px rgba(0,0,0,.05);
  }
  .lp-card-head {
    padding: 16px 20px; border-bottom: 1px solid var(--border);
    display: flex; align-items: center; justify-content: space-between;
    gap: 12px; flex-wrap: wrap;
  }
  .lp-card-title {
    font-size: .9rem; font-weight: 600; color: var(--text-main);
    display: flex; align-items: center; gap: 8px;
  }
  .lp-count-tag {
    font-size: .72rem; color: var(--text-muted);
    background: #f8fafc; border: 1px solid var(--border); padding: 2px 10px;
    border-radius: 20px; font-family: monospace;
  }

  /* ─── CHART BARS ───────────────────────────────── */
  .chart-area { padding: 16px 20px; }
  .bar-row { display: flex; align-items: center; gap: 10px; margin-bottom: 9px; }
  .bar-lbl { font-size: .75rem; font-weight: 600; min-width: 120px; max-width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-muted); }
  .bar-track { flex: 1; background: #f8fafc; border: 1px solid var(--border); border-radius: 4px; height: 12px; overflow: hidden; }
  .bar-fill { height: 100%; border-radius: 4px; transition: width .8s cubic-bezier(.34,1.3,.64,1); }
  .bar-num { font-family: monospace; font-size: .72rem; font-weight: 500; min-width: 60px; text-align: right; color: var(--text-muted); }

  /* ─── TABLE ────────────────────────────────────── */
  .tbl-wrap { overflow-x: auto; }
  .lp-tbl { width: 100%; border-collapse: collapse; font-size: .83rem; }
  .lp-tbl thead tr { background: #f8fafc; }
  .lp-tbl thead th {
    padding: 11px 16px; text-align: left; color: var(--text-muted);
    font-weight: 600; font-size: .72rem; text-transform: uppercase;
    letter-spacing: .06em; border-bottom: 1px solid var(--border); white-space: nowrap;
  }
  .lp-tbl thead th.tr { text-align: right; }
  .lp-tbl tbody tr { border-bottom: 1px solid var(--border); transition: background .15s; }
  .lp-tbl tbody tr:last-child { border-bottom: none; }
  .lp-tbl tbody tr:hover { background: #f8fafc; }
  .lp-tbl tbody td { padding: 11px 16px; color: #334155; vertical-align: middle; }
  .tr { text-align: right; }

  /* ─── HPP ROWS ─────────────────────────────────── */
  .hpp-row {
    display: grid; grid-template-columns: 2fr 1fr 1fr 1fr 1fr 1fr;
    gap: 8px; padding: 14px 20px; border-bottom: 1px solid var(--border);
    cursor: pointer; transition: background .12s;
  }
  .hpp-row:last-child { border-bottom: none; }
  .hpp-row:hover { background: #f8fafc; }
  .hpp-row:hover .hpp-hint { opacity: 1; }
  .hpp-cell { display: flex; flex-direction: column; gap: 4px; }
  .hpp-label { font-size: .65rem; text-transform: uppercase; letter-spacing: .06em; color: var(--text-muted); font-weight: 600; }
  .hpp-val { font-family: monospace; font-size: .85rem; font-weight: 700; color: var(--text-main); }
  .hpp-hint { font-size: .65rem; color: var(--blue); opacity: 0; transition: opacity .15s; margin-top: 2px; }

  /* ─── MISC ─────────────────────────────────────── */
  .mono { font-family: monospace; }
  .c-blue  { color: #4f8ef7; }
  .c-green { color: #4ade80; }
  .c-amber { color: #f59e0b; }
  .c-red   { color: #ef4444; }
  .c-muted { color: var(--text-muted); }

  .tag {
    display: inline-flex; align-items: center; padding: 2px 8px;
    border-radius: 5px; font-family: monospace; font-size: .72rem; font-weight: 500;
  }
  .tag-blue  { background: var(--blue-bg);  color: #4f8ef7;  border: 1px solid var(--blue-brd); }
  .tag-green { background: var(--green-bg); color: #10b981; border: 1px solid var(--green-brd); }
  .tag-amber { background: var(--amber-bg); color: #f59e0b; border: 1px solid var(--amber-brd); }

  .pct-bar { display: inline-flex; align-items: center; gap: 5px; justify-content: flex-end; }
  .pct-track { width: 50px; background: #f8fafc; border: 1px solid var(--border); border-radius: 3px; height: 5px; overflow: hidden; }
  .pct-fill  { height: 100%; border-radius: 3px; }

  .empty-state { text-align: center; padding: 44px 24px; }
  .empty-state i { font-size: 2rem; opacity: .2; display: block; margin-bottom: 10px; }
  .empty-state p { font-size: .8rem; color: var(--text-muted); }

  /* ─── SKELETON ─────────────────────────────────── */
  .skel { background: linear-gradient(90deg, #e2e8f0 25%, #cbd5e1 50%, #e2e8f0 75%); background-size: 200% 100%; animation: sk 1.5s infinite; border-radius: 5px; }
  @keyframes sk { 0%{background-position:200% 0} 100%{background-position:-200% 0} }
  .skel-row { display: flex; gap: 10px; margin-bottom: 10px; align-items: center; }

  /* ─── TOAST ────────────────────────────────────── */
  #lp-toast {
    position: fixed; bottom: 20px; right: 20px; z-index: 9999;
    padding: 12px 16px; border-radius: 10px; font-size: .85rem; font-weight: 500;
    display: flex; align-items: center; gap: 8px;
    transform: translateY(60px) scale(.95); opacity: 0;
    transition: all .3s cubic-bezier(.34,1.4,.64,1); pointer-events: none;
    max-width: 320px; box-shadow: 0 4px 20px rgba(0,0,0,.1);
  }
  #lp-toast.show { transform: translateY(0) scale(1); opacity: 1; }
  #lp-toast.ok  { background: #fff; border: 1px solid var(--green-brd); color: #059669; }
  #lp-toast.err { background: #fff; border: 1px solid var(--red-brd);   color: #dc2626; }

  /* ─── RESPONSIVE ───────────────────────────────── */
  @media (max-width: 700px) {
    .hpp-row    { grid-template-columns: 1fr 1fr; }
    .lp-filter  { flex-direction: column; }
    .lp-tabs    { width: 100%; }
    .lp-tab     { flex: 1; justify-content: center; }
  }
</style>

<div id="lp-toast"></div>

<div>

  <!-- ══ PAGE HEADER ══ -->
  <div class="lp-head">
    <div>
      <div class="lp-title">
        <i class="bi bi-bar-chart-line-fill" style="color:#4f8ef7"></i>
        Laporan Produksi
      </div>
      <div class="lp-subtitle">Rekap · Per Produk · Pemakaian Bahan · HPP Aktual</div>
    </div>
    <div class="lp-head-right">
      <button class="btn-accent" onclick="loadLaporan()">
        <i class="bi bi-arrow-clockwise"></i> Refresh
      </button>
    </div>
  </div>

  <!-- ══ FILTER ══ -->
  <div class="lp-filter">
    <div class="f-grp" style="min-width:120px;flex:0 0 auto">
      <label>Periode</label>
      <select id="f-periode">
        <option value="harian">Harian</option>
        <option value="mingguan">Mingguan</option>
        <option value="bulanan" selected>Bulanan</option>
      </select>
    </div>
    <div class="f-grp">
      <label>Dari Tanggal</label>
      <input type="date" id="f-dari">
    </div>
    <div class="f-grp">
      <label>Sampai</label>
      <input type="date" id="f-sampai">
    </div>
    <div class="f-grp" style="min-width:160px">
      <label>Filter Produk</label>
      <select id="f-produk"><option value="">— Semua Produk —</option></select>
    </div>
    <button class="btn-accent" onclick="loadLaporan()">
      <i class="bi bi-funnel-fill"></i> Terapkan
    </button>
  </div>

  <!-- ══ STAT CARDS ══ -->
  <div class="lp-stats">
    <div class="lp-stat s-blue">
      <div class="stat-ico" style="background:var(--blue-bg);color:#4f8ef7"><i class="bi bi-layers-fill"></i></div>
      <div class="stat-val c-blue" id="s-total-prod">—</div>
      <div class="stat-lbl">Total Batch</div>
    </div>
    <div class="lp-stat s-green">
      <div class="stat-ico" style="background:var(--green-bg);color:#4ade80"><i class="bi bi-boxes"></i></div>
      <div class="stat-val c-green" id="s-total-kem">—</div>
      <div class="stat-lbl">Total Picis</div>
    </div>
    <div class="lp-stat s-amber">
      <div class="stat-ico" style="background:var(--amber-bg);color:#f59e0b"><i class="bi bi-basket2-fill"></i></div>
      <div class="stat-val c-amber" id="s-jenis-bahan">—</div>
      <div class="stat-lbl">Jenis Bahan Terpakai</div>
    </div>
    <div class="lp-stat s-slate">
      <div class="stat-ico" style="background:var(--slate-bg);color:#6366f1"><i class="bi bi-cash-stack"></i></div>
      <div class="stat-val mono" style="color:#6366f1" id="s-total-hpp">—</div>
      <div class="stat-lbl">Total HPP</div>
    </div>
    <div class="lp-stat s-red">
      <div class="stat-ico" style="background:var(--red-bg);color:#ef4444"><i class="bi bi-tag-fill"></i></div>
      <div class="stat-val c-red" id="s-hpp-pcs">—</div>
      <div class="stat-lbl">HPP / Picis</div>
    </div>
  </div>

  <!-- ══ TABS ══ -->
  <div class="lp-tabs">
    <button class="lp-tab active" onclick="switchTab('periode',this)">
      <i class="bi bi-calendar3"></i> Rekap Periode
      <span class="tab-ct" id="tc-periode">—</span>
    </button>
    <button class="lp-tab" onclick="switchTab('produk',this)">
      <i class="bi bi-bag-fill"></i> Per Produk
      <span class="tab-ct" id="tc-produk">—</span>
    </button>
    <button class="lp-tab" onclick="switchTab('bahan',this)">
      <i class="bi bi-basket2-fill"></i> Pemakaian Bahan
      <span class="tab-ct" id="tc-bahan">—</span>
    </button>
    <button class="lp-tab" onclick="switchTab('hpp',this)">
      <i class="bi bi-receipt"></i> HPP Aktual
      <span class="tab-ct" id="tc-hpp">—</span>
    </button>
  </div>

  <!-- ══ PANE: PERIODE ══ -->
  <div class="pane active" id="pane-periode">
    <div class="lp-card">
      <div class="lp-card-head">
        <div class="lp-card-title">
          <i class="bi bi-calendar3" style="color:#4f8ef7"></i>
          Rekap Produksi per Periode
        </div>
        <span class="lp-count-tag" id="cnt-periode">—</span>
      </div>
      <div class="chart-area" id="chart-periode"><div class="skel-row"><div class="skel" style="width:100%;height:14px"></div></div></div>
      <div class="tbl-wrap">
        <table class="lp-tbl">
          <thead>
            <tr>
              <th>Periode</th>
              <th class="tr">Batch</th>
              <th class="tr">Total Picis</th>
              <th class="tr">HPP Total</th>
              <th class="tr">HPP / Picis</th>
            </tr>
          </thead>
          <tbody id="tb-periode"><tr><td colspan="5"><div style="padding:20px 16px"><?php for($i=0;$i<4;$i++): ?><div class="skel-row"><div class="skel" style="width:100%;height:13px"></div></div><?php endfor; ?></div></td></tr></tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- ══ PANE: PER PRODUK ══ -->
  <div class="pane" id="pane-produk">
    <div class="lp-card">
      <div class="lp-card-head">
        <div class="lp-card-title">
          <i class="bi bi-bag-fill" style="color:#10b981"></i>
          Rekap Produksi per Produk
        </div>
        <span class="lp-count-tag" id="cnt-produk">—</span>
      </div>
      <div class="chart-area" id="chart-produk"></div>
      <div class="tbl-wrap">
        <table class="lp-tbl">
          <thead>
            <tr>
              <th>#</th><th>Produk</th>
              <th class="tr">Batch</th><th class="tr">Picis</th>
              <th class="tr">HPP Total</th><th class="tr">HPP / Picis</th>
            </tr>
          </thead>
          <tbody id="tb-produk"></tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- ══ PANE: PEMAKAIAN BAHAN ══ -->
  <div class="pane" id="pane-bahan">
    <div class="lp-card">
      <div class="lp-card-head">
        <div class="lp-card-title">
          <i class="bi bi-basket2-fill" style="color:#f59e0b"></i>
          Pemakaian Bahan Produksi
        </div>
        <span class="lp-count-tag" id="cnt-bahan">—</span>
      </div>
      <div class="chart-area" id="chart-bahan"></div>
      <div class="tbl-wrap">
        <table class="lp-tbl">
          <thead>
            <tr>
              <th>#</th><th>Nama Bahan</th><th>Satuan</th>
              <th class="tr">Total Terpakai</th><th class="tr">Estimasi Biaya</th>
              <th class="tr">Kontribusi HPP</th>
            </tr>
          </thead>
          <tbody id="tb-bahan"></tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- ══ PANE: HPP AKTUAL ══ -->
  <div class="pane" id="pane-hpp">
    <div class="lp-card">
      <div class="lp-card-head">
        <div class="lp-card-title">
          <i class="bi bi-receipt" style="color:#6366f1"></i>
          HPP Aktual per Produk
        </div>
        <div style="display:flex;align-items:center;gap:8px">
          <span style="font-size:.72rem;color:var(--text-muted)">Klik baris untuk detail bahan ↓</span>
          <span class="lp-count-tag" id="cnt-hpp">—</span>
        </div>
      </div>
      <div style="display:grid;grid-template-columns:2fr 1fr 1fr 1fr 1fr 1fr;gap:8px;padding:8px 20px;border-bottom:1px solid var(--border);background:#f8fafc">
        <div style="font-size:.65rem;font-weight:600;text-transform:uppercase;letter-spacing:.06em;color:var(--text-muted)">Produk</div>
        <div style="font-size:.65rem;font-weight:600;text-transform:uppercase;letter-spacing:.06em;color:var(--text-muted);text-align:right">Picis</div>
        <div style="font-size:.65rem;font-weight:600;text-transform:uppercase;letter-spacing:.06em;color:var(--text-muted);text-align:right">Biaya Bahan</div>
        <div style="font-size:.65rem;font-weight:600;text-transform:uppercase;letter-spacing:.06em;color:var(--text-muted);text-align:right">Tenaga+Lain</div>
        <div style="font-size:.65rem;font-weight:600;text-transform:uppercase;letter-spacing:.06em;color:var(--text-muted);text-align:right">HPP Total</div>
        <div style="font-size:.65rem;font-weight:600;text-transform:uppercase;letter-spacing:.06em;color:var(--text-muted);text-align:right">HPP/Picis</div>
      </div>
      <div id="hpp-rows"></div>
    </div>

    <div class="lp-card" id="hpp-detail-card" style="display:none">
      <div class="lp-card-head">
        <div class="lp-card-title">
          <i class="bi bi-list-ul" style="color:#6366f1"></i>
          <span id="hpp-detail-name">Komponen HPP</span>
        </div>
        <button class="btn-ghost" onclick="document.getElementById('hpp-detail-card').style.display='none'">
          <i class="bi bi-x"></i> Tutup
        </button>
      </div>
      <div class="tbl-wrap">
        <table class="lp-tbl">
          <thead>
            <tr>
              <th>Bahan</th><th>Satuan</th>
              <th class="tr">Total Terpakai</th>
              <th class="tr">Harga Snapshot</th>
              <th class="tr">Subtotal Biaya</th>
              <th class="tr">% HPP Bahan</th>
            </tr>
          </thead>
          <tbody id="tb-hpp-detail"></tbody>
        </table>
      </div>
    </div>
  </div>

</div>

<script>
const BASE = '<?= base_url() ?>';
let lpData = null, toastT;
const esc  = s => String(s??'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
const fmtN = n => (parseFloat(n)||0).toLocaleString('id-ID');
const fmtRp= n => 'Rp\u00a0' + (parseFloat(n)||0).toLocaleString('id-ID');

function toast(msg, type='ok'){
  const el = document.getElementById('lp-toast');
  el.textContent = msg; el.className = 'show ' + type;
  clearTimeout(toastT);
  toastT = setTimeout(() => el.className='', 3800);
}

function switchTab(name, btn){
  document.querySelectorAll('.lp-tab').forEach(t => t.classList.remove('active'));
  document.querySelectorAll('.pane').forEach(p => p.classList.remove('active'));
  btn.classList.add('active');
  document.getElementById('pane-'+name).classList.add('active');
}

(function(){
  const now = new Date(), y = now.getFullYear(), m = String(now.getMonth()+1).padStart(2,'0');
  document.getElementById('f-dari').value   = `${y}-${m}-01`;
  document.getElementById('f-sampai').value = now.toISOString().split('T')[0];
})();

function bars(id, list, lk, vk, fill){
  const el = document.getElementById(id);
  if (!list?.length){ el.innerHTML = ''; return; }
  const max = Math.max(...list.map(i=>parseFloat(i[vk])||0))||1;
  el.innerHTML = list.slice(0,10).map(item => {
    const pct = ((parseFloat(item[vk])||0)/max*100).toFixed(1);
    return `<div class="bar-row">
      <div class="bar-lbl" title="${esc(item[lk])}">${esc(item[lk])}</div>
      <div class="bar-track"><div class="bar-fill" style="width:${pct}%;background:${fill}"></div></div>
      <div class="bar-num">${fmtN(item[vk])}</div>
    </div>`;
  }).join('');
}

function skel(cols){ return `<tr><td colspan="${cols}"><div style="padding:16px">${Array(4).fill(`<div class="skel-row"><div class="skel" style="width:100%;height:13px"></div></div>`).join('')}</div></td></tr>`; }
function empty(cols, msg='Tidak ada data di periode ini.'){
  return `<tr><td colspan="${cols}"><div class="empty-state"><i class="bi bi-inbox"></i><p>${msg}</p></div></td></tr>`;
}

async function loadLaporan(){
  ['tb-periode','tb-produk','tb-bahan'].forEach(id => document.getElementById(id).innerHTML = skel(6));
  document.getElementById('hpp-rows').innerHTML = `<div style="padding:20px;text-align:center;color:var(--text-muted);font-size:.8rem"><i class="bi bi-hourglass-split"></i> Memuat HPP…</div>`;

  const p = new URLSearchParams({
    periode:   document.getElementById('f-periode').value,
    dari:      document.getElementById('f-dari').value,
    sampai:    document.getElementById('f-sampai').value,
    id_produk: document.getElementById('f-produk').value,
  });

  try {
    const res  = await fetch(BASE+'laporan/produksi/data?'+p, { headers:{'X-Requested-With':'XMLHttpRequest'} });
    const text = await res.text();
    let d;
    try { d = JSON.parse(text); } catch { toast('Server error — bukan JSON','err'); return; }
    if (!d.success){ toast(d.error||'Gagal memuat','err'); return; }
    lpData = d;
    renderAll(d);
  } catch(e){ toast('Koneksi gagal: '+e.message,'err'); }
}

function renderAll(d){
  const s = d.summary||{};
  document.getElementById('s-total-prod').textContent  = fmtN(s.total_produksi??0);
  document.getElementById('s-total-kem').textContent   = fmtN(s.total_kemasan??0)+' pcs';
  document.getElementById('s-jenis-bahan').textContent = fmtN(s.jenis_bahan??0)+' jenis';
  document.getElementById('s-total-hpp').textContent   = fmtRp(s.total_hpp??0);
  document.getElementById('s-hpp-pcs').textContent     = fmtRp(s.hpp_per_kemasan??0);

  if(d.produk_list?.length){
    const sel = document.getElementById('f-produk'), cur = sel.value;
    sel.innerHTML = '<option value="">— Semua Produk —</option>' +
      d.produk_list.map(p=>`<option value="${p.id}" ${String(p.id)===cur?'selected':''}>${esc(p.nama)}</option>`).join('');
  }

  renderPeriode(d.rekap_periode||[]);
  renderProduk(d.rekap_produk||[]);
  renderBahan(d.pemakaian_bahan||[]);
  renderHPP(d.hpp_aktual||[]);
}

function renderPeriode(list){
  document.getElementById('cnt-periode').textContent = list.length+' baris';
  document.getElementById('tc-periode').textContent  = list.length;
  bars('chart-periode', list, 'label', 'total_kemasan', '#4f8ef7');
  if(!list.length){ document.getElementById('tb-periode').innerHTML = empty(5); return; }
  document.getElementById('tb-periode').innerHTML = list.map(r=>`
    <tr>
      <td style="font-weight:600">${esc(r.label)}</td>
      <td class="tr mono c-blue">${fmtN(r.total_batch)}</td>
      <td class="tr mono c-green" style="font-weight:bold">${fmtN(r.total_kemasan)} pcs</td>
      <td class="tr mono" style="color:#6366f1">${fmtRp(r.hpp_total)}</td>
      <td class="tr mono c-red">${fmtRp(r.hpp_per_kemasan)}</td>
    </tr>`).join('');
}

function renderProduk(list){
  document.getElementById('cnt-produk').textContent = list.length+' produk';
  document.getElementById('tc-produk').textContent  = list.length;
  bars('chart-produk', list, 'nama_produk', 'total_kemasan', '#4ade80');
  if(!list.length){ document.getElementById('tb-produk').innerHTML = empty(6); return; }
  document.getElementById('tb-produk').innerHTML = list.map((r,i)=>`
    <tr>
      <td class="mono c-muted" style="font-size:.72rem">${i+1}</td>
      <td>
        <span class="tag tag-blue">${esc(r.kode_produk||'—')}</span>
        <span style="font-weight:600;margin-left:6px">${esc(r.nama_produk)}</span>
      </td>
      <td class="tr mono c-blue">${fmtN(r.total_batch)}</td>
      <td class="tr mono c-green" style="font-weight:bold">${fmtN(r.total_kemasan)} pcs</td>
      <td class="tr mono" style="color:#6366f1">${fmtRp(r.hpp_total)}</td>
      <td class="tr mono c-red">${fmtRp(r.hpp_per_kemasan)}</td>
    </tr>`).join('');
}

function renderBahan(list){
  document.getElementById('cnt-bahan').textContent = list.length+' jenis';
  document.getElementById('tc-bahan').textContent  = list.length;
  bars('chart-bahan', list, 'nama_bahan', 'total_terpakai', '#f59e0b');
  if(!list.length){ document.getElementById('tb-bahan').innerHTML = empty(6); return; }
  const tot = list.reduce((s,r)=>s+(parseFloat(r.estimasi_biaya)||0),0)||1;
  document.getElementById('tb-bahan').innerHTML = list.map((r,i)=>{
    const pct = ((parseFloat(r.estimasi_biaya)||0)/tot*100).toFixed(1);
    return `<tr>
      <td class="mono c-muted" style="font-size:.72rem">${i+1}</td>
      <td style="font-weight:600">${esc(r.nama_bahan)}</td>
      <td class="mono c-muted">${esc(r.satuan)}</td>
      <td class="tr mono c-amber" style="font-weight:bold">${fmtN(r.total_terpakai)}</td>
      <td class="tr mono" style="color:#6366f1">${fmtRp(r.estimasi_biaya)}</td>
      <td class="tr">
        <div class="pct-bar">
          <div class="pct-track"><div class="pct-fill" style="width:${pct}%;background:#6366f1"></div></div>
          <span class="mono" style="font-size:.72rem;color:#6366f1;min-width:38px">${pct}%</span>
        </div>
      </td>
    </tr>`;
  }).join('');
}

function renderHPP(list){
  document.getElementById('cnt-hpp').textContent = list.length+' produk';
  document.getElementById('tc-hpp').textContent  = list.length;
  if(!list.length){
    document.getElementById('hpp-rows').innerHTML = `<div class="empty-state"><i class="bi bi-cash-stack"></i><p>Tidak ada data HPP.</p></div>`;
    return;
  }
  document.getElementById('hpp-rows').innerHTML = list.map(r=>`
    <div class="hpp-row" onclick='showHppDetail(${JSON.stringify(r)})'>
      <div class="hpp-cell">
        <div class="hpp-label">Produk</div>
        <div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap">
          <span class="tag tag-blue">${esc(r.kode_produk||'—')}</span>
          <span style="font-weight:600;font-size:.83rem">${esc(r.nama_produk)}</span>
        </div>
        <div class="hpp-hint"><i class="bi bi-list-ul"></i> lihat detail bahan</div>
      </div>
      <div class="hpp-cell" style="text-align:right">
        <div class="hpp-label">Picis</div>
        <div class="hpp-val c-green">${fmtN(r.total_kemasan)}</div>
      </div>
      <div class="hpp-cell" style="text-align:right">
        <div class="hpp-label">Biaya Bahan</div>
        <div class="hpp-val c-blue">${fmtRp(r.hpp_bahan)}</div>
      </div>
      <div class="hpp-cell" style="text-align:right">
        <div class="hpp-label">Tenaga + Lain</div>
        <div class="hpp-val c-amber">${fmtRp((parseFloat(r.hpp_tenaga)||0)+(parseFloat(r.hpp_lain)||0))}</div>
      </div>
      <div class="hpp-cell" style="text-align:right">
        <div class="hpp-label">HPP Total</div>
        <div class="hpp-val" style="color:#6366f1">${fmtRp(r.hpp_total)}</div>
      </div>
      <div class="hpp-cell" style="text-align:right">
        <div class="hpp-label">HPP / Picis</div>
        <div class="hpp-val c-red">${fmtRp(r.hpp_per_kemasan)}</div>
      </div>
    </div>`).join('');
}

function showHppDetail(r){
  document.getElementById('hpp-detail-name').textContent = 'Komponen HPP — ' + r.nama_produk;
  const card = document.getElementById('hpp-detail-card');
  card.style.display = 'block';
  const bahan = r.bahan_detail||[];
  if(!bahan.length){ document.getElementById('tb-hpp-detail').innerHTML = empty(6,'Tidak ada detail bahan.'); return; }
  const tot = bahan.reduce((s,b)=>s+(parseFloat(b.subtotal_biaya)||0),0)||1;
  document.getElementById('tb-hpp-detail').innerHTML = bahan.map(b=>{
    const pct = ((parseFloat(b.subtotal_biaya)||0)/tot*100).toFixed(1);
    return `<tr>
      <td style="font-weight:600">${esc(b.nama_bahan)}</td>
      <td class="mono c-muted">${esc(b.satuan)}</td>
      <td class="tr mono c-amber">${fmtN(b.total_terpakai)}</td>
      <td class="tr mono c-muted">${fmtRp(b.harga_per_satuan)}</td>
      <td class="tr mono" style="color:#6366f1">${fmtRp(b.subtotal_biaya)}</td>
      <td class="tr">
        <div class="pct-bar">
          <div class="pct-track"><div class="pct-fill" style="width:${pct}%;background:#4f8ef7"></div></div>
          <span class="mono" style="font-size:.72rem;color:#4f8ef7;min-width:38px">${pct}%</span>
        </div>
      </td>
    </tr>`;
  }).join('');
  card.scrollIntoView({ behavior:'smooth', block:'start' });
}

function exportCSV(){
  if(!lpData){ toast('Muat data dulu.','err'); return; }
  let h=[], rows=[];
  const active = document.querySelector('.pane.active')?.id;
  if(active==='pane-periode'){
    h=['Periode','Batch','Picis','HPP Total','HPP/Picis'];
    rows=(lpData.rekap_periode||[]).map(r=>[r.label,r.total_batch,r.total_kemasan,r.hpp_total,r.hpp_per_kemasan]);
  } else if(active==='pane-produk'){
    h=['Kode','Produk','Batch','Picis','HPP Total','HPP/Picis'];
    rows=(lpData.rekap_produk||[]).map(r=>[r.kode_produk,r.nama_produk,r.total_batch,r.total_kemasan,r.hpp_total,r.hpp_per_kemasan]);
  } else if(active==='pane-bahan'){
    h=['Bahan','Satuan','Total Terpakai','Estimasi Biaya'];
    rows=(lpData.pemakaian_bahan||[]).map(r=>[r.nama_bahan,r.satuan,r.total_terpakai,r.estimasi_biaya]);
  } else {
    h=['Kode','Produk','Picis','Biaya Bahan','Tenaga+Lain','HPP Total','HPP/Picis'];
    rows=(lpData.hpp_aktual||[]).map(r=>[r.kode_produk,r.nama_produk,r.total_kemasan,r.hpp_bahan,(parseFloat(r.hpp_tenaga)||0)+(parseFloat(r.hpp_lain)||0),r.hpp_total,r.hpp_per_kemasan]);
  }
  const csv = [h,...rows].map(r=>r.map(c=>'"'+String(c??'').replace(/"/g,'""')+'"').join(',')).join('\n');
  const a = document.createElement('a');
  a.href = URL.createObjectURL(new Blob(['\uFEFF'+csv],{type:'text/csv;charset=utf-8'}));
  a.download = `laporan_produksi_${active}_${new Date().toISOString().split('T')[0]}.csv`;
  a.click();
  toast('CSV berhasil diunduh!');
}

loadLaporan();
</script>

<?= $this->endSection() ?>