<?= $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 grid */
    .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.teal   { background:#e0f2fe; color:#0891b2; }
    .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 */
    .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; }

    /* List item */
    .pb-item { padding:18px 22px; border-bottom:1px solid var(--border); display:flex; align-items:flex-start; gap:14px; transition:background .15s; }
    .pb-item:last-child { border-bottom:none; }
    .pb-item:hover { background:var(--bg-card2); }
    .pb-item-ico { width:42px; height:42px; border-radius:11px; flex-shrink:0; background:var(--accent-soft); display:flex; align-items:center; justify-content:center; font-size:17px; color:var(--accent); }
    .pb-item-body { flex:1; min-width:0; }
    .pb-item-top  { display:flex; align-items:center; gap:8px; flex-wrap:wrap; margin-bottom:4px; }
    .pb-no   { font-size:.72rem; color:var(--accent); background:var(--accent-soft); padding:2px 8px; border-radius:6px; font-weight:700; }
    .pb-date { font-size:.76rem; color:var(--text-muted); }
    .pb-meta { font-size:.76rem; color:var(--text-muted); }
    .pb-chips { display:flex; flex-wrap:wrap; gap:5px; margin-top:7px; }
    .pb-chip  { background:var(--bg-card2); border:1px solid var(--border); padding:3px 10px; border-radius:20px; font-size:.72rem; color:var(--text-main); font-weight:500; }
    .pb-total { font-size:1rem; font-weight:700; color:#16a34a; white-space:nowrap; }
    .nota-thumb { width:46px; height:46px; border-radius:8px; object-fit:cover; border:1px solid var(--border); cursor:pointer; flex-shrink:0; transition:transform .2s; }
    .nota-thumb:hover { transform:scale(1.08); }

    /* Tombol */
    .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 { background:#2859e0; box-shadow:0 4px 14px rgba(59,111,245,.25); }
    .btn-secondary { background:var(--bg-side); color:var(--text-main); border:1px solid var(--border); border-radius:10px; padding:9px 18px; font-size:.82rem; font-weight:600; cursor:pointer; display:inline-flex; align-items:center; gap:7px; text-decoration:none; transition:all .2s; }
    .btn-secondary:hover { border-color:var(--accent); color:var(--accent); background:var(--accent-soft); }
    .btn-sm-del { background:transparent; border:1px solid var(--border); border-radius:8px; padding:5px 10px; font-size:.75rem; color:var(--text-muted); cursor:pointer; transition:all .18s; }
    .btn-sm-del:hover { border-color:#fca5a5; color:#dc2626; background:#fff5f5; }

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

    /* Modal overlay */
    .modal-overlay { display:none; position:fixed; inset:0; z-index:600; background:rgba(15,22,35,.45); backdrop-filter:blur(4px); align-items:center; justify-content:center; opacity:0; transition:opacity .22s; }
    .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:96%; 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; max-height:90vh; overflow-y: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 dalam modal */
    .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, .f-group textarea:focus { border-color:var(--accent); background:#fff; box-shadow:0 0 0 3px rgba(59,111,245,.1); }
    .f-group input.invalid { border-color:#dc2626!important; background:#fff5f5!important; box-shadow:0 0 0 3px rgba(220,38,38,.1)!important; }

    /* Item bahan */
    .items-section { border:1px solid var(--border); border-radius:12px; overflow:hidden; margin-bottom:10px; }
    .items-head    { background:var(--bg-card2); padding:10px 14px; display:flex; align-items:center; justify-content:space-between; border-bottom:1px solid var(--border); }
    .items-head span { font-size:.73rem; font-weight:700; text-transform:uppercase; letter-spacing:.06em; color:var(--text-muted); }
    .item-row-hdr  { display:grid; grid-template-columns:2fr 1fr 1fr 80px 32px; gap:8px; padding:6px 14px; background:var(--bg-card2); border-bottom:1px solid var(--border); }
    .item-row-hdr span { font-size:.63rem; font-weight:700; text-transform:uppercase; letter-spacing:.06em; color:var(--text-muted); }
    .item-row { display:grid; grid-template-columns:2fr 1fr 1fr 80px 32px; gap:8px; padding:8px 14px; align-items:center; border-bottom:1px solid var(--border); }
    .item-row:last-child { border-bottom:none; }
    .item-row input, .item-row select { padding:7px 10px; border:1.5px solid var(--border); border-radius:8px; background:var(--bg-card2); color:var(--text-main); font-size:.8rem; outline:none; width:100%; transition:border-color .18s; }
    .item-row input:focus, .item-row select:focus { border-color:var(--accent); background:#fff; }
    .item-row input.invalid, .item-row select.invalid { border-color:#dc2626!important; background:#fff5f5!important; }
    .item-subtotal { font-size:.76rem; font-weight:700; color:#16a34a; text-align:right; white-space:nowrap; }
    .btn-rm-item { background:#fee2e2; border:none; border-radius:7px; width:30px; height:30px; cursor:pointer; display:flex; align-items:center; justify-content:center; color:#dc2626; font-size:12px; transition:all .18s; }
    .btn-rm-item:hover { background:#fca5a5; }
    .btn-add-item { background:var(--accent-soft); border:1.5px dashed var(--accent); border-radius:10px; padding:9px; width:100%; color:var(--accent); font-size:.8rem; font-weight:700; cursor:pointer; display:flex; align-items:center; justify-content:center; gap:6px; transition:all .18s; margin-bottom:14px; }
    .btn-add-item:hover { background:var(--accent); color:#fff; }

    /* Total bar */
    .total-bar { background:var(--accent-soft); border:1px solid #c7d7fc; border-radius:10px; padding:10px 16px; display:flex; align-items:center; justify-content:space-between; margin-bottom:14px; }
    .total-bar span { font-size:.78rem; color:var(--text-muted); font-weight:600; }
    .total-bar strong { font-size:1.05rem; font-weight:700; color:var(--accent); }

    /* Nota preview */
    .nota-preview { border:1.5px dashed var(--border); border-radius:12px; background:var(--bg-card2); min-height:76px; cursor:pointer; display:flex; align-items:center; justify-content:center; flex-direction:column; gap:5px; transition:all .2s; position:relative; overflow:hidden; }
    .nota-preview:hover { border-color:var(--accent); background:var(--accent-soft); }
    .nota-preview p { font-size:.78rem; color:var(--text-muted); margin:0; }
    .nota-preview img { width:100%; max-height:110px; object-fit:cover; border-radius:8px; }
    .nota-label { position:absolute; bottom:7px; right:7px; background:rgba(0,0,0,.5); color:#fff; font-size:.63rem; padding:2px 7px; border-radius:20px; }

    /* 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 { 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; position:relative; overflow:hidden; }
    .btn-save:hover:not(:disabled) { background:#138638; box-shadow:0 4px 14px rgba(22,163,74,.25); }
    .btn-save:disabled { opacity:.65; cursor:not-allowed; }
    .btn-save .btn-spin { display:none; width:17px; height:17px; border-radius:50%; border:2.5px solid rgba(255,255,255,.3); border-top-color:#fff; animation:spin .5s linear infinite; }
    .btn-save.loading .btn-label { opacity:0; }
    .btn-save.loading .btn-spin  { display:block; }
    .btn-save.done::after { content:'✓'; position:absolute; font-size:1.1rem; font-weight:700; animation:tickPop .28s ease forwards; }
    @keyframes spin    { to { transform:rotate(360deg); } }
    @keyframes tickPop { from{transform:scale(.3);opacity:0} to{transform:scale(1);opacity:1} }

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

    /* Nota lightbox */
    .nota-viewer { display:none; position:fixed; inset:0; z-index:900; background:rgba(0,0,0,.8); align-items:center; justify-content:center; }
    .nota-viewer.open { display:flex; }
    .nota-viewer img  { max-width:90vw; max-height:88vh; border-radius:12px; }
    .nota-viewer-close { position:absolute; top:18px; right:22px; background:rgba(255,255,255,.15); border:none; color:#fff; font-size:1.3rem; cursor:pointer; border-radius:50%; width:38px; height:38px; display:flex; align-items:center; justify-content:center; }
    .nota-viewer-close:hover { background:rgba(255,255,255,.3); }

    /* Toast */
    #pb-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); }
    #pb-toast.show { transform:translateY(0) scale(1); opacity:1; }
    #pb-toast.success { background:#fff; border:1px solid #86efac; color:#166534; }
    #pb-toast.error   { background:#fff; border:1px solid #fca5a5; color:#991b1b; }
    #pb-toast .t-ico  { width:26px; height:26px; border-radius:7px; flex-shrink:0; display:flex; align-items:center; justify-content:center; font-size:13px; }
    #pb-toast.success .t-ico { background:#dcfce7; }
    #pb-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; }
</style>
<?= $this->endSection() ?>

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

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

<!-- Nota Lightbox -->
<div class="nota-viewer" id="nota-viewer">
    <button class="nota-viewer-close" id="nota-close-btn">&times;</button>
    <img src="" id="nota-img-large" alt="Foto Nota">
</div>

<!-- ══ MODAL TAMBAH PEMBELIAN ══ -->
<div class="modal-overlay" id="modal-pb">
    <div class="modal-box">
        <div class="modal-head">
            <div class="modal-ico" style="background:#dcfce7">
                <i class="bi bi-cart-plus-fill" style="color:#16a34a"></i>
            </div>
            <div>
                <p class="modal-title">Tambah Pembelian Bahan</p>
                <p class="modal-sub">1 transaksi dapat berisi banyak bahan sekaligus</p>
            </div>
        </div>

        <div class="f-row">
            <div class="f-group">
                <label>Tanggal Pembelian</label>
                <input id="pb-tanggal" type="date">
            </div>
            <div class="f-group">
                <label>Supplier / Toko</label>
                <input id="pb-supplier" placeholder="Nama supplier atau toko">
            </div>
        </div>
        <div class="f-row full">
            <div class="f-group">
                <label>Tempat Pembelian</label>
                <input id="pb-tempat" placeholder="Contoh: Pasar Batu, Toko ABC Online…">
            </div>
        </div>

        <hr class="m-divider">

        <div class="items-section">
            <div class="items-head">
                <span><i class="bi bi-list-check"></i> Detail Bahan yang Dibeli</span>
                <span id="item-count-label" style="font-size:.7rem;color:var(--accent)"></span>
            </div>
            <div class="item-row-hdr">
                <span>Nama Bahan</span>
                <span>Jumlah</span>
                <span>Harga/Sat. (Rp)</span>
                <span style="text-align:right">Subtotal</span>
                <span></span>
            </div>
            <div id="items-body"></div>
        </div>

        <button class="btn-add-item" id="btn-add-item" type="button">
            <i class="bi bi-plus-lg"></i> Tambah Bahan Lain
        </button>

        <div class="total-bar">
            <span><i class="bi bi-calculator"></i> Total Keseluruhan</span>
            <strong id="pb-total-display">Rp 0</strong>
        </div>

        <div class="f-row">
            <div class="f-group">
                <label>Catatan</label>
                <input id="pb-catatan" placeholder="Opsional…">
            </div>
            <div class="f-group">
                <label>Foto Nota / Struk</label>
                <input type="file" id="pb-nota-file" accept="image/*" style="display:none">
                <div class="nota-preview" id="nota-preview-box"
                     onclick="document.getElementById('pb-nota-file').click()">
                    <i class="bi bi-camera" style="font-size:1.3rem;color:var(--text-muted)"></i>
                    <p>Klik untuk upload foto nota</p>
                </div>
            </div>
        </div>

        <div class="modal-footer">
            <button class="btn-cancel" id="btn-batal-pb">Batal</button>
            <button class="btn-save" id="btn-submit-pb">
                <span class="btn-label"><i class="bi bi-cart-check-fill"></i> Simpan Pembelian</span>
                <span class="btn-spin"></span>
            </button>
        </div>
    </div>
</div>

<!-- ══ KONTEN UTAMA ══ -->
<div class="page-header">
    <div>
        <div class="page-title"><i class="bi bi-cart3"></i> Pembelian Bahan</div>
        <p class="page-subtitle">Riwayat transaksi pembelian bahan produksi beserta nota</p>
    </div>
    <div style="display:flex;gap:10px;flex-wrap:wrap;align-items:center">
        <a href="<?= base_url('bahan') ?>" class="btn-secondary">
            <i class="bi bi-arrow-left"></i> Manajemen Bahan
        </a>
        <button class="btn-primary" id="btn-open-pb">
            <i class="bi bi-plus-lg"></i> Tambah Pembelian
        </button>
    </div>
</div>

<!-- Stats -->
<div class="stats-grid">
    <div class="stat-card">
        <div class="stat-ico blue"><i class="bi bi-receipt"></i></div>
        <div class="stat-val" id="s-transaksi">—</div>
        <div class="stat-label">Total Transaksi</div>
    </div>
    <div class="stat-card">
        <div class="stat-ico green"><i class="bi bi-currency-dollar"></i></div>
        <div class="stat-val" id="s-total">—</div>
        <div class="stat-label">Total Nilai Pembelian</div>
    </div>
    <div class="stat-card">
        <div class="stat-ico amber"><i class="bi bi-calendar-week"></i></div>
        <div class="stat-val" id="s-bulan">—</div>
        <div class="stat-label">Pembelian Bulan Ini</div>
    </div>
    <div class="stat-card">
        <div class="stat-ico teal"><i class="bi bi-basket3"></i></div>
        <div class="stat-val" id="s-item">—</div>
        <div class="stat-label">Total Item Dibeli</div>
    </div>
</div>

<!-- Daftar Pembelian -->
<div class="card">
    <div class="card-head">
        <div class="card-title">
            <i class="bi bi-cart-check-fill" style="color:#16a34a"></i> Riwayat Pembelian
        </div>
        <span class="card-count" id="pb-count-label">memuat…</span>
    </div>
    <div id="pb-list-wrap">
        <div class="pb-empty">
            <i class="bi bi-hourglass-split"></i>
            <p>Memuat data…</p>
        </div>
    </div>
</div>

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

<?= $this->section('js') ?>
<script>
const PB_BASE = '<?= base_url() ?>';
let allBahan = [];
let pbToastT;
let notaB64  = null;
let itemIdx  = 0;

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 => (parseFloat(n)||0).toLocaleString('id-ID');
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('pb-toast');
    document.getElementById('pt-ico').textContent = type==='success' ? '✓' : '✕';
    document.getElementById('pt-msg').textContent = msg;
    el.className = 'show '+type;
    clearTimeout(pbToastT);
    pbToastT = setTimeout(()=>{ el.className=''; }, 3600);
}

/* 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-pb').addEventListener('click', ()=> closeModal('modal-pb'));

/* Nota viewer */
document.getElementById('nota-close-btn').addEventListener('click', ()=> document.getElementById('nota-viewer').classList.remove('open'));
document.getElementById('nota-viewer').addEventListener('click', e=>{ if(e.target===document.getElementById('nota-viewer')) document.getElementById('nota-viewer').classList.remove('open'); });
function viewNota(src){ document.getElementById('nota-img-large').src=src; document.getElementById('nota-viewer').classList.add('open'); }

/* Nota upload */
document.getElementById('pb-nota-file').addEventListener('change', function(){
    const file = this.files[0];
    if(!file) return;
    const reader = new FileReader();
    reader.onload = ev => {
        notaB64 = ev.target.result;
        const box = document.getElementById('nota-preview-box');
        box.innerHTML = `<img src="${notaB64}" alt="Nota"><span class="nota-label">Ganti foto</span>`;
    };
    reader.readAsDataURL(file);
});

/* Item rows */
function buildBahanOptions(selectedId=0){
    return `<option value="">-- Pilih Bahan --</option>` +
        allBahan.filter(b => b.status_bahan === 'aktif').map(b =>
            `<option value="${b.id_bahan}" data-harga="${b.harga_bahan}" ${b.id_bahan==selectedId?'selected':''}>
                ${esc(b.nama_bahan)}
            </option>`
        ).join('');
}

function addItemRow(data={}){
    itemIdx++;
    const row = document.createElement('div');
    row.className = 'item-row';
    row.dataset.idx = itemIdx;
    row.innerHTML = `
        <select class="item-bahan">${buildBahanOptions(data.id_bahan||0)}</select>
        <input class="item-jumlah" type="number" step="0.001" min="0.001" placeholder="0" value="${data.jumlah||''}">
        <input class="item-harga"  type="number" min="1" placeholder="0" value="${data.harga||''}">
        <div class="item-subtotal">—</div>
        <button class="btn-rm-item" type="button"><i class="bi bi-trash3-fill"></i></button>`;

    const sel = row.querySelector('.item-bahan');
    const inpJ = row.querySelector('.item-jumlah');
    const inpH = row.querySelector('.item-harga');

    sel.addEventListener('change', function(){
        const opt = this.options[this.selectedIndex];
        if(opt && opt.dataset.harga) inpH.value = opt.dataset.harga;
        recalcRow(row); recalcTotal();
    });
    inpJ.addEventListener('input', ()=>{ recalcRow(row); recalcTotal(); });
    inpH.addEventListener('input', ()=>{ recalcRow(row); recalcTotal(); });
    row.querySelector('.btn-rm-item').addEventListener('click', ()=>{ row.remove(); recalcTotal(); updateItemCount(); });

    const initOpt = sel.options[sel.selectedIndex];
    if(initOpt && initOpt.dataset.harga && !data.harga) inpH.value = initOpt.dataset.harga;

    document.getElementById('items-body').appendChild(row);
    recalcRow(row); recalcTotal(); updateItemCount();
}

function recalcRow(row){
    const j = parseFloat(row.querySelector('.item-jumlah')?.value)||0;
    const h = parseFloat(row.querySelector('.item-harga')?.value)||0;
    row.querySelector('.item-subtotal').textContent = j>0 && h>0 ? fmt(j*h) : '—';
}
function recalcTotal(){
    let total = 0;
    document.querySelectorAll('.item-row').forEach(row=>{
        total += (parseFloat(row.querySelector('.item-jumlah')?.value)||0) * (parseFloat(row.querySelector('.item-harga')?.value)||0);
    });
    document.getElementById('pb-total-display').textContent = fmt(total);
}
function updateItemCount(){
    const n = document.querySelectorAll('.item-row').length;
    document.getElementById('item-count-label').textContent = n ? `${n} bahan` : '';
}

document.getElementById('btn-add-item').addEventListener('click', ()=> addItemRow());

function openModalPB(){
    document.getElementById('pb-tanggal').value  = new Date().toISOString().split('T')[0];
    document.getElementById('pb-supplier').value = '';
    document.getElementById('pb-tempat').value   = '';
    document.getElementById('pb-catatan').value  = '';
    document.getElementById('pb-total-display').textContent = 'Rp 0';
    document.getElementById('nota-preview-box').innerHTML = `
        <i class="bi bi-camera" style="font-size:1.3rem;color:var(--text-muted)"></i>
        <p>Klik untuk upload foto nota</p>`;
    document.getElementById('pb-nota-file').value = '';
    notaB64 = null; itemIdx = 0;
    document.getElementById('items-body').innerHTML = '';
    addItemRow();
    openModal('modal-pb');
}
document.getElementById('btn-open-pb').addEventListener('click', openModalPB);

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

/* Submit */
async function submitPB(btn){
    const items = [];
    let hasInvalid = false;
    document.querySelectorAll('.item-row').forEach(row=>{
        const id_bahan = row.querySelector('.item-bahan')?.value;
        const jumlah   = parseFloat(row.querySelector('.item-jumlah')?.value)||0;
        const harga    = parseFloat(row.querySelector('.item-harga')?.value)||0;
        const selEl    = row.querySelector('.item-bahan');
        const jEl      = row.querySelector('.item-jumlah');
        const hEl      = row.querySelector('.item-harga');
        let valid = true;
        if(!id_bahan){ selEl.classList.add('invalid','shake'); setTimeout(()=>selEl.classList.remove('shake'),380); valid=false; }
        if(jumlah<=0){ jEl.classList.add('invalid','shake'); setTimeout(()=>jEl.classList.remove('shake'),380); valid=false; }
        if(harga<=0) { hEl.classList.add('invalid','shake'); setTimeout(()=>hEl.classList.remove('shake'),380); valid=false; }
        if(!valid){ hasInvalid=true; return; }
        selEl.classList.remove('invalid'); jEl.classList.remove('invalid'); hEl.classList.remove('invalid');
        items.push({ id_bahan, jumlah_bahan:jumlah, harga_satuan_bahan:harga });
    });
    if(hasInvalid){ showToast('Lengkapi semua detail bahan.','error'); return; }
    if(!items.length){ showToast('Tambahkan minimal 1 bahan.','error'); return; }

    btn.disabled=true; btn.classList.add('loading');
    try {
        const res = await post('/pembelian-bahan/simpan', {
            tanggal_pembelian_bahan : document.getElementById('pb-tanggal').value,
            supplier_pembelian      : document.getElementById('pb-supplier').value,
            tempat_pembelian_bahan  : document.getElementById('pb-tempat').value,
            catatan_pembelian       : document.getElementById('pb-catatan').value,
            foto_nota_base64        : notaB64,
            items,
        });
        if(res.success){
            btn.classList.remove('loading'); btn.classList.add('done');
            setTimeout(()=>{ btn.classList.remove('done'); btn.disabled=false; closeModal('modal-pb'); }, 700);
            setTimeout(()=>{ showToast(res.message); loadData(); }, 900);
        } else {
            btn.classList.remove('loading'); btn.disabled=false;
            btn.classList.add('shake'); setTimeout(()=>btn.classList.remove('shake'),380);
            showToast(res.error,'error');
        }
    } catch(e){
        btn.classList.remove('loading'); btn.disabled=false;
        showToast('Koneksi gagal, coba lagi.','error');
    }
}
document.getElementById('btn-submit-pb').addEventListener('click', function(){ submitPB(this); });

/* Hapus */
async function hapusPB(id){
    if(!confirm('Hapus transaksi ini? Semua item dan stok bahan akan dikembalikan.')) return;
    const res = await post('/pembelian-bahan/hapus', { id_pembelian_bahan:id });
    if(res.success){ showToast(res.message); loadData(); }
    else showToast(res.error,'error');
}

/* Render */
function renderList(list){
    document.getElementById('pb-count-label').textContent = list.length+' transaksi';
    const wrap = document.getElementById('pb-list-wrap');
    if(!list.length){
        wrap.innerHTML = `<div class="pb-empty"><i class="bi bi-cart-x"></i><p>Belum ada transaksi pembelian.</p></div>`;
        return;
    }
    wrap.innerHTML = list.map(pb => {
        const chips = (pb.detail||[]).map(d =>
            `<span class="pb-chip">${esc(d.nama_bahan)} · ${fmtN(d.jumlah_bahan)} ${esc(d.satuan_bahan)}</span>`
        ).join('');
        const notaHtml = pb.foto_nota_pembelian_bahan
            ? `<img class="nota-thumb" src="${PB_BASE}/uploads/nota/${esc(pb.foto_nota_pembelian_bahan)}" alt="Nota"
                    onclick="viewNota('${PB_BASE}/uploads/nota/${esc(pb.foto_nota_pembelian_bahan)}')">`
            : '';
        return `
        <div class="pb-item">
            <div class="pb-item-ico"><i class="bi bi-receipt"></i></div>
            <div class="pb-item-body">
                <div class="pb-item-top">
                    <span class="pb-no">#${String(pb.id_pembelian_bahan).padStart(4,'0')}</span>
                    <span class="pb-date"><i class="bi bi-calendar3"></i> ${fmtD(pb.tanggal_pembelian_bahan)}</span>
                    ${pb.tempat_pembelian_bahan ? `<span class="pb-meta"><i class="bi bi-geo-alt"></i> ${esc(pb.tempat_pembelian_bahan)}</span>` : ''}
                    ${pb.supplier_pembelian    ? `<span class="pb-meta">· ${esc(pb.supplier_pembelian)}</span>` : ''}
                </div>
                <div class="pb-chips">${chips || '<span class="pb-chip" style="opacity:.5">Tidak ada detail</span>'}</div>
            </div>
            ${notaHtml}
            <div style="text-align:right;flex-shrink:0">
                <div class="pb-total">${fmtK(pb.total_pembelian_bahan)}</div>
                <div style="margin-top:6px">
                    <button class="btn-sm-del" onclick="hapusPB(${pb.id_pembelian_bahan})">
                        <i class="bi bi-trash3"></i> Hapus
                    </button>
                </div>
            </div>
        </div>`;
    }).join('');
}

/* Load data */
async function loadData(){
    try {
        const rb = await fetch(PB_BASE+'/bahan/data', { headers:{'X-Requested-With':'XMLHttpRequest'} });
        const db = await rb.json();
        if(db.success) allBahan = db.list;

        const rp = await fetch(PB_BASE+'/pembelian-bahan/data', { headers:{'X-Requested-With':'XMLHttpRequest'} });
        const dp = await rp.json();
        if(!dp.success) throw new Error(dp.error||'Gagal');

        document.getElementById('s-transaksi').textContent = dp.summary.total_transaksi;
        document.getElementById('s-total').textContent     = fmtK(dp.summary.total_nilai);
        document.getElementById('s-bulan').textContent     = fmtK(dp.summary.nilai_bulan_ini);
        document.getElementById('s-item').textContent      = dp.summary.total_item + ' item';

        renderList(dp.list);
    } catch(e){
        showToast('Gagal memuat: '+e.message,'error');
    }
}

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