<?= $this->extend('layout/main') ?>

<?= $this->section('content') ?>
<div class="glass-card" style="width: 100%; overflow-x: auto;">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <h3 class="card-title" style="margin-bottom: 0;">Data Barang</h3>
        <div>
            <?php if(session()->get('role') == 'admin'): ?>
            <button class="btn btn-success" onclick="openModal('modalImport')">
                <i class="fas fa-file-excel"></i> Import XLSX
            </button>
            <button class="btn btn-primary" onclick="tambahData()">
                <i class="fas fa-plus"></i> Tambah Barang
            </button>
            <a href="<?= base_url('aset/hapus-semua-barang') ?>" class="btn btn-danger" onclick="return confirm('Apakah Anda yakin ingin menghapus SEMUA data barang?')">
                <i class="fas fa-trash-alt"></i> Hapus Semua
            </a>
            <?php endif; ?>
        </div>
    </div>

    <!-- Filter Baris -->
    <div style="display: flex; gap: 15px; margin-bottom: 20px; flex-wrap: wrap;">
        <select id="filterJenis" class="form-control" style="width: auto;">
            <option value="">Semua Jenis Barang</option>
            <?php foreach($jenis as $j): ?><option value="<?= $j['nama_jenis'] ?>"><?= $j['nama_jenis'] ?></option><?php endforeach; ?>
        </select>
        <select id="filterSumber" class="form-control" style="width: auto;">
            <option value="">Semua Sumber Dana</option>
            <?php foreach($sumber as $s): ?><option value="<?= $s['nama_sumber'] ?>"><?= $s['nama_sumber'] ?></option><?php endforeach; ?>
        </select>
        <select id="filterRuang" class="form-control" style="width: auto;">
            <option value="">Semua Ruangan</option>
            <?php foreach($ruangan as $r): ?><option value="<?= $r['nama_ruangan'] ?>"><?= $r['nama_ruangan'] ?></option><?php endforeach; ?>
        </select>
        <select id="filterKondisi" class="form-control" style="width: auto;">
            <option value="">Semua Kondisi</option>
            <option value="Baik">Baik</option>
            <option value="Rusak Ringan">Rusak Ringan</option>
            <option value="Rusak Berat">Rusak Berat</option>
        </select>
    </div>

    <table id="tableBarang" class="display nowrap" style="width:100%">
        <thead>
            <tr>
                <th>No.</th>
                <th>KIB</th>
                <th>Kode Brg</th>
                <th>Nama Barang</th>
                <th>Jenis Barang</th>
                <th>Merk</th>
                <th>Spesifikasi</th>
                <th>Tahun</th>
			    <th>Sumber Dana</th>
				<th>Jml</th>
				<th>Harga Satuan</th>
                <th>Harga Total</th>
                <th>Umur Eko</th>
				<th>Residu</th>
                <th>Nil Sekarang</th>
    			<th>Ruang</th>
				<th>Kondisi</th>
                <?php if(session()->get('role') == 'admin'): ?>
                <th>Aksi</th>
                <?php endif; ?>
            </tr>
        </thead>
        <tbody>
            <?php $no = 1; foreach($barang as $b): ?>
            <tr>
                <td><?= $no++ ?></td>
                <td><?= $b['kib'] ?></td>
                <td><?= $b['kode_barang'] ?></td>
                <td><?= $b['nama_barang'] ?></td>
                <td><?= $b['nama_jenis'] ?></td>
                <td><?= $b['merk'] ?></td>
                <td><?= $b['spesifikasi'] ?></td>
				 <td><?= $b['tahun_perolehan'] ?></td>
<td><?= $b['nama_sumber'] ?></td>
<td><?= $b['jumlah'] ?></td>
<td>Rp <?= number_format($b['harga_satuan'], 0, ',', '.') ?></td>
<td>Rp <?= number_format($b['harga_total'], 0, ',', '.') ?></td>
<td><?= $b['umur_ekonomis'] ?> tahun</td>
<td>
    <?php 
    $persen_penyusutan = $b['umur_ekonomis'] > 0 ? (100 / $b['umur_ekonomis']) : 0; 
    echo number_format($persen_penyusutan, 2, ',', '.') . '%'; 
    ?>
</td>
<td>
    <?php 
    $penyusutan_total = $b['penyusutan_per_tahun'] * $b['jumlah'];
    $umur_terpakai = date('Y') - $b['tahun_perolehan']; 
    $umur_penyusutan = min(max($umur_terpakai, 0), $b['umur_ekonomis']);
    
    // Nilai sisa dihitung berdasarkan total penyusutan yang sudah berjalan
    $ns = max($b['harga_total'] - ($penyusutan_total * $umur_penyusutan), 0); 
    ?>
    Rp <?= number_format($ns, 0, ',', '.') ?>
</td>
                <td><?= $b['nama_ruangan'] ?></td>
                <td>
                    <?php
					if ($b['kondisi'] == 'Rusak Ringan') {
						$badge = 'btn-warning';
					} elseif ($b['kondisi'] == 'Rusak Berat') {
						$badge = 'btn-danger';
					} else {
						$badge = 'btn-success';
					}
					?>
                    <span class="btn btn-sm <?= $badge ?>" style="pointer-events:none; padding:2px 8px;"><?= $b['kondisi'] ?></span>
                </td>
                <?php if(session()->get('role') == 'admin'): ?>
                <td>
                    <button class="btn btn-sm btn-success" title="Edit" onclick='editData(<?= json_encode($b) ?>)'><i class="fas fa-edit"></i></button>
                    <a href="<?= base_url('aset/hapus-barang/'.$b['id']) ?>" class="btn btn-sm btn-danger" onclick="return confirm('Yakin?')"><i class="fas fa-trash"></i></a>
                </td>
                <?php endif; ?>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<!-- Modal CRUD Barang -->
<div class="modal-overlay" id="modalForm">
    <div class="modal" style="max-width: 820px;">
        <div class="modal-header">
            <h3 id="modalTitle">Tambah Barang</h3>
            <button class="close-btn" onclick="closeModal('modalForm')">&times;</button>
        </div>
        <form action="<?= base_url('aset/simpan-barang') ?>" method="post" enctype="multipart/form-data">
            <div class="modal-body" style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                <input type="hidden" name="id" id="id">

                <!-- KIB & Kode Barang (Cascading) -->
                <div class="form-group">
                    <label class="form-label"><i class="fas fa-barcode" style="color:var(--primary);"></i> KIB</label>
                    <select name="kib" id="sel_kib" class="form-control" onchange="loadKibDetails(this.value,'sel_kode_barang_brg')">
                        <option value="">-- Pilih KIB --</option>
                        <?php foreach($kibList as $k): ?>
                        <option value="<?= $k['nama_kib'] ?>" data-id="<?= $k['id'] ?>"><?= $k['nama_kib'] ?> (<?= $k['kode_brg'] ?>)</option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">Kode Barang</label>
                    <select name="kode_barang" id="sel_kode_barang_brg" class="form-control">
                        <option value="">-- Pilih KIB dulu --</option>
                    </select>
                </div>

                <div class="form-group" style="grid-column: span 2;">
                    <label class="form-label">Nama Barang</label>
                    <input type="text" name="nama_barang" id="nama_barang" class="form-control" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Merk</label>
                    <input type="text" name="merk" id="merk" class="form-control">
                </div>
                <div class="form-group">
                    <label class="form-label">Jumlah</label>
                    <input type="number" name="jumlah" id="jumlah" class="form-control" oninput="hitungTotal()" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Harga Satuan</label>
                    <input type="number" name="harga_satuan" id="harga_satuan" class="form-control" oninput="hitungTotal()" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Harga Total</label>
                    <input type="number" name="harga_total" id="harga_total" class="form-control" readonly>
                </div>
                <div class="form-group">
                    <label class="form-label">Sumber Dana</label>
                    <select name="id_sumber_dana" id="id_sumber_dana" class="form-control" required>
                        <option value="">Pilih Sumber Dana</option>
                        <?php foreach($sumber as $s): ?>
                            <option value="<?= $s['id'] ?>"><?= $s['nama_sumber'] ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">Ruangan</label>
                    <select name="id_ruangan" id="id_ruangan" class="form-control" required>
                        <option value="">Pilih Ruangan</option>
                        <?php foreach($ruangan as $r): ?>
                            <option value="<?= $r['id'] ?>"><?= $r['nama_ruangan'] ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">Tahun Perolehan</label>
                    <input type="number" name="tahun_perolehan" id="tahun_perolehan" class="form-control" min="1900" max="2100">
                </div>
                <div class="form-group">
                    <label class="form-label">Umur Ekonomis (Tahun)</label>
                    <input type="number" name="umur_ekonomis" id="umur_ekonomis" class="form-control">
                </div>
                <div class="form-group">
                    <label class="form-label">Kondisi</label>
                    <select name="kondisi" id="kondisi" class="form-control" required>
                        <option value="Baik">Baik</option>
                        <option value="Rusak Ringan">Rusak Ringan</option>
                        <option value="Rusak Berat">Rusak Berat</option>
                    </select>
                </div>
                <div class="form-group" style="grid-column: span 2;">
                    <label class="form-label">Spesifikasi</label>
                    <textarea name="spesifikasi" id="spesifikasi" class="form-control" rows="2"></textarea>
                </div>
                <div class="form-group" style="grid-column: span 2;">
                    <label class="form-label">Foto</label>
                    <input type="file" name="foto" class="form-control" accept="image/*">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" onclick="closeModal('modalForm')">Batal</button>
                <button type="submit" class="btn btn-primary">Simpan</button>
            </div>
        </form>
    </div>
</div>

<!-- Modal Import -->
<div class="modal-overlay" id="modalImport">
    <div class="modal">
        <div class="modal-header">
            <h3>Import Data Barang (XLSX)</h3>
            <button class="close-btn" onclick="closeModal('modalImport')">&times;</button>
        </div>
        <form action="<?= base_url('aset/import-barang') ?>" method="post" enctype="multipart/form-data">
            <div class="modal-body">
                <div class="form-group">
                    <label class="form-label">Pilih File Excel (.xlsx)</label>
                    <input type="file" name="file_excel" class="form-control" accept=".xlsx,.xls" required>
                </div>
                <p style="font-size:0.85em; color:#666; margin-top:10px;">Format: A=KIB | B=Kode Brg | C=Nama Barang | D=ID Jenis | E=Merk | F=Spesifikasi | G=Jumlah | H=Harga Satuan | I=ID Sumber Dana | J=ID Ruangan | K=Tahun Perolehan | L=Umur Ekonomis | M=Kondisi</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" onclick="closeModal('modalImport')">Batal</button>
                <button type="submit" class="btn btn-success">Import</button>
            </div>
        </form>
    </div>
</div>

<!-- KIB Details data untuk JS -->
<script id="kibDetailsData" type="application/json"><?= json_encode($kibDetails) ?></script>
<script id="kibListData" type="application/json"><?= json_encode($kibList) ?></script>

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

<?= $this->section('scripts') ?>
<script>
    const ALL_KIB_DETAILS = JSON.parse(document.getElementById('kibDetailsData').textContent);
    const ALL_KIB_LIST    = JSON.parse(document.getElementById('kibListData').textContent);

    /**
     * Isi dropdown kode_barang berdasarkan KIB yang dipilih.
     * @param {string} kibNama - nama_kib terpilih (mis. "KIB-A")
     * @param {string} targetSelectId - id elemen <select> tujuan
     * @param {string} currentKode - kode yang sudah tersimpan (untuk edit mode)
     */
    function loadKibDetails(kibNama, targetSelectId, currentKode = '') {
        const sel = document.getElementById(targetSelectId);
        sel.innerHTML = '<option value="">-- Pilih Kode --</option>';
        if (!kibNama) return;

        // Cari id KIB kategori berdasarkan nama
        const kib = ALL_KIB_LIST.find(k => k.nama_kib === kibNama);
        if (!kib) return;

        const details = ALL_KIB_DETAILS.filter(d => parseInt(d.id_kib_kategori) === parseInt(kib.id));
        details.forEach(d => {
            const opt = document.createElement('option');
            opt.value = d.kode;
            opt.textContent = d.kode + ' — ' + d.nama_barang;
            if (d.kode === currentKode) opt.selected = true;
            sel.appendChild(opt);
        });

        // Jika edit mode dan kode ada tapi tidak ada di list, tambahkan sebagai opsi
        if (currentKode && !details.find(d => d.kode === currentKode)) {
            const opt = document.createElement('option');
            opt.value = currentKode;
            opt.textContent = currentKode + ' (manual)';
            opt.selected = true;
            sel.appendChild(opt);
        }
    }

    $(document).ready(function() {
        initDataTable('#tableBarang');
        let table = $('#tableBarang').DataTable();
        $('#filterJenis').on('change', function()  { table.column(4).search(this.value).draw(); });
        $('#filterSumber').on('change', function()  { table.column(8).search(this.value).draw(); });
        $('#filterRuang').on('change', function()   { table.column(15).search(this.value).draw(); });
        $('#filterKondisi').on('change', function() { table.column(16).search(this.value).draw(); });
    });

    function tambahData() {
        document.getElementById('modalTitle').innerText = 'Tambah Barang';
        document.getElementById('id').value = '';
        document.getElementById('sel_kib').value = '';
        document.getElementById('sel_kode_barang_brg').innerHTML = '<option value="">-- Pilih KIB dulu --</option>';
        document.getElementById('nama_barang').value = '';
        document.getElementById('merk').value = '';
        document.getElementById('jumlah').value = '';
        document.getElementById('harga_satuan').value = '';
        document.getElementById('harga_total').value = '';
        document.getElementById('id_sumber_dana').value = '';
        document.getElementById('id_ruangan').value = '';
        document.getElementById('tahun_perolehan').value = '';
        document.getElementById('umur_ekonomis').value = '';
        document.getElementById('kondisi').value = 'Baik';
        document.getElementById('spesifikasi').value = '';
        openModal('modalForm');
    }

    function editData(data) {
        document.getElementById('modalTitle').innerText = 'Edit Barang';
        document.getElementById('id').value = data.id;
        // Set KIB terlebih dulu, lalu isi kode_barang
        document.getElementById('sel_kib').value = data.kib || '';
        loadKibDetails(data.kib, 'sel_kode_barang_brg', data.kode_barang);
        document.getElementById('nama_barang').value = data.nama_barang;
        document.getElementById('merk').value = data.merk;
        document.getElementById('jumlah').value = data.jumlah;
        document.getElementById('harga_satuan').value = data.harga_satuan;
        document.getElementById('harga_total').value = data.harga_total;
        document.getElementById('id_sumber_dana').value = data.id_sumber_dana;
        document.getElementById('id_ruangan').value = data.id_ruangan;
        document.getElementById('tahun_perolehan').value = data.tahun_perolehan;
        document.getElementById('umur_ekonomis').value = data.umur_ekonomis;
        document.getElementById('kondisi').value = data.kondisi;
        document.getElementById('spesifikasi').value = data.spesifikasi;
        openModal('modalForm');
    }

    function hitungTotal() {
        let jumlah = document.getElementById('jumlah').value || 0;
        let harga  = document.getElementById('harga_satuan').value || 0;
        document.getElementById('harga_total').value = jumlah * harga;
    }
</script>
<?= $this->endSection() ?>
