<?= $this->extend('layouts/main') ?>
<?= $this->section('css') ?>
<style>
    @import url('https://fonts.googleapis.com/css2?family=Sora:wght@400;600;700;800&family=DM+Sans:wght@400;500;600&display=swap');

    .mb-wrap {
        --accent:      #3b6ff5;
        --accent-soft: #eef3ff;
        --bg-side:     #ffffff;
        --bg-card2:    #fafbfe;
        --border:      #e5eaf5;
        --border2:     #cdd5e8;
        --text-main:   #0f1623;
        --text-muted:  #7a849e;
        --shadow:      0 2px 10px rgba(15,22,35,.05);
        --green:       #16a34a;
        --amber:       #d97706;
        --red:         #dc2626;
        --r:           16px;
        --r-sm:        10px;
        font-family: 'DM Sans', sans-serif;
        color: var(--text-main);
    }

    .mb-wrap .page-header {
        display: flex; align-items: flex-start; justify-content: space-between;
        flex-wrap: wrap; gap: 16px; margin-bottom: 28px;
    }
    .mb-wrap .page-title {
        font-family: 'Sora', sans-serif;
        font-size: 1.4rem; font-weight: 800; color: var(--text-main);
        display: flex; align-items: center; gap: 10px; margin: 0;
        letter-spacing: -0.5px;
    }
    .mb-wrap .page-title i { color: var(--accent); }
    .mb-wrap .page-sub { font-size: 12px; color: var(--text-muted); margin-top: 5px; }
    .mb-wrap .header-btns { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }

    .mb-wrap .stats-grid {
        display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
        gap: 14px; margin-bottom: 28px;
    }
    .mb-wrap .stat-card {
        background: var(--bg-side); border: 1px solid var(--border);
        border-radius: var(--r); padding: 20px 22px;
        box-shadow: var(--shadow);
        transition: box-shadow .2s, transform .2s; cursor: default;
    }
    .mb-wrap .stat-card:hover {
        box-shadow: 0 6px 20px rgba(59,111,245,.1); transform: translateY(-2px);
    }
    .mb-wrap .stat-ico {
        width: 40px; height: 40px; border-radius: 11px;
        display: flex; align-items: center; justify-content: center;
        font-size: 16px; margin-bottom: 14px;
    }
    .mb-wrap .ic-b { background: #eef3ff; color: var(--accent); }
    .mb-wrap .ic-g { background: #dcfce7; color: var(--green); }
    .mb-wrap .ic-a { background: #fef3c7; color: var(--amber); }
    .mb-wrap .ic-r { background: #fee2e2; color: var(--red); }
    .mb-wrap .stat-val {
        font-family: 'Sora', sans-serif; font-size: 1.45rem; font-weight: 700; color: var(--text-main);
    }
    .mb-wrap .stat-label {
        font-size: 11px; text-transform: uppercase; letter-spacing: .08em;
        color: var(--text-muted); font-weight: 600; margin-top: 5px;
    }

    .mb-wrap .card {
        background: var(--bg-side); border: 1px solid var(--border);
        border-radius: var(--r); overflow: hidden; margin-bottom: 20px;
        box-shadow: var(--shadow);
    }
    .mb-wrap .card-head {
        padding: 15px 22px; border-bottom: 1px solid var(--border);
        display: flex; align-items: center; justify-content: space-between; gap: 12px;
        background: var(--bg-card2);
    }
    .mb-wrap .card-title {
        display: flex; align-items: center; gap: 8px;
        font-family: 'Sora', sans-serif; font-size: .9rem; font-weight: 700; color: var(--text-main);
    }
    .mb-wrap .count-badge {
        font-size: 11px; color: var(--text-muted);
        background: #f0f2f9; padding: 3px 10px; border-radius: 20px; font-weight: 600;
    }

    .mb-wrap .tabs {
        display: flex; border-bottom: 2px solid var(--border); margin-bottom: 20px; gap: 2px; flex-wrap: wrap;
    }
    .mb-wrap .tab {
        padding: 10px 20px; background: none; border: none;
        font-family: 'DM Sans', sans-serif; font-size: 13px; font-weight: 600;
        color: var(--text-muted); cursor: pointer;
        border-bottom: 2px solid transparent; margin-bottom: -2px;
        transition: color .18s, border-color .18s;
        display: inline-flex; align-items: center; gap: 6px;
    }
    .mb-wrap .tab.active { color: var(--accent); border-bottom-color: var(--accent); }
    .mb-wrap .tab:hover:not(.active) { color: var(--text-main); }

    .mb-wrap .tbl-wrap { overflow-x: auto; }
    .mb-wrap table { width: 100%; border-collapse: collapse; }
    .mb-wrap thead th {
        background: var(--bg-card2); color: var(--text-muted);
        font-size: 11px; text-transform: uppercase; letter-spacing: .05em;
        padding: 12px 18px; border-bottom: 1px solid var(--border);
        font-weight: 600; white-space: nowrap;
    }
    .mb-wrap thead th.text-end { text-align: right; }
    .mb-wrap tbody td {
        padding: 14px 18px; border-bottom: 1px solid #f0f2f9;
        font-size: 13px; color: var(--text-main);
        vertical-align: middle; white-space: nowrap;
    }
    .mb-wrap tbody tr:last-child td { border-bottom: none; }
    .mb-wrap tbody tr:hover td { background: #f6f9ff; }

    .mb-wrap .badge-status {
        padding: 4px 10px; border-radius: 20px;
        font-size: 11px; font-weight: 700; text-transform: uppercase;
        display: inline-flex; align-items: center;
    }
    .mb-wrap .b-ok  { background: #dcfce7; color: #15803d; }
    .mb-wrap .b-w   { background: #fef3c7; color: #b45309; }
    .mb-wrap .b-r   { background: #fee2e2; color: #b91c1c; }
    .mb-wrap .b-na  { background: #f1f5f9; color: #64748b; }

    /* Stok pill — angka + satuan dalam satu blok */
    .mb-wrap .stok-pill {
        display: inline-flex; align-items: center; gap: 4px;
    }
    .mb-wrap .stok-num {
        font-family: 'Courier New', monospace; font-size: 12px; font-weight: 700;
    }
    .mb-wrap .stok-sat {
        font-size: 11px; color: var(--text-muted); font-weight: 500;
    }
    .mb-wrap .stok-bar { display: flex; align-items: center; gap: 8px; justify-content: flex-end; }
    .mb-wrap .stok-track { width: 52px; height: 5px; background: #e8ecf4; border-radius: 99px; }
    .mb-wrap .stok-fill  { height: 100%; border-radius: 99px; }

    .mb-wrap .btn-primary {
        background: var(--accent); color: #fff; border: none;
        border-radius: var(--r-sm); padding: 9px 18px;
        font-size: 13px; font-weight: 600; cursor: pointer;
        display: inline-flex; align-items: center; gap: 7px;
        font-family: 'DM Sans', sans-serif; transition: all .2s; white-space: nowrap;
    }
    .mb-wrap .btn-primary:hover {
        background: #2859e0; box-shadow: 0 4px 14px rgba(59,111,245,.28);
    }
    .mb-wrap .btn-link-alt {
        background: #f8fafc; color: var(--text-main); border: 1px solid var(--border2);
        border-radius: var(--r-sm); padding: 9px 18px;
        font-size: 13px; font-weight: 600; cursor: pointer;
        display: inline-flex; align-items: center; gap: 7px;
        font-family: 'DM Sans', sans-serif; transition: all .2s; text-decoration: none;
    }
    .mb-wrap .btn-link-alt:hover {
        background: var(--accent-soft); border-color: var(--accent); color: var(--accent);
    }
    .mb-wrap .btn-toggle {
        background: transparent; border: 1px solid var(--border);
        color: var(--text-muted); padding: 6px 10px;
        border-radius: var(--r-sm); font-size: 12px;
        cursor: pointer; transition: all .2s;
        display: inline-flex; align-items: center; gap: 4px;
    }
    .mb-wrap .btn-toggle:hover { border-color: var(--accent); color: var(--accent); background: var(--accent-soft); }
    .mb-wrap .btn-toggle.danger:hover { border-color: var(--red); color: var(--red); background: #fee2e2; }
    .mb-wrap .btn-toggle.success:hover { border-color: var(--green); color: var(--green); background: #dcfce7; }
    .mb-wrap .btn-toggle.amber:hover { border-color: var(--amber); color: var(--amber); background: #fef3c7; }

    .mb-wrap .trash-banner {
        background: #fffbeb; border: 1.5px solid #fcd34d;
        border-radius: var(--r); padding: 14px 20px; margin-bottom: 20px;
        display: flex; align-items: center; gap: 12px; flex-wrap: wrap;
    }
    .mb-wrap .trash-banner i { font-size: 1.1rem; color: var(--amber); }
    .mb-wrap .trash-banner p { margin: 0; font-size: 13px; color: #78350f; font-weight: 600; }
    .mb-wrap .trash-banner span { font-size: 12px; color: #92400e; margin-left: 4px; font-weight: 400; }

    .mb-wrap .tab-section { display: none; }
    .mb-wrap .tab-section.active { display: block; }
    .mb-wrap .mono { font-family: 'Courier New', monospace; }
    .mb-wrap .tg { color: var(--green); font-weight: 600; }
    .mb-wrap .ta { color: var(--amber); font-weight: 600; }
    .mb-wrap .tr2 { color: var(--red); font-weight: 600; }
    .mb-wrap .muted { color: var(--text-muted); }
    .mb-wrap .bb-empty { text-align: center; padding: 48px 24px; color: var(--text-muted); }
    .mb-wrap .bb-empty i { font-size: 2rem; opacity: .2; display: block; margin-bottom: 12px; }
    .mb-wrap .bb-empty p { font-size: 13px; margin: 0; }

    /* ── Modal ── */
    .bb-overlay {
        display: none; position: fixed; inset: 0; z-index: 600;
        background: rgba(15,22,35,.42); backdrop-filter: blur(4px);
        align-items: center; justify-content: center;
        opacity: 0; transition: opacity .22s ease;
    }
    .bb-overlay.visible         { display: flex; }
    .bb-overlay.visible.shown   { opacity: 1; }
    .bb-overlay.closing         { opacity: 0; transition: opacity .18s ease-in; }
    .bb-modal {
        background: #ffffff; border: 1px solid var(--border);
        border-radius: 20px; padding: 28px 30px;
        max-width: 460px; width: 94%;
        box-shadow: 0 20px 60px rgba(15,22,35,.14);
        transform: scale(.93) translateY(14px); opacity: 0;
        transition: transform .28s cubic-bezier(.34,1.38,.64,1), opacity .22s ease;
    }
    .bb-overlay.shown   .bb-modal { transform: scale(1) translateY(0); opacity: 1; }
    .bb-overlay.closing .bb-modal {
        transform: scale(.95) translateY(8px); opacity: 0;
        transition: transform .16s ease-in, opacity .15s ease-in;
    }
    .m-head { display: flex; align-items: center; gap: 13px; margin-bottom: 22px; }
    .m-ico  {
        width: 44px; height: 44px; border-radius: 12px; flex-shrink: 0;
        display: flex; align-items: center; justify-content: center; font-size: 18px;
    }
    .m-title { font-family: 'Sora', sans-serif; font-size: 1.05rem; font-weight: 700; color: #0f1623; margin: 0; }
    .m-sub   { font-size: 12px; color: var(--text-muted); margin-top: 2px; }
    .f-row  { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; margin-bottom: 14px; }
    .f-row.full { grid-template-columns: 1fr; }
    .f-grp  { display: flex; flex-direction: column; gap: 6px; }
    .f-grp label {
        font-size: 11px; font-weight: 600; text-transform: uppercase;
        letter-spacing: .07em; color: var(--text-muted);
    }
    .f-grp input, .f-grp select, .f-grp textarea {
        padding: 10px 13px; border: 1.5px solid var(--border);
        border-radius: var(--r-sm); background: #f8faff;
        color: #0f1623; font-family: 'DM Sans', sans-serif; font-size: 14px;
        outline: none; transition: border-color .18s, background .18s, box-shadow .18s;
        box-sizing: border-box; width: 100%;
    }
    .f-grp input:focus, .f-grp select:focus, .f-grp textarea:focus {
        border-color: var(--accent); background: #fff;
        box-shadow: 0 0 0 3px rgba(59,111,245,.1);
    }
    .f-grp textarea { resize: vertical; min-height: 60px; }
    .f-grp input.invalid, .f-grp select.invalid {
        border-color: #dc2626 !important; background: #fff5f5 !important;
        box-shadow: 0 0 0 3px rgba(220,38,38,.1) !important;
    }

    /* Input satuan custom (muncul saat pilih Lainnya) */
    #satuan-custom-wrap {
        margin-top: 8px; display: none;
    }
    #satuan-custom-wrap.visible { display: block; }

    @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; }
    .m-footer { display: flex; gap: 10px; margin-top: 22px; }
    .btn-mc {
        flex: 1; padding: 11px; border-radius: var(--r-sm);
        border: 1.5px solid var(--border2); background: #f2f5fb; color: #4b5675;
        font-size: 13px; font-weight: 600; cursor: pointer; font-family: 'DM Sans', sans-serif;
        transition: all .18s;
    }
    .btn-mc:hover { background: #e5eaf5; color: var(--text-main); border-color: #aab4cc; }
    .btn-ms {
        flex: 2; padding: 11px; border-radius: var(--r-sm); border: none;
        background: var(--accent); color: #fff; font-size: 13px; font-weight: 700; cursor: pointer;
        font-family: 'DM Sans', sans-serif;
        display: inline-flex; align-items: center; justify-content: center; gap: 7px;
        position: relative; overflow: hidden;
        transition: background .2s, box-shadow .2s, transform .15s;
    }
    .btn-ms:hover { background: #2859e0; box-shadow: 0 4px 14px rgba(59,111,245,.28); }
    .btn-ms:active { transform: scale(.96); }
    .btn-ms:disabled { cursor: not-allowed; opacity: .72; }
    .btn-ms .btn-label { display: inline-flex; align-items: center; gap: 7px; transition: opacity .15s, transform .15s; }
    .btn-ms .btn-spin {
        display: none; position: absolute;
        width: 19px; height: 19px; border-radius: 50%;
        border: 2.5px solid rgba(255,255,255,.3); border-top-color: #fff;
        animation: bspin .5s linear infinite;
    }
    @keyframes bspin { to { transform: rotate(360deg); } }
    .btn-ms.loading .btn-label { opacity: 0; transform: scale(.8); }
    .btn-ms.loading .btn-spin  { display: block; }
    .btn-ms.done .btn-label    { opacity: 0; }
    .btn-ms.done::after {
        content: '✓'; position: absolute;
        font-size: 1.15rem; font-weight: 700; color: #fff;
        animation: tickPop .28s cubic-bezier(.34,1.6,.64,1) forwards;
    }
    @keyframes tickPop {
        from { transform: scale(.3) rotate(-20deg); opacity: 0; }
        to   { transform: scale(1) rotate(0deg); opacity: 1; }
    }

    /* ── Toast ── */
    #bb-toast {
        position: fixed; bottom: 24px; right: 24px; z-index: 9999;
        padding: 14px 18px; border-radius: 14px; font-size: 13px; font-weight: 600;
        display: flex; align-items: center; gap: 10px;
        transform: translateY(80px) scale(.94); opacity: 0;
        transition: all .34s cubic-bezier(.34,1.45,.64,1);
        max-width: 320px; pointer-events: none;
        box-shadow: 0 10px 30px rgba(0,0,0,.12); font-family: 'DM Sans', sans-serif;
    }
    #bb-toast.show    { transform: translateY(0) scale(1); opacity: 1; }
    #bb-toast.success { background: #fff; border: 1.5px solid #86efac; color: #166534; }
    #bb-toast.error   { background: #fff; border: 1.5px solid #fca5a5; color: #991b1b; }
    .t-ico {
        width: 28px; height: 28px; border-radius: 8px; flex-shrink: 0;
        display: flex; align-items: center; justify-content: center; font-size: 14px;
    }
    #bb-toast.success .t-ico { background: #dcfce7; }
    #bb-toast.error   .t-ico { background: #fee2e2; }
</style>
<?= $this->endSection() ?>

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

<div id="bb-toast"><div class="t-ico" id="t-ico"></div><span id="t-msg"></span></div>

<!-- ════ MODAL: TAMBAH / EDIT BAHAN ════ -->
<div class="bb-overlay" id="modal-bahan">
    <div class="bb-modal">
        <div class="m-head">
            <div class="m-ico ic-b" id="m-bahan-ico" style="font-size:20px">✦</div>
            <div>
                <p class="m-title" id="m-bahan-title">Tambah Bahan</p>
                <p class="m-sub">Isi data master bahan</p>
            </div>
        </div>
        <input type="hidden" id="bahan-id">

        <div class="f-row full">
            <div class="f-grp">
                <label>Nama Bahan</label>
                <input id="bahan-nama" placeholder="Bawang Merah">
            </div>
        </div>

        <div class="f-row full">
            <div class="f-grp">
                <label>Satuan</label>
                <select id="bahan-satuan">
                    <option value="kg">kg</option>
                    <option value="gram">gram</option>
                    <option value="liter">liter</option>
                    <option value="ml">ml</option>
                    <option value="buah">buah</option>
                    <option value="ikat">ikat</option>
                    <option value="pcs">pcs</option>
                    <option value="lusin">lusin</option>
                    <option value="lainnya">Lainnya…</option>
                </select>
                <!-- Input muncul saat "Lainnya…" dipilih -->
                <div id="satuan-custom-wrap">
                    <input id="bahan-satuan-custom" placeholder="Tulis satuan sendiri, misal: pak, roll, botol…">
                </div>
            </div>
        </div>

        <div class="f-row full">
            <div class="f-grp">
                <label>Harga Beli / Satuan (Rp)</label>
                <input id="bahan-harga" type="number" placeholder="28000">
            </div>
        </div>
        <div class="f-row full">
            <div class="f-grp">
                <label>Keterangan</label>
                <textarea id="bahan-ket" placeholder="Opsional…"></textarea>
            </div>
        </div>
        <div class="m-footer">
            <button class="btn-mc" id="btn-batal-bahan">Batal</button>
            <button class="btn-ms" id="btn-simpan-bahan">
                <span class="btn-label"><i class="bi bi-check-lg"></i> Simpan Bahan</span>
                <span class="btn-spin"></span>
            </button>
        </div>
    </div>
</div>

<!-- ════ KONTEN UTAMA ════ -->
<div class="mb-wrap">

    <div class="page-header">
        <div>
            <h1 class="page-title"><i class="bi bi-basket3-fill"></i> Manajemen Bahan</h1>
            <p class="page-sub">Stok dan penggunaan seluruh bahan produksi</p>
        </div>
        <div class="header-btns">
            <a href="<?= base_url('pembelian-bahan') ?>" class="btn-link-alt">
                <i class="bi bi-cart-check-fill"></i> Pembelian Bahan
            </a>
            <button class="btn-primary" id="btn-open-bahan">
                <i class="bi bi-plus-lg"></i> Tambah Bahan
            </button>
        </div>
    </div>

    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-ico ic-b"><i class="bi bi-basket2-fill"></i></div>
            <div class="stat-val" id="s-jenis">—</div>
            <div class="stat-label">Jenis Bahan</div>
        </div>
        <div class="stat-card">
            <div class="stat-ico ic-g"><i class="bi bi-currency-dollar"></i></div>
            <div class="stat-val" id="s-nilai">—</div>
            <div class="stat-label">Nilai Stok</div>
        </div>
        <div class="stat-card">
            <div class="stat-ico ic-a"><i class="bi bi-bag-check-fill"></i></div>
            <div class="stat-val" id="s-beli">—</div>
            <div class="stat-label">Total Pembelian</div>
        </div>
        <div class="stat-card">
            <div class="stat-ico ic-r"><i class="bi bi-exclamation-triangle-fill"></i></div>
            <div class="stat-val" id="s-nipis">—</div>
            <div class="stat-label">Stok Sedikit (≤5)</div>
        </div>
    </div>

    <div class="tabs">
        <button class="tab active" data-tab="stok">
            <i class="bi bi-list-ul"></i> Stok Bahan
        </button>
        <button class="tab" data-tab="pakai">
            <i class="bi bi-fire"></i> Riwayat Penggunaan
        </button>
        <button class="tab" data-tab="trash">
            <i class="bi bi-trash3"></i> Bahan Dihapus
            <span class="count-badge" id="trash-count" style="margin-left:2px">0</span>
        </button>
    </div>

    <!-- Tab: Stok -->
    <div id="tab-stok" class="tab-section active">
        <div class="card">
            <div class="card-head">
                <div class="card-title">
                    <i class="bi bi-basket3-fill" style="color:var(--accent)"></i> Daftar Bahan
                </div>
                <span class="count-badge" id="stok-label">memuat…</span>
            </div>
            <div class="tbl-wrap">
                <table>
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Nama Bahan</th>
                            <th class="text-end">Stok</th>
                            <th class="text-end">Harga/Sat.</th>
                            <th class="text-end">Nilai Stok</th>
                            <th>Status</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody id="tbody-stok"></tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Tab: Pakai -->
    <div id="tab-pakai" class="tab-section">
        <div class="card">
            <div class="card-head">
                <div class="card-title">
                    <i class="bi bi-fire-fill" style="color:var(--red)"></i> Riwayat Penggunaan
                </div>
                <span class="count-badge" id="pakai-label">—</span>
            </div>
            <div class="tbl-wrap">
                <table>
                    <thead>
                        <tr>
                            <th>Tanggal</th>
                            <th>Bahan</th>
                            <th class="text-end">Jumlah</th>
                            <th>Keperluan</th>
                            <th>Catatan</th>
                        </tr>
                    </thead>
                    <tbody id="tbody-pakai"></tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Tab: Trash -->
    <div id="tab-trash" class="tab-section">
        <div class="trash-banner">
            <i class="bi bi-info-circle-fill"></i>
            <p>Bahan yang dihapus (soft delete)
                <span>— data tidak benar-benar hilang, klik Pulihkan untuk mengembalikan.</span>
            </p>
        </div>
        <div class="card">
            <div class="card-head">
                <div class="card-title">
                    <i class="bi bi-trash3-fill" style="color:var(--amber)"></i> Bahan Terhapus
                </div>
                <span class="count-badge" id="trash-label">—</span>
            </div>
            <div class="tbl-wrap">
                <table>
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Nama Bahan</th>
                            <th class="text-end">Stok Saat Dihapus</th>
                            <th class="text-end">Harga/Sat.</th>
                            <th>Keterangan</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody id="tbody-trash"></tbody>
                </table>
            </div>
        </div>
    </div>

</div>

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

<?= $this->section('js') ?>
<script>
const BB_BASE = '<?= base_url() ?>';
let allBahan = [];
let allTrash = [];
let bbTT;

/* Daftar satuan bawaan — untuk cek apakah satuan tersimpan perlu mode "Lainnya" */
const SATUAN_DEFAULT = ['kg','gram','liter','ml','buah','ikat','pcs','lusin'];

const fmt  = n => 'Rp ' + (parseFloat(n)||0).toLocaleString('id-ID');
const fmtK = n => {
    const v = parseFloat(n) || 0;
    if (v >= 1e9) return 'Rp ' + (v/1e9).toFixed(2) + ' M';
    if (v >= 1e6) return 'Rp ' + (v/1e6).toFixed(1) + ' Jt';
    if (v >= 1e3) return 'Rp ' + (v/1e3).toFixed(0) + ' Rb';
    return 'Rp ' + v.toLocaleString('id-ID');
};
const fmtN = (n, s='') => (parseFloat(n)||0).toLocaleString('id-ID') + (s ? ' '+s : '');
const esc  = s => String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
const fmtD = s => s ? new Date(s).toLocaleDateString('id-ID', {day:'2-digit', month:'short', year:'numeric'}) : '—';

function getCsrf() {
    return document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') ?? '';
}

/* ── Toast ── */
function showToast(msg, type='success') {
    const el = document.getElementById('bb-toast');
    document.getElementById('t-ico').textContent = type === 'success' ? '✓' : '✕';
    document.getElementById('t-msg').textContent = msg;
    el.className = 'show ' + type;
    clearTimeout(bbTT);
    bbTT = setTimeout(() => { el.className = ''; }, 3600);
}

/* ── Tabs ── */
document.querySelectorAll('.tab').forEach(btn => {
    btn.addEventListener('click', function() {
        const name = this.dataset.tab;
        document.querySelectorAll('.tab-section').forEach(s => s.classList.remove('active'));
        document.querySelectorAll('.tab').forEach(b => b.classList.remove('active'));
        document.getElementById('tab-' + name).classList.add('active');
        this.classList.add('active');
    });
});

/* ── Modal helpers ── */
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('.bb-overlay').forEach(el => {
    el.addEventListener('click', e => { if (e.target === el) closeModal(el.id); });
});
document.getElementById('btn-batal-bahan').addEventListener('click', () => closeModal('modal-bahan'));

/* ── Button states ── */
function btnLoading(btn) { btn.disabled = true; btn.classList.add('loading'); }
function btnSuccess(btn) {
    btn.classList.remove('loading'); btn.classList.add('done');
    setTimeout(() => { btn.classList.remove('done'); btn.disabled = false; }, 950);
}
function btnError(btn) {
    btn.classList.remove('loading'); btn.disabled = false;
    btn.classList.add('shake');
    setTimeout(() => btn.classList.remove('shake'), 380);
}

/* ── Validasi ── */
function validateFields(ids) {
    let firstBad = null;
    ids.forEach(id => {
        const el  = document.getElementById(id);
        const bad = !el.value.trim() || (el.type === 'number' && parseFloat(el.value) <= 0);
        if (bad) {
            el.classList.add('invalid', 'shake');
            setTimeout(() => el.classList.remove('shake'), 380);
            if (!firstBad) { firstBad = el; el.focus(); }
        } else {
            el.classList.remove('invalid');
        }
    });
    return !firstBad;
}
document.addEventListener('input', e => {
    if (e.target.classList.contains('invalid') && e.target.value.trim())
        e.target.classList.remove('invalid');
});

/* ── Logika dropdown Satuan + input Lainnya ── */
const selSatuan     = document.getElementById('bahan-satuan');
const customWrap    = document.getElementById('satuan-custom-wrap');
const inputCustom   = document.getElementById('bahan-satuan-custom');

function toggleCustomSatuan() {
    if (selSatuan.value === 'lainnya') {
        customWrap.classList.add('visible');
        inputCustom.focus();
    } else {
        customWrap.classList.remove('visible');
        inputCustom.value = '';
    }
}
selSatuan.addEventListener('change', toggleCustomSatuan);

/* Kembalikan nilai satuan final (dari select atau custom input) */
function getSatuanFinal() {
    if (selSatuan.value === 'lainnya') {
        return inputCustom.value.trim();
    }
    return selSatuan.value;
}

/* Set nilai satuan di form — termasuk handle satuan non-default */
function setSatuanForm(val) {
    if (!val) { selSatuan.value = 'kg'; toggleCustomSatuan(); return; }
    if (SATUAN_DEFAULT.includes(val)) {
        selSatuan.value = val;
        customWrap.classList.remove('visible');
        inputCustom.value = '';
    } else {
        selSatuan.value    = 'lainnya';
        inputCustom.value  = val;
        customWrap.classList.add('visible');
    }
}

/* ── Open modal bahan ── */
function openModalBahan(row = null) {
    document.getElementById('bahan-id').value    = row ? row.id_bahan         : '';
    document.getElementById('bahan-nama').value  = row ? row.nama_bahan       : '';
    document.getElementById('bahan-harga').value = row ? row.harga_bahan      : '';
    document.getElementById('bahan-ket').value   = row ? row.keterangan_bahan : '';
    setSatuanForm(row ? row.satuan_bahan : 'kg');
    document.getElementById('m-bahan-title').textContent = row ? 'Edit Bahan' : 'Tambah Bahan';
    document.getElementById('m-bahan-ico').textContent   = row ? '✎'          : '✦';
    document.getElementById('bahan-nama').classList.remove('invalid');
    openModal('modal-bahan');
}
function openModalBahanFromId(id) {
    const row = allBahan.find(b => b.id_bahan == id);
    if (row) openModalBahan(row);
}
document.getElementById('btn-open-bahan').addEventListener('click', () => openModalBahan());

/* ── Fetch helper ── */
async function post(url, body) {
    const r = await fetch(BB_BASE + url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest',
            'X-CSRF-TOKEN': getCsrf(),
        },
        body: JSON.stringify(body),
    });
    return r.json();
}

/* ── Simpan bahan ── */
async function simpanBahan(btn) {
    const satuanFinal = getSatuanFinal();

    /* Validasi nama */
    if (!validateFields(['bahan-nama'])) return;

    /* Validasi custom satuan jika pilih Lainnya */
    if (selSatuan.value === 'lainnya' && !satuanFinal) {
        inputCustom.classList.add('invalid', 'shake');
        setTimeout(() => inputCustom.classList.remove('shake'), 380);
        inputCustom.focus();
        return;
    }

    btnLoading(btn);
    try {
        const res = await post('bahan/simpan', {
            id_bahan:         document.getElementById('bahan-id').value,
            nama_bahan:       document.getElementById('bahan-nama').value,
            satuan_bahan:     satuanFinal,
            harga_bahan:      document.getElementById('bahan-harga').value,
            keterangan_bahan: document.getElementById('bahan-ket').value,
        });
        if (res.success) {
            btnSuccess(btn);
            closeModal('modal-bahan');
            showToast(res.message);
            await loadData();
        } else {
            btnError(btn);
            showToast(res.error || 'Gagal menyimpan.', 'error');
        }
    } catch (e) {
        btnError(btn);
        showToast('Koneksi gagal, coba lagi.', 'error');
    }
}
document.getElementById('btn-simpan-bahan').addEventListener('click', function() { simpanBahan(this); });

/* ── Hapus, restore, toggle ── */
async function hapusBahan(id, nama) {
    if (!confirm(`Hapus bahan "${nama}"?\nData akan disembunyikan dan bisa dipulihkan kapan saja.`)) return;
    const res = await post('bahan/hapus', { id_bahan: id });
    if (res.success) { showToast(res.message); await loadData(); }
    else showToast(res.error, 'error');
}
async function restoreBahan(id, nama) {
    if (!confirm(`Pulihkan bahan "${nama}"?`)) return;
    const res = await post('bahan/restore', { id_bahan: id });
    if (res.success) { showToast(res.message); await loadData(); }
    else showToast(res.error, 'error');
}
async function toggleStatus(id) {
    const res = await post('bahan/toggle-status', { id_bahan: id });
    if (res.success) { showToast(res.message); await loadData(); }
    else showToast(res.error, 'error');
}

/* ── Render tabel stok ──
   Satuan + Stok digabung → satu kolom "Stok" tampil: "12.5 kg"
*/
function renderStok(list) {
    allBahan = list;
    document.getElementById('stok-label').textContent = list.length + ' bahan';
    const tbody = document.getElementById('tbody-stok');
    if (!list.length) {
        tbody.innerHTML = `<tr><td colspan="7"><div class="bb-empty"><i class="bi bi-basket3"></i><p>Belum ada bahan.</p></div></td></tr>`;
        return;
    }
    const mx = Math.max(...list.map(r => parseFloat(r.stok_bahan)||0), 1);
    tbody.innerHTML = list.map((r, i) => {
        const stok     = parseFloat(r.stok_bahan) || 0;
        const nonaktif = r.status_bahan !== 'aktif';
        const pct      = Math.min(stok / mx * 100, 100).toFixed(1);
        const col      = nonaktif ? '#94a3b8' : stok <= 0 ? '#dc2626' : stok <= 5 ? '#d97706' : '#16a34a';
        const badge    = nonaktif ? 'b-na' : stok <= 0 ? 'b-r' : stok <= 5 ? 'b-w' : 'b-ok';
        const badgeTxt = nonaktif ? 'Nonaktif' : stok <= 0 ? 'Habis' : stok <= 5 ? 'Sedikit' : 'Tersedia';
        return `<tr style="${nonaktif ? 'opacity:.65' : ''}">
            <td class="muted" style="font-size:11px">${i+1}</td>
            <td style="font-weight:600;color:var(--text-main)">${esc(r.nama_bahan)}</td>
            <td class="text-end">
                <div class="stok-bar">
                    <div class="stok-pill">
                        <span class="stok-num" style="color:${col}">${fmtN(stok)}</span>
                        <span class="stok-sat">${esc(r.satuan_bahan)}</span>
                    </div>
                    <div class="stok-track"><div class="stok-fill" style="width:${pct}%;background:${col}"></div></div>
                </div>
            </td>
            <td class="text-end muted">${fmt(r.harga_bahan)}</td>
            <td class="text-end tg">${fmtK(stok * parseFloat(r.harga_bahan))}</td>
            <td><span class="badge-status ${badge}">${badgeTxt}</span></td>
            <td>
                <div style="display:flex;gap:4px;flex-wrap:wrap">
                    <button class="btn-toggle" data-action="edit" data-id="${r.id_bahan}">
                        <i class="bi bi-pencil"></i>
                    </button>
                    <button class="btn-toggle ${nonaktif ? 'success' : 'danger'}" data-action="toggle" data-id="${r.id_bahan}">
                        <i class="bi bi-${nonaktif ? 'check-circle' : 'slash-circle'}"></i>
                    </button>
                    <button class="btn-toggle danger" data-action="hapus" data-id="${r.id_bahan}" data-nama="${esc(r.nama_bahan)}">
                        <i class="bi bi-trash3"></i>
                    </button>
                </div>
            </td>
        </tr>`;
    }).join('');
}

document.getElementById('tbody-stok').addEventListener('click', function(e) {
    const btn = e.target.closest('[data-action]');
    if (!btn) return;
    const { action, id, nama } = btn.dataset;
    if (action === 'edit')   openModalBahanFromId(id);
    if (action === 'toggle') toggleStatus(id);
    if (action === 'hapus')  hapusBahan(id, nama);
});

/* ── Render tabel trash ── */
function renderTrash(list) {
    allTrash = list;
    const count = list.length;
    document.getElementById('trash-label').textContent = count + ' bahan';
    document.getElementById('trash-count').textContent = count;
    const tbody = document.getElementById('tbody-trash');
    if (!count) {
        tbody.innerHTML = `<tr><td colspan="6"><div class="bb-empty"><i class="bi bi-trash3"></i><p>Tidak ada bahan terhapus.</p></div></td></tr>`;
        return;
    }
    tbody.innerHTML = list.map((r, i) => `<tr style="opacity:.75">
        <td class="muted" style="font-size:11px">${i+1}</td>
        <td style="font-weight:600;color:var(--text-main);text-decoration:line-through">${esc(r.nama_bahan)}</td>
        <td class="text-end">
            <span class="stok-pill">
                <span class="stok-num ta">${fmtN(r.stok_bahan)}</span>
                <span class="stok-sat">${esc(r.satuan_bahan)}</span>
            </span>
        </td>
        <td class="text-end muted">${fmt(r.harga_bahan)}</td>
        <td style="font-size:12px;color:var(--text-muted);max-width:160px;white-space:normal">${esc(r.keterangan_bahan||'—')}</td>
        <td>
            <button class="btn-toggle amber" data-action="restore" data-id="${r.id_bahan}" data-nama="${esc(r.nama_bahan)}">
                <i class="bi bi-arrow-counterclockwise"></i> Pulihkan
            </button>
        </td>
    </tr>`).join('');
}

document.getElementById('tbody-trash').addEventListener('click', function(e) {
    const btn = e.target.closest('[data-action]');
    if (!btn) return;
    if (btn.dataset.action === 'restore') restoreBahan(btn.dataset.id, btn.dataset.nama);
});

/* ── Render riwayat penggunaan ── */
function renderPakai(rows) {
    document.getElementById('pakai-label').textContent = rows.length + ' transaksi';
    const tbody = document.getElementById('tbody-pakai');
    if (!rows.length) {
        tbody.innerHTML = `<tr><td colspan="5"><div class="bb-empty"><i class="bi bi-fire"></i><p>Belum ada penggunaan.</p></div></td></tr>`;
        return;
    }
    tbody.innerHTML = rows.map(r => `<tr>
        <td class="muted" style="font-size:12px">${fmtD(r.tanggal_penggunaan)}</td>
        <td style="font-weight:600;color:var(--text-main)">${esc(r.nama_bahan)}</td>
        <td class="text-end tr2">
            <span class="stok-pill">
                <span class="stok-num" style="color:var(--red)">${fmtN(r.jumlah_penggunaan)}</span>
                <span class="stok-sat">${esc(r.satuan_bahan)}</span>
            </span>
        </td>
        <td style="font-size:12px;color:var(--text-muted)">${esc(r.keperluan_penggunaan||'—')}</td>
        <td style="font-size:12px;color:var(--text-muted)">${esc(r.catatan_penggunaan||'—')}</td>
    </tr>`).join('');
}

/* ── Load semua data ── */
async function loadData() {
    try {
        const r = await fetch(BB_BASE + 'bahan/data', {
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        });
        const d = await r.json();
        if (!d.success) throw new Error(d.error || 'Gagal mengambil data.');

        document.getElementById('s-jenis').textContent = d.summary.total_jenis;
        document.getElementById('s-nilai').textContent = fmtK(d.summary.total_nilai);
        document.getElementById('s-beli').textContent  = fmtK(d.summary.total_beli);
        document.getElementById('s-nipis').textContent = d.summary.stok_nipis + ' bahan';

        renderStok(d.list);
        renderPakai(d.penggunaan);
        renderTrash(d.trash || []);
    } catch (e) {
        showToast('Gagal memuat: ' + e.message, 'error');
    }
}

loadData();
</script>
<?= $this->endSection() ?>