<?= $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 Buku</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="tambahBuku()">
                <i class="fas fa-plus"></i> Tambah Buku
            </button>
            <a href="<?= base_url('aset/hapus-semua-buku') ?>" class="btn btn-danger" onclick="return confirm('Apakah Anda yakin ingin menghapus SEMUA data buku?')">
                <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;">
        <input type="number" id="filterTgl" class="form-control" style="width: auto;" placeholder="Filter Thn Pengadaan" title="Filter Thn Pengadaan">
        <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>
        <input type="text" id="filterJenisBacaan" class="form-control" style="width: auto;" placeholder="Cari Jenis Bacaan">
        <input type="text" id="filterPenerbit"    class="form-control" style="width: auto;" placeholder="Cari Penerbit">
        <input type="number" id="filterTahun"     class="form-control" style="width: auto;" placeholder="Cari Tahun Terbit">
    </div>

    <table id="tableBuku" class="display nowrap" style="width:100%">
        <thead>
            <tr>
                <th>No.</th>
                <th>KIB</th>
                <th>Kode Brg</th>
                <th>Judul</th>
                <th>Jenis Bacaan</th>
                <th>Pengarang</th>
                <th>Penerbit</th>
                <th>Tahun Terbit</th>
                <th>Thn Pengadaan</th>
                <th>Sumber Dana</th>
                <th>Harga Satuan</th>
                <th>Jumlah</th>
                <th>Total Harga</th>
                <th>Umur Ekonomis</th>
                <th>Penyusutan/Tahun</th>
                <th>Nilai Sekarang</th>
                <th>Ruangan</th>
                <th>Kondisi</th>
                <?php if(session()->get('role') == 'admin'): ?>
                <th>Aksi</th>
                <?php endif; ?>
            </tr>
        </thead>
        <tbody>
            <?php $no = 1; foreach($buku as $b): ?>
            <tr>
                <td><?= $no++ ?></td>
                <td><?= $b['kib'] ?? '-' ?></td>
                <td><code style="background:rgba(67,97,238,0.08); padding:2px 6px; border-radius:4px;"><?= $b['kode_barang'] ?? '-' ?></code></td>
                <td><?= $b['judul'] ?></td>
                <td><?= $b['jenis_bacaan'] ?></td>
                <td><?= $b['pengarang'] ?></td>
                <td><?= $b['penerbit'] ?></td>
                <td><?= $b['tahun_terbit'] ?></td>
                <td><?= date('Y', strtotime($b['tgl_pengadaan'])) ?></td>
                <td><?= $b['nama_sumber'] ?></td>
                <td>Rp <?= number_format($b['harga_satuan'], 0, ',', '.') ?></td>
                <td><?= $b['jumlah'] ?></td>
                <td>Rp <?= number_format($b['total_harga'], 0, ',', '.') ?></td>
                <td><?= $b['umur_ekonomis'] ?? 5 ?> tahun</td>
                <td>
                    <?php 
                    $umur_ekonomis = $b['umur_ekonomis'] ?? 5;
                    $persen_penyusutan = $umur_ekonomis > 0 ? (100 / $umur_ekonomis) : 0; 
                    echo number_format($persen_penyusutan, 2, ',', '.') . '%'; 
                    ?>
                </td>
                <td>
                    <?php 
                    $penyusutan_per_tahun = $b['penyusutan_per_tahun'] ?? ($b['harga_satuan'] / max($umur_ekonomis, 1));
                    $penyusutan_total = $penyusutan_per_tahun * $b['jumlah'];
                    $tahun_pengadaan = date('Y', strtotime($b['tgl_pengadaan']));
                    $umur_terpakai = date('Y') - $tahun_pengadaan; 
                    $umur_penyusutan = min(max($umur_terpakai, 0), $umur_ekonomis);
                    $ns = max($b['total_harga'] - ($penyusutan_total * $umur_penyusutan), 0); 
                    ?>
                    Rp <?= number_format($ns, 0, ',', '.') ?>
                </td>
                <td><?= $b['nama_ruangan'] ?></td>
                <td>
                    <?php
                        $badge = 'btn-success';
                        if(($b['kondisi'] ?? 'Baik') == 'Rusak Ringan') $badge = 'btn-warning';
                        if(($b['kondisi'] ?? 'Baik') == 'Rusak Berat')  $badge = 'btn-danger';
                    ?>
                    <span class="btn btn-sm <?= $badge ?>" style="pointer-events:none; padding:2px 8px;"><?= $b['kondisi'] ?? 'Baik' ?></span>
                </td>
                <?php if(session()->get('role') == 'admin'): ?>
                <td>
                    <button class="btn btn-sm btn-success" onclick='editBuku(<?= json_encode($b) ?>)'><i class="fas fa-edit"></i></button>
                    <a href="<?= base_url('aset/hapus-buku/'.$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 Buku -->
<div class="modal-overlay" id="modalBuku">
    <div class="modal" style="max-width: 820px;">
        <div class="modal-header">
            <h3>Form Buku</h3>
            <button class="close-btn" onclick="closeModal('modalBuku')">&times;</button>
        </div>
        <form action="<?= base_url('aset/simpan-buku') ?>" 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">

                <!-- KIB & Kode Barang (Cascading) -->
                <div class="form-group">
                    <label><i class="fas fa-barcode" style="color:var(--primary);"></i> KIB</label>
                    <select name="kib" id="buku_sel_kib" class="form-control" onchange="loadKibDetails(this.value,'buku_sel_kode')">
                        <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>Kode Barang</label>
                    <select name="kode_barang" id="buku_sel_kode" class="form-control">
                        <option value="">-- Pilih KIB dulu --</option>
                    </select>
                </div>

                <div class="form-group"><label>Judul Buku</label><input type="text" name="judul" class="form-control" required></div>
                <div class="form-group"><label>Jenis Bacaan</label><input type="text" name="jenis_bacaan" class="form-control"></div>
                <div class="form-group"><label>Thn Pengadaan</label><input type="number" name="tgl_pengadaan" class="form-control" min="1900" max="2100" required></div>
                <div class="form-group">
                    <label>Sumber Dana</label>
                    <select name="id_sumber_dana" class="form-control" required>
                        <option value="">Pilih</option>
                        <?php foreach($sumber as $s): ?>
                            <option value="<?= $s['id'] ?>"><?= $s['nama_sumber'] ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group"><label>Pengarang</label><input type="text" name="pengarang" class="form-control" required></div>
                <div class="form-group"><label>Penerbit</label><input type="text" name="penerbit" class="form-control" required></div>
                <div class="form-group"><label>Tahun Terbit</label><input type="number" name="tahun_terbit" class="form-control" required></div>
                <div class="form-group">
                    <label>Ruangan</label>
                    <select name="id_ruangan" class="form-control" required>
                        <option value="">Pilih</option>
                        <?php foreach($ruangan as $r): ?>
                            <option value="<?= $r['id'] ?>"><?= $r['nama_ruangan'] ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group"><label>Jumlah</label><input type="number" name="jumlah" class="form-control" required></div>
                <div class="form-group"><label>Harga Satuan</label><input type="number" name="harga_satuan" class="form-control" required></div>
                <div class="form-group"><label>Umur Ekonomis (Tahun)</label><input type="number" name="umur_ekonomis" class="form-control" required value="5"></div>
                <div class="form-group">
                    <label>Kondisi</label>
                    <select name="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>Foto Sampul</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('modalBuku')">Batal</button>
                <button type="submit" class="btn btn-primary">Simpan</button>
            </div>
        </form>
    </div>
</div>

<!-- Modal Import Buku -->
<div class="modal-overlay" id="modalImport">
    <div class="modal">
        <div class="modal-header">
            <h3>Import Data Buku (XLSX)</h3>
            <button class="close-btn" onclick="closeModal('modalImport')">&times;</button>
        </div>
        <form action="<?= base_url('aset/import-buku') ?>" method="post" enctype="multipart/form-data">
            <div class="modal-body">
                <div class="form-group">
                    <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=Tgl Pengadaan | D=ID Sumber Dana | E=Judul | F=Jenis Bacaan | G=Pengarang | H=Penerbit | I=Tahun Terbit | J=Harga Satuan | K=Jumlah | L=ID Ruangan | 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 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);

    function loadKibDetails(kibNama, targetSelectId, currentKode = '') {
        const sel = document.getElementById(targetSelectId);
        sel.innerHTML = '<option value="">-- Pilih Kode --</option>';
        if (!kibNama) { sel.innerHTML = '<option value="">-- Pilih KIB dulu --</option>'; return; }

        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);
        });
        if (currentKode && !details.find(d => d.kode === currentKode)) {
            const opt = document.createElement('option');
            opt.value = currentKode; opt.textContent = currentKode; opt.selected = true;
            sel.appendChild(opt);
        }
    }

    $(document).ready(function() {
        initDataTable('#tableBuku');
        let table = $('#tableBuku').DataTable();
        $('#filterTgl').on('keyup change', function() { table.column(8).search(this.value).draw(); });
        $('#filterSumber').on('change',    function() { table.column(9).search(this.value).draw(); });
        $('#filterJenisBacaan').on('keyup',function() { table.column(4).search(this.value).draw(); });
        $('#filterPenerbit').on('keyup',   function() { table.column(6).search(this.value).draw(); });
        $('#filterTahun').on('keyup change',function(){ table.column(7).search(this.value).draw(); });
    });

    function tambahBuku() {
        document.querySelector('#modalBuku input[name="id"]').value = '';
        document.querySelector('#modalBuku form').reset();
        document.getElementById('buku_sel_kode').innerHTML = '<option value="">-- Pilih KIB dulu --</option>';
        document.querySelector('#modalBuku input[name="umur_ekonomis"]').value = 5;
        openModal('modalBuku');
    }

    function editBuku(data) {
        document.querySelector('#modalBuku input[name="id"]').value = data.id;
        // Set KIB → load kode
        document.getElementById('buku_sel_kib').value = data.kib || '';
        loadKibDetails(data.kib, 'buku_sel_kode', data.kode_barang);
        document.querySelector('#modalBuku input[name="judul"]').value = data.judul;
        document.querySelector('#modalBuku input[name="jenis_bacaan"]').value = data.jenis_bacaan;
        document.querySelector('#modalBuku input[name="tgl_pengadaan"]').value = data.tgl_pengadaan ? data.tgl_pengadaan.substring(0, 4) : '';
        document.querySelector('#modalBuku input[name="pengarang"]').value = data.pengarang;
        document.querySelector('#modalBuku input[name="penerbit"]').value = data.penerbit;
        document.querySelector('#modalBuku input[name="tahun_terbit"]').value = data.tahun_terbit;
        document.querySelector('#modalBuku select[name="id_sumber_dana"]').value = data.id_sumber_dana;
        document.querySelector('#modalBuku select[name="id_ruangan"]').value = data.id_ruangan;
        document.querySelector('#modalBuku input[name="jumlah"]').value = data.jumlah;
        document.querySelector('#modalBuku input[name="harga_satuan"]').value = data.harga_satuan;
        document.querySelector('#modalBuku input[name="umur_ekonomis"]').value = data.umur_ekonomis || 5;
        document.querySelector('#modalBuku select[name="kondisi"]').value = data.kondisi || 'Baik';
        openModal('modalBuku');
    }
</script>
<?= $this->endSection() ?>
