<?= $this->extend('layouts/main') ?>
<?= $this->section('css') ?>
<style>
    .page-header   { display:flex; align-items:center; justify-content:space-between; margin-bottom:28px; flex-wrap:wrap; gap:12px; }
    .page-title    { font-size:1.4rem; font-weight:700; color:var(--text-main); display:flex; align-items:center; gap:10px; }
    .page-title i  { color:var(--accent); }
    .page-subtitle { font-size:.82rem; color:var(--text-muted); margin-top:4px; }

    /* Stats */
    .stats-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(170px,1fr)); gap:14px; margin-bottom:28px; }
    .stat-card  { background:var(--bg-side); border:1px solid var(--border); border-radius:14px; padding:20px 22px; box-shadow:var(--shadow); transition:box-shadow .2s, transform .2s; }
    .stat-card:hover { box-shadow:0 6px 20px rgba(0,0,0,.08); transform:translateY(-2px); }
    .stat-ico   { width:38px; height:38px; border-radius:10px; display:flex; align-items:center; justify-content:center; font-size:16px; margin-bottom:12px; }
    .stat-ico.blue  { background:var(--accent-soft); color:var(--accent); }
    .stat-ico.green { background:#dcfce7; color:#16a34a; }
    .stat-ico.amber { background:#fef3c7; color:#d97706; }
    .stat-ico.red   { background:#fee2e2; color:#dc2626; }
    .stat-val   { font-size:1.5rem; font-weight:700; color:var(--text-main); }
    .stat-label { font-size:.7rem; text-transform:uppercase; letter-spacing:.06em; color:var(--text-muted); font-weight:600; margin-top:4px; }

    /* Card & table */
    .card { background:var(--bg-side); border:1px solid var(--border); border-radius:16px; box-shadow:var(--shadow); overflow:hidden; margin-bottom:20px; }
    .card-head  { padding:14px 22px; border-bottom:1px solid var(--border); display:flex; align-items:center; justify-content:space-between; gap:12px; background:var(--bg-card2); flex-wrap:wrap; }
    .card-title { font-size:.9rem; font-weight:700; color:var(--text-main); display:flex; align-items:center; gap:8px; }
    .card-count { font-size:.72rem; color:var(--text-muted); background:var(--bg-card2); border:1px solid var(--border); padding:3px 10px; border-radius:20px; }

    table.pr-tbl { width:100%; border-collapse:collapse; font-size:.82rem; }
    table.pr-tbl thead th { background:var(--bg-card2); color:var(--text-muted); font-size:.67rem; text-transform:uppercase; letter-spacing:.07em; padding:11px 16px; border-bottom:1px solid var(--border); white-space:nowrap; }
    table.pr-tbl thead th.tr { text-align:right; }
    table.pr-tbl tbody td   { padding:13px 16px; border-bottom:1px solid var(--border); color:var(--text-main); vertical-align:middle; }
    table.pr-tbl tbody tr:last-child td { border-bottom:none; }
    table.pr-tbl tbody tr:hover td { background:var(--bg-card2); }
    .tr { text-align:right; }

    /* Bahan detail expandable row */
    .bahan-detail { display:none; background:var(--bg-card2); padding:11px 16px 11px 38px; border-bottom:1px solid var(--border); }
    .bahan-detail.open { display:block; }
    .bahan-chip { display:inline-flex; align-items:center; gap:5px; background:var(--accent-soft); color:var(--accent); border:1px solid #c7d7fc; border-radius:20px; padding:3px 10px; font-size:.72rem; font-weight:600; margin:3px 3px 3px 0; }

    /* Badges */
    .badge { display:inline-flex; align-items:center; padding:3px 10px; border-radius:20px; font-size:.69rem; font-weight:700; text-transform:uppercase; }
    .badge-ok  { background:#dcfce7; color:#15803d; }
    .badge-red { background:#fee2e2; color:#b91c1c; }

    /* Code tag */
    .code-tag { background:var(--accent-soft); color:var(--accent); padding:2px 8px; border-radius:6px; font-size:.73rem; font-weight:700; }

    /* Buttons */
    .btn-primary   { background:var(--accent); color:#fff; border:none; border-radius:10px; padding:9px 18px; font-size:.82rem; font-weight:700; cursor:pointer; display:inline-flex; align-items:center; gap:7px; transition:all .2s; }
    .btn-primary:hover:not(:disabled) { background:#2859e0; box-shadow:0 4px 14px rgba(59,111,245,.25); }
    .btn-primary:disabled { opacity:.6; cursor:not-allowed; }
    .btn-toggle { background:transparent; border:1px solid var(--border); color:var(--text-muted); padding:5px 11px; border-radius:20px; font-size:.73rem; font-weight:600; cursor:pointer; display:inline-flex; align-items:center; gap:5px; transition:all .18s; }
    .btn-toggle.blue { border-color:#c7d7fc; color:var(--accent); background:var(--accent-soft); }
    .btn-toggle.blue:hover { background:var(--accent); color:#fff; }
    .btn-toggle.red  { border-color:#fca5a5; color:#dc2626; background:#fff5f5; }
    .btn-toggle.red:hover  { background:#fee2e2; }

    /* Empty */
    .pr-empty { text-align:center; padding:52px 24px; color:var(--text-muted); }
    .pr-empty i { font-size:2.4rem; opacity:.2; display:block; margin-bottom:14px; }
    .pr-empty p { font-size:.84rem; }

    /* Skeleton */
    .skel { background:linear-gradient(90deg,var(--bg-card2) 25%,var(--border) 50%,var(--bg-card2) 75%); background-size:200% 100%; animation:skel-anim 1.4s infinite; border-radius:6px; }
    .skel-row { display:flex; gap:12px; margin-bottom:11px; align-items:center; }
    @keyframes skel-anim { 0%{background-position:200% 0} 100%{background-position:-200% 0} }

    /* Error state */
    .pr-error { text-align:center; padding:40px 24px; }
    .pr-error .err-title { font-weight:700; color:#dc2626; font-size:1rem; margin-bottom:6px; }
    .pr-error .err-msg   { font-size:.8rem; color:var(--text-muted); margin-bottom:14px; max-width:400px; margin-left:auto; margin-right:auto; }
    .pr-error .err-code  { font-size:.72rem; background:#fff5f5; border:1px solid #fca5a5; border-radius:8px; padding:10px 14px; color:#991b1b; max-width:480px; margin:0 auto 14px; word-break:break-all; text-align:left; }

    /* Modal */
    .modal-overlay { display:none; position:fixed; inset:0; z-index:600; background:rgba(15,22,35,.45); backdrop-filter:blur(4px); align-items:flex-start; justify-content:center; opacity:0; transition:opacity .22s; overflow-y:auto; padding:24px 16px; }
    .modal-overlay.visible { display:flex; }
    .modal-overlay.shown   { opacity:1; }
    .modal-overlay.closing { opacity:0; transition:opacity .18s; }
    .modal-box { background:#fff; border:1px solid var(--border); border-radius:20px; padding:28px 30px; max-width:640px; width:100%; box-shadow:0 20px 60px rgba(0,0,0,.14); transform:scale(.93) translateY(14px); opacity:0; transition:transform .28s cubic-bezier(.34,1.38,.64,1), opacity .22s; margin:auto; }
    .modal-overlay.shown   .modal-box { transform:scale(1) translateY(0); opacity:1; }
    .modal-overlay.closing .modal-box { transform:scale(.95) translateY(8px); opacity:0; transition:transform .16s ease-in, opacity .15s ease-in; }

    .modal-head  { display:flex; align-items:center; gap:13px; margin-bottom:22px; }
    .modal-ico   { width:46px; height:46px; border-radius:13px; flex-shrink:0; display:flex; align-items:center; justify-content:center; font-size:20px; }
    .modal-title { font-size:1.08rem; font-weight:700; color:var(--text-main); margin:0; }
    .modal-sub   { font-size:.78rem; color:var(--text-muted); margin-top:3px; }

    /* Form */
    .f-row      { display:grid; grid-template-columns:1fr 1fr; gap:14px; margin-bottom:14px; }
    .f-row.full { grid-template-columns:1fr; }
    .f-group { display:flex; flex-direction:column; gap:6px; }
    .f-group label { font-size:.69rem; font-weight:600; text-transform:uppercase; letter-spacing:.07em; color:var(--text-muted); }
    .f-group input, .f-group select, .f-group textarea { padding:10px 13px; border:1.5px solid var(--border); border-radius:10px; background:var(--bg-card2); color:var(--text-main); font-size:.85rem; outline:none; transition:border-color .18s, box-shadow .18s; width:100%; box-sizing:border-box; }
    .f-group input:focus, .f-group select:focus { border-color:var(--accent); background:#fff; box-shadow:0 0 0 3px rgba(59,111,245,.1); }
    .f-group input.invalid, .f-group select.invalid { border-color:#dc2626!important; background:#fff5f5!important; }

    /* Resep list */
    .resep-list-wrap { background:var(--bg-card2); border:1px solid var(--border); border-radius:12px; padding:14px 16px; margin-bottom:14px; display:none; }
    .resep-list-wrap.show { display:block; }
    .resep-list-lbl  { font-size:.7rem; font-weight:700; text-transform:uppercase; letter-spacing:.07em; color:var(--text-muted); margin-bottom:12px; display:flex; align-items:center; gap:6px; }
    .resep-list-empty { text-align:center; padding:18px; font-size:.8rem; color:var(--text-muted); }
    .resep-list { display:flex; flex-direction:column; gap:8px; }
    .resep-item { padding:12px 14px; background:#fff; border:1.5px solid var(--border); border-radius:10px; cursor:pointer; transition:all .18s; display:flex; align-items:center; justify-content:space-between; gap:10px; }
    .resep-item:hover { border-color:var(--accent); box-shadow:0 3px 12px rgba(59,111,245,.1); background:var(--accent-soft); }
    .resep-item-name { font-weight:700; font-size:.84rem; color:var(--text-main); }
    .resep-item-info { font-size:.72rem; color:var(--text-muted); margin-top:3px; }
    .btn-pilih { padding:6px 14px; background:var(--accent); color:#fff; border:none; border-radius:8px; font-size:.72rem; font-weight:700; cursor:pointer; transition:all .15s; flex-shrink:0; white-space:nowrap; }
    .btn-pilih:hover { background:#2859e0; }

    /* Resep preview */
    .resep-preview { background:var(--bg-card2); border:1px solid var(--border); border-radius:12px; padding:14px 16px; margin-bottom:14px; display:none; }
    .resep-preview.show { display:block; }
    .resep-preview-lbl { font-size:.7rem; font-weight:700; text-transform:uppercase; letter-spacing:.07em; color:var(--text-muted); margin-bottom:10px; display:flex; align-items:center; gap:6px; }
    .rp-bahan-list { display:flex; flex-wrap:wrap; gap:6px; }
    .rp-chip { display:inline-flex; align-items:center; gap:5px; background:var(--accent-soft); color:var(--accent); border:1px solid #c7d7fc; border-radius:20px; padding:4px 12px; font-size:.75rem; font-weight:600; }
    .rp-chip.warn { background:#fef3c7; color:#92400e; border-color:#fcd34d; }
    .stok-warn { margin-top:10px; font-size:.76rem; color:#d97706; font-weight:600; display:none; align-items:center; gap:6px; }
    .stok-warn.show { display:flex; }

    /* Produksi summary */
    .pr-summary { background:var(--accent-soft); border:1px solid #c7d7fc; border-radius:12px; padding:12px 16px; margin:14px 0; display:grid; grid-template-columns:1fr 1fr; gap:8px; }
    .ps-item  { display:flex; flex-direction:column; gap:3px; }
    .ps-lbl   { font-size:.67rem; text-transform:uppercase; letter-spacing:.07em; color:var(--text-muted); font-weight:600; }
    .ps-val   { font-size:.9rem; font-weight:700; color:var(--accent); }

    /* Divider */
    .m-divider { border:none; border-top:1px solid var(--border); margin:16px 0; }

    /* Modal footer */
    .modal-footer { display:flex; gap:10px; margin-top:20px; }
    .btn-cancel { flex:1; padding:11px; border-radius:10px; border:1px solid var(--border); background:var(--bg-card2); color:var(--text-muted); font-size:.84rem; font-weight:600; cursor:pointer; transition:all .18s; }
    .btn-cancel:hover { background:var(--border); }
    .btn-save-green { flex:2; padding:11px; border-radius:10px; border:none; background:#16a34a; color:#fff; font-size:.84rem; font-weight:700; cursor:pointer; display:inline-flex; align-items:center; justify-content:center; gap:7px; transition:all .2s; }
    .btn-save-green:hover:not(:disabled) { background:#138638; box-shadow:0 4px 14px rgba(22,163,74,.25); }
    .btn-save-green:disabled { opacity:.65; cursor:not-allowed; }

    /* Toast */
    #pr-toast { position:fixed; bottom:24px; right:24px; z-index:9999; padding:13px 17px; border-radius:13px; font-size:.83rem; font-weight:600; display:flex; align-items:center; gap:9px; transform:translateY(70px) scale(.94); opacity:0; transition:all .34s cubic-bezier(.34,1.45,.64,1); max-width:310px; pointer-events:none; box-shadow:var(--shadow); }
    #pr-toast.show { transform:translateY(0) scale(1); opacity:1; }
    #pr-toast.success { background:#fff; border:1px solid #86efac; color:#166534; }
    #pr-toast.error   { background:#fff; border:1px solid #fca5a5; color:#991b1b; }
    #pr-toast .t-ico  { width:26px; height:26px; border-radius:7px; flex-shrink:0; display:flex; align-items:center; justify-content:center; font-size:13px; }
    #pr-toast.success .t-ico { background:#dcfce7; }
    #pr-toast.error   .t-ico { background:#fee2e2; }

    @keyframes shake { 0%,100%{transform:translateX(0)} 20%{transform:translateX(-5px)} 40%{transform:translateX(5px)} 60%{transform:translateX(-3px)} 80%{transform:translateX(3px)} }
    .shake { animation:shake .32s ease; }

    @media(max-width:600px){
        .f-row { grid-template-columns:1fr; }
        .pr-summary { grid-template-columns:1fr; }
        .modal-box { padding:20px 16px; }
    }
</style>
<?= $this->endSection() ?>

<?= $this->section('content') ?>

<!-- Toast -->
<div id="pr-toast"><div class="t-ico" id="pr-t-ico"></div><span id="pr-t-msg"></span></div>

<!-- ══ MODAL CATAT PRODUKSI ══ -->
<div class="modal-overlay" id="modal-produksi">
    <div class="modal-box">
        <div class="modal-head">
            <div class="modal-ico" style="background:#dcfce7">
                <i class="bi bi-gear-fill" style="color:#16a34a"></i>
            </div>
            <div>
                <p class="modal-title">Catat Produksi</p>
                <p class="modal-sub">Pilih produk → resep tampil → pilih resep → bahan otomatis berkurang</p>
            </div>
        </div>

        <div class="f-row">
            <div class="f-group">
                <label>Tanggal Produksi</label>
                <input id="pr-tanggal" type="date">
            </div>
            <div class="f-group">
                <label>Pilih Produk</label>
                <select id="pr-produk">
                    <option value="">— Pilih produk —</option>
                </select>
            </div>
        </div>

        <!-- Resep list -->
        <div class="resep-list-wrap" id="resep-list-wrap">
            <div class="resep-list-lbl">
                <i class="bi bi-book-fill" style="color:var(--accent)"></i> Resep untuk Produk Ini
            </div>
            <div class="resep-list" id="resep-list"></div>
        </div>

        <!-- Jumlah hasil -->
        <div class="f-row" id="jumlah-row" style="display:none">
            <div class="f-group">
                <label>Jumlah Hasil (kemasan)</label>
                <input id="pr-jumlah" type="number" min="1" placeholder="contoh: 20">
            </div>
            <div class="f-group">
                <label style="visibility:hidden">Spacer</label>
                <div style="font-size:.75rem;color:var(--text-muted);align-self:flex-end">Berapa kemasan yang dihasilkan?</div>
            </div>
        </div>

        <!-- Resep preview -->
        <div class="resep-preview" id="resep-preview">
            <div class="resep-preview-lbl">
                <i class="bi bi-basket2-fill" style="color:var(--accent)"></i>
                Bahan dalam Resep
                <span id="rp-catatan" style="font-weight:400;color:var(--text-muted);font-size:.7rem"></span>
            </div>
            <div class="rp-bahan-list" id="rp-bahan-list"></div>
            <div class="stok-warn" id="rp-stok-warn">
                <i class="bi bi-exclamation-triangle-fill"></i>
                <span id="rp-stok-msg">Stok bahan tidak mencukupi.</span>
            </div>
        </div>

        <!-- Summary -->
        <div class="pr-summary" id="pr-summary" style="display:none">
            <div class="ps-item">
                <div class="ps-lbl">Produk</div>
                <div class="ps-val" id="ps-produk">—</div>
            </div>
            <div class="ps-item" style="text-align:right">
                <div class="ps-lbl">Stok Saat Ini</div>
                <div class="ps-val" id="ps-stok-kini">—</div>
            </div>
            <div class="ps-item">
                <div class="ps-lbl">Hasil Produksi</div>
                <div class="ps-val" id="ps-hasil" style="color:#16a34a">—</div>
            </div>
            <div class="ps-item" style="text-align:right">
                <div class="ps-lbl">Stok Setelah</div>
                <div class="ps-val" id="ps-stok-after" style="color:#16a34a">—</div>
            </div>
        </div>

        <div class="f-row full">
            <div class="f-group">
                <label>Catatan <span style="font-weight:400;text-transform:none">(opsional)</span></label>
                <input id="pr-catatan" placeholder="Misal: batch pagi, produksi besar…">
            </div>
        </div>

        <div class="modal-footer">
            <button class="btn-cancel" id="btn-batal-produksi">Batal</button>
            <button class="btn-save-green" id="btn-simpan-produksi">
                <i class="bi bi-check-circle-fill"></i> Jalankan Produksi
            </button>
        </div>
    </div>
</div>

<!-- ══ KONTEN UTAMA ══ -->
<div class="page-header">
    <div>
        <div class="page-title"><i class="bi bi-gear-fill"></i> Produksi</div>
        <p class="page-subtitle">Pilih produk → resep tampil → pilih resep → bahan otomatis berkurang, stok produk bertambah</p>
    </div>
    <div>
        <button class="btn-primary" id="btn-open-produksi" disabled>
            <i class="bi bi-hourglass-split"></i> Memuat…
        </button>
    </div>
</div>

<!-- Stats -->
<div class="stats-grid">
    <div class="stat-card">
        <div class="stat-ico blue"><i class="bi bi-clipboard2-check-fill"></i></div>
        <div class="stat-val" id="s-total">—</div>
        <div class="stat-label">Total Produksi</div>
    </div>
    <div class="stat-card">
        <div class="stat-ico green"><i class="bi bi-check-circle-fill"></i></div>
        <div class="stat-val" id="s-selesai">—</div>
        <div class="stat-label">Selesai</div>
    </div>
    <div class="stat-card">
        <div class="stat-ico amber"><i class="bi bi-calendar-check-fill"></i></div>
        <div class="stat-val" id="s-bulan">—</div>
        <div class="stat-label">Bulan Ini</div>
    </div>
    <div class="stat-card">
        <div class="stat-ico red"><i class="bi bi-x-circle-fill"></i></div>
        <div class="stat-val" id="s-batal">—</div>
        <div class="stat-label">Dibatalkan</div>
    </div>
</div>

<!-- Tabel Produksi -->
<div class="card">
    <div class="card-head">
        <div class="card-title">
            <i class="bi bi-clipboard2-data-fill" style="color:var(--accent)"></i> Riwayat Produksi
        </div>
        <span class="card-count" id="pr-count-label">memuat…</span>
    </div>
    <div style="overflow-x:auto">
        <table class="pr-tbl">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Tanggal</th>
                    <th>Kode</th>
                    <th>Resep</th>
                    <th>Produk</th>
                    <th class="tr">Hasil</th>
                    <th>Bahan Digunakan</th>
                    <th>Status</th>
                    <th class="text-end">Aksi</th>
                </tr>
            </thead>
            <tbody id="tbody-produksi">
                <tr><td colspan="9">
                    <div style="padding:16px 18px">
                        <?php for($i=0;$i<4;$i++): ?>
                        <div class="skel-row">
                            <div class="skel" style="width:24px;height:14px;flex-shrink:0"></div>
                            <div class="skel" style="width:90px;height:14px;flex-shrink:0"></div>
                            <div class="skel" style="width:110px;height:14px;flex-shrink:0"></div>
                            <div class="skel" style="flex:1;height:14px"></div>
                            <div class="skel" style="width:60px;height:14px;flex-shrink:0"></div>
                        </div>
                        <?php endfor; ?>
                    </div>
                </td></tr>
            </tbody>
        </table>
    </div>
</div>

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

<?= $this->section('js') ?>
<script>
const PR_BASE = '<?= base_url() ?>';
let allProduk = [];
let allResep  = [];
let prTT;
let dataLoaded    = false;
let selectedResep = null;

const esc  = s => String(s ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
const fmtD = s => s ? new Date(s+'T00:00:00').toLocaleDateString('id-ID',{day:'2-digit',month:'short',year:'numeric'}) : '—';
const fmtN = n => (parseFloat(n)||0).toLocaleString('id-ID');
function getCsrf(){
    const meta = document.querySelector('meta[name="csrf-token"]');
    if(meta) return meta.getAttribute('content');
    const m = document.cookie.match(/(?:^|;\s*)csrf_token=([^;]*)/);
    return m ? decodeURIComponent(m[1]) : '';
}

/* Toast */
function prToast(msg, type='success'){
    const el = document.getElementById('pr-toast');
    document.getElementById('pr-t-ico').textContent = type==='success' ? '✓' : '✕';
    document.getElementById('pr-t-msg').textContent = msg;
    el.className = 'show '+type;
    clearTimeout(prTT);
    prTT = setTimeout(()=>{ el.className=''; }, 4200);
}

/* Modal */
function openModal(id){
    const el = document.getElementById(id);
    el.classList.add('visible');
    requestAnimationFrame(()=> requestAnimationFrame(()=> el.classList.add('shown')));
}
function closeModal(id){
    const el = document.getElementById(id);
    el.classList.add('closing'); el.classList.remove('shown');
    setTimeout(()=> el.classList.remove('visible','closing'), 210);
}
document.querySelectorAll('.modal-overlay').forEach(el=>{
    el.addEventListener('click', e=>{ if(e.target===el) closeModal(el.id); });
});
document.getElementById('btn-batal-produksi').addEventListener('click', ()=> closeModal('modal-produksi'));

/* POST helper */
async function post(url, body){
    const headers = { 'Content-Type':'application/json', 'X-Requested-With':'XMLHttpRequest' };
    const csrf = getCsrf();
    if(csrf) headers['X-CSRF-TOKEN'] = csrf;
    const res  = await fetch(PR_BASE+url, { method:'POST', headers, body:JSON.stringify(body) });
    const text = await res.text();
    try { return JSON.parse(text); }
    catch { throw new Error('Server error '+res.status); }
}

/* Produk dipilih */
function onProdukChange(){
    const idProduk  = document.getElementById('pr-produk').value;
    const wrap      = document.getElementById('resep-list-wrap');
    const listEl    = document.getElementById('resep-list');

    selectedResep = null;
    document.getElementById('jumlah-row').style.display = 'none';
    document.getElementById('resep-preview').classList.remove('show');
    document.getElementById('pr-summary').style.display = 'none';

    if(!idProduk){ wrap.classList.remove('show'); return; }

    const resepFor = allResep.filter(r => String(r.id_produk) === String(idProduk));
    if(!resepFor.length){
        listEl.innerHTML = '<div class="resep-list-empty">Tidak ada resep untuk produk ini.</div>';
        wrap.classList.add('show'); return;
    }

    listEl.innerHTML = resepFor.map(r => `
        <div class="resep-item">
            <div>
                <div class="resep-item-name">${esc(r.nama_resep)}</div>
                <div class="resep-item-info">${r.catatan_resep ? esc(r.catatan_resep) : 'Tanpa catatan'}</div>
            </div>
            <button class="btn-pilih" type="button" data-nama="${esc(r.nama_resep)}">
                <i class="bi bi-check-lg"></i> Pilih
            </button>
        </div>
    `).join('');

    listEl.querySelectorAll('.btn-pilih').forEach(btn=>{
        btn.addEventListener('click', function(e){
            e.preventDefault();
            selectResep(this.getAttribute('data-nama'));
        });
    });
    wrap.classList.add('show');
}

/* Resep dipilih */
function selectResep(nama){
    const resep = allResep.find(r => r.nama_resep === nama);
    if(!resep) return;
    selectedResep = resep;
    document.getElementById('jumlah-row').style.display = 'grid';
    document.getElementById('pr-jumlah').focus();
    renderResepBahan(resep);
    document.getElementById('resep-preview').classList.add('show');
    updateSummary();
}

/* Preview bahan */
function renderResepBahan(resep){
    const listEl   = document.getElementById('rp-bahan-list');
    const warn     = document.getElementById('rp-stok-warn');
    const warnMsg  = document.getElementById('rp-stok-msg');
    const kurang   = [];

    document.getElementById('rp-catatan').textContent = resep.catatan_resep ? ('— '+resep.catatan_resep) : '';

    listEl.innerHTML = (resep.bahan || []).map(b => {
        const butuh = parseFloat(b.jumlah_bahan);
        const stok  = parseFloat(b.stok_bahan);
        const cukup = stok >= butuh;
        if(!cukup) kurang.push(`${b.nama_bahan} (butuh ${fmtN(butuh)}, stok ${fmtN(stok)} ${b.satuan_bahan})`);
        return `<span class="rp-chip ${cukup ? '' : 'warn'}">
            <i class="bi bi-dot"></i>
            ${esc(b.nama_bahan)} <strong>${fmtN(butuh)} ${esc(b.satuan_bahan)}</strong>
            ${cukup ? '' : '<i class="bi bi-exclamation-circle-fill" style="color:#d97706"></i>'}
        </span>`;
    }).join('');

    if(kurang.length){
        warnMsg.textContent = 'Stok kurang: '+kurang.join('; ');
        warn.classList.add('show');
    } else {
        warn.classList.remove('show');
    }
}

/* Update summary */
function updateSummary(){
    const idProduk = document.getElementById('pr-produk').value;
    const jumlah   = parseInt(document.getElementById('pr-jumlah').value)||0;
    const produk   = allProduk.find(p => String(p.id) === String(idProduk));
    const summEl   = document.getElementById('pr-summary');
    if(!produk || !jumlah){ summEl.style.display='none'; return; }
    const stokKini = parseInt(produk.stok)||0;
    document.getElementById('ps-produk').textContent    = produk.nama;
    document.getElementById('ps-stok-kini').textContent = fmtN(stokKini)+' pcs';
    document.getElementById('ps-hasil').textContent     = '+'+fmtN(jumlah)+' pcs';
    document.getElementById('ps-stok-after').textContent= fmtN(stokKini+jumlah)+' pcs';
    summEl.style.display = 'grid';
}

/* Buka modal */
function openModalProduksi(){
    if(!dataLoaded){ prToast('Data belum selesai dimuat.','error'); return; }
    document.getElementById('pr-tanggal').value = new Date().toISOString().split('T')[0];
    document.getElementById('pr-produk').value  = '';
    document.getElementById('pr-jumlah').value  = '';
    document.getElementById('pr-catatan').value = '';
    document.getElementById('resep-preview').classList.remove('show');
    document.getElementById('resep-list-wrap').classList.remove('show');
    document.getElementById('jumlah-row').style.display = 'none';
    document.getElementById('pr-summary').style.display = 'none';
    document.getElementById('rp-stok-warn').classList.remove('show');
    selectedResep = null;

    const sel = document.getElementById('pr-produk');
    sel.innerHTML = '<option value="">— Pilih produk —</option>' +
        allProduk.map(p =>
            `<option value="${p.id}">${esc(p.nama)} (stok: ${fmtN(p.stok)} pcs)</option>`
        ).join('');

    openModal('modal-produksi');
    setTimeout(()=> document.getElementById('pr-produk').focus(), 60);
}

document.getElementById('pr-produk').addEventListener('change', onProdukChange);
document.getElementById('pr-jumlah').addEventListener('input',  updateSummary);
document.getElementById('btn-open-produksi').addEventListener('click', openModalProduksi);

/* Submit produksi */
document.getElementById('btn-simpan-produksi').addEventListener('click', async function(){
    const namaResep = selectedResep?.nama_resep;
    const idProduk  = document.getElementById('pr-produk').value;
    const jumlah    = document.getElementById('pr-jumlah').value;
    const tanggal   = document.getElementById('pr-tanggal').value;
    const catatan   = document.getElementById('pr-catatan').value;

    if(!namaResep){ prToast('Pilih resep terlebih dahulu.','error'); return; }
    if(!idProduk) { prToast('Pilih produk yang dihasilkan.','error'); return; }
    if(!jumlah || parseInt(jumlah)<1){ prToast('Jumlah hasil harus > 0.','error'); return; }

    if(document.getElementById('rp-stok-warn').classList.contains('show')){
        if(!confirm('Stok beberapa bahan tidak mencukupi. Lanjutkan tetap?')) return;
    }

    this.disabled = true;
    this.innerHTML = '<i class="bi bi-hourglass-split"></i> Memproses…';
    try {
        const res = await post('produksi/simpan', { nama_resep:namaResep, id_produk:idProduk, jumlah_hasil:jumlah, tanggal, catatan });
        if(res.success){
            closeModal('modal-produksi');
            prToast(res.message || 'Produksi berhasil dicatat!');
            loadData();
        } else {
            prToast(res.error || 'Terjadi kesalahan.','error');
        }
    } catch(e){
        prToast(e.message || 'Koneksi gagal.','error');
    }
    this.disabled = false;
    this.innerHTML = '<i class="bi bi-check-circle-fill"></i> Jalankan Produksi';
});

/* Batalkan */
async function batalkanProduksi(id, kode){
    if(!confirm(`Batalkan produksi "${kode}"?\nStok bahan dikembalikan & stok produk dikurangi.`)) return;
    try {
        const res = await post('produksi/batalkan', { id });
        if(res.success){ prToast(res.message); loadData(); }
        else prToast(res.error || 'Gagal membatalkan.','error');
    } catch(e){ prToast(e.message || 'Koneksi gagal.','error'); }
}

function toggleDetail(id){
    document.getElementById('detail-'+id)?.classList.toggle('open');
}

/* Render error */
function renderError(msg){
    document.getElementById('pr-count-label').textContent = 'gagal memuat';
    document.getElementById('tbody-produksi').innerHTML = `
        <tr><td colspan="9">
            <div class="pr-error">
                <div class="err-title"><i class="bi bi-exclamation-triangle-fill"></i> Gagal memuat data produksi</div>
                <div class="err-msg">Pastikan tabel <code>tb_produksi</code> sudah dibuat, lalu refresh halaman.</div>
                <div class="err-code">${esc(msg)}</div>
                <button class="btn-toggle blue" onclick="loadData()" style="margin:0 auto">
                    <i class="bi bi-arrow-clockwise"></i> Coba Lagi
                </button>
            </div>
        </td></tr>`;
}

/* Render tabel */
function renderProduksi(list){
    document.getElementById('pr-count-label').textContent = list.length+' produksi';
    const tbody = document.getElementById('tbody-produksi');
    if(!list.length){
        tbody.innerHTML = `<tr><td colspan="9"><div class="pr-empty">
            <i class="bi bi-clipboard2-x"></i><p>Belum ada catatan produksi.</p>
        </div></td></tr>`;
        return;
    }
    tbody.innerHTML = list.map((r,i) => {
        const selesai = r.status === 'selesai';
        const bahan   = r.bahan || [];
        const chips   = bahan.map(b =>
            `<span class="bahan-chip"><i class="bi bi-dot"></i>${esc(b.nama_bahan)} <strong>${fmtN(b.jumlah)} ${esc(b.satuan)}</strong></span>`
        ).join('');
        return `
            <tr>
                <td style="font-size:.74rem;color:var(--text-muted)">${i+1}</td>
                <td style="font-size:.78rem;color:var(--text-muted)">${fmtD(r.tanggal)}</td>
                <td><span class="code-tag">${esc(r.kode)}</span></td>
                <td style="font-weight:600">${esc(r.nama_resep||'—')}</td>
                <td>
                    <span class="code-tag">${esc(r.kode_produk||'')}</span>
                    <span style="font-size:.8rem;margin-left:4px">${esc(r.nama_produk||'—')}</span>
                    ${r.catatan ? `<div style="font-size:.72rem;color:var(--text-muted);margin-top:2px">${esc(r.catatan)}</div>` : ''}
                </td>
                <td class="tr" style="font-weight:700;color:#16a34a">+${fmtN(r.jumlah_hasil)} pcs</td>
                <td>
                    ${bahan.length
                        ? `<button class="btn-toggle blue" onclick="toggleDetail(${r.id})">
                               <i class="bi bi-layers-fill"></i> ${bahan.length} bahan
                           </button>`
                        : '<span style="font-size:.74rem;color:var(--text-muted)">—</span>'
                    }
                </td>
                <td>
                    <span class="badge ${selesai ? 'badge-ok' : 'badge-red'}">
                        ${selesai ? 'Selesai' : 'Dibatalkan'}
                    </span>
                </td>
                <td class="text-end">
                    ${selesai
                        ? `<button class="btn-toggle red" onclick='batalkanProduksi(${r.id},"${esc(r.kode)}")'>
                               <i class="bi bi-x-circle"></i> Batal
                           </button>`
                        : '<span style="font-size:.74rem;color:var(--text-muted)">—</span>'
                    }
                </td>
            </tr>
            ${bahan.length ? `
            <tr><td colspan="9" style="padding:0">
                <div class="bahan-detail" id="detail-${r.id}">
                    <strong style="font-size:.72rem;color:var(--text-muted);text-transform:uppercase;letter-spacing:.06em">Bahan digunakan:</strong>
                    <div style="margin-top:6px">${chips}</div>
                </div>
            </td></tr>` : ''}
        `;
    }).join('');
}

/* Load data */
async function loadData(){
    const btnOpen = document.getElementById('btn-open-produksi');
    btnOpen.disabled = true;
    btnOpen.innerHTML = '<i class="bi bi-hourglass-split"></i> Memuat…';
    try {
        const res  = await fetch(PR_BASE+'produksi/data', { headers:{'X-Requested-With':'XMLHttpRequest'} });
        const text = await res.text();
        let d;
        try { d = JSON.parse(text); }
        catch { renderError('Server error '+res.status+'. Cek CI4 log.'); prToast('Gagal memuat data.','error'); return; }
        if(!d.success){ renderError(d.error||'Respons tidak valid.'); prToast('Gagal: '+(d.error||'unknown'),'error'); return; }

        allProduk = Array.isArray(d.produk) ? d.produk : [];
        allResep  = Array.isArray(d.resep)  ? d.resep  : [];
        const list = Array.isArray(d.list)  ? d.list   : [];
        const sum  = d.summary || {};

        document.getElementById('s-total').textContent   = sum.total      ?? 0;
        document.getElementById('s-selesai').textContent = sum.selesai    ?? 0;
        document.getElementById('s-bulan').textContent   = sum.bulan_ini  ?? 0;
        document.getElementById('s-batal').textContent   = sum.dibatalkan ?? 0;

        renderProduksi(list);
        dataLoaded = true;
        btnOpen.disabled = false;
        btnOpen.innerHTML = '<i class="bi bi-plus-lg"></i> Catat Produksi';
    } catch(e){
        renderError(e.message);
        prToast('Koneksi gagal: '+e.message,'error');
        btnOpen.disabled = false;
        btnOpen.innerHTML = '<i class="bi bi-plus-lg"></i> Catat Produksi';
    }
}

document.readyState === 'loading' ? document.addEventListener('DOMContentLoaded', loadData) : loadData();
</script>
<?= $this->endSection() ?>