<div class="container mt-4">
    <div class="card modern-card shadow-sm border-0 rounded-4">
        <div class="card-body p-4">

            <div class="d-flex justify-content-between mb-3">
                <h5>Data Asset</h5>
                <div class="text-end">
                    <button class="btn btn-add bg-success btn-from-stock mr-2">Dari Gudang</button>
                    <button class="btn btn-add bg-warning btn-add-asset">Tambah Asset</button>
                </div>
            </div>

            <div class="table-responsive">
                <table id="tableAsset" class="table modern-table w-100">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>Tanggal</th>
                            <th>Kode</th>
                            <th>Nama</th>
                            <th>Lokasi Asset</th>
                            <th>Nilai</th>
                            <th>Masa</th>
                            <th>Susut/Bulan</th>
                            <th>Create</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                </table>
            </div>

        </div>
    </div>
</div>

<!-- MODAL TAMBAH ASSET -->
<div class="modal fade" id="modalAsset">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header bg-warning text-white">
    <h5 id="modalTitleAsset">Tambah Asset</h5>
</div>
<div class="modal-body">
    <input type="hidden" id="id_asset">
    
    <label class="mt-2">Akun Asset (Debit)</label>
    <select id="account_asset" class="form-control"></select>

    <label class="mt-2">Akun Kas (Kredit)</label>
    <select id="account_kas" class="form-control"></select>

    <label class="mt-2">Lokasi Aset</label>
    <select id="lokasi_asset" class="form-control"></select>

    <label>Nama Asset</label>
    <input type="text" id="nama_asset" class="form-control">

    <label class="mt-2">Keterangan</label>
    <input type="text" id="keterangan" class="form-control">

    <label class="mt-2">Harga Per Unit</label>
    <input type="text" id="harga" class="form-control format-rupiah">

    <label class="mt-2">Tanggal</label>
    <input type="date" id="tanggal" class="form-control">

    <hr>

    <label>Masa Manfaat (bulan)</label>
    <input type="number" id="masa" class="form-control">

    <label>Nilai Residu</label>
    <input type="text" id="residu" class="form-control format-rupiah">

    <label>Penyusutan / bulan</label>
    <input type="text" id="susut" class="form-control format-rupiah" readonly>
</div>
<div class="modal-footer">
    <button class="btn btn-warning" id="btnSave">Simpan</button>
</div>
</div>
</div>
</div>

<!-- MODAL EDIT ASSET -->
<div class="modal fade" id="modalEditAsset">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header bg-primary text-white">
    <h5>Edit Asset</h5>
</div>
<div class="modal-body">
    <input type="hidden" id="edit_id">
    
    <label>Nama Asset</label>
    <input type="text" id="edit_nama" class="form-control">

    <label class="mt-2">Lokasi Aset</label>
    <select id="edit_lokasi_asset" class="form-control"></select>

    <label class="mt-2">Keterangan</label>
    <input type="text" id="edit_keterangan" class="form-control">
</div>
<div class="modal-footer">
    <button class="btn btn-primary" id="btnUpdate">Update</button>
</div>
</div>
</div>
</div>

<!-- MODAL DETAIL & HISTORY -->
<div class="modal fade" id="modalDetail">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header bg-info text-white">
    <h5>Detail & History Asset</h5>
</div>
<div class="modal-body">
    <div id="detailContent"></div>
    <hr>
    <h6>History Perubahan:</h6>
    <div class="table-responsive">
        <table class="table table-sm" id="tableHistory">
            <thead>
                <tr>
                    <th>Tanggal</th>
                    <th>Tipe</th>
                    <th>Nilai</th>
                    <th>Keterangan</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>
</div>
</div>
</div>
</div>

<!-- MODAL DARI GUDANG -->
<div class="modal fade" id="modalAssetStock">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header bg-success text-white">
    <h5>Tambah Asset dari Gudang</h5>
</div>
<div class="modal-body">
    <input type="hidden" id="s_item_id">
    <input type="hidden" id="s_harga">

    <label class="mt-2">Akun Asset (Debit)</label>
    <select id="s_account_asset" class="form-control"></select>

    <label class="mt-2">Lokasi Aset</label>
    <select id="s_lokasi_asset" class="form-control"></select>

    <label>Pilih Barang</label>
    <select id="s_item" class="form-control"></select>

    <label class="mt-2">Stok Tersedia</label>
    <input type="text" id="s_stok" class="form-control" readonly>

    <label class="mt-2">Tanggal</label>
    <input type="date" id="s_tanggal" class="form-control">

    <hr>

    <label>Masa Manfaat (bulan)</label>
    <input type="number" id="s_masa" class="form-control">

    <label>Nilai Residu</label>
    <input type="text" id="s_residu" class="form-control format-rupiah">

    <label>Penyusutan / bulan</label>
    <input type="text" id="s_susut" class="form-control format-rupiah" readonly>
</div>
<div class="modal-footer">
    <button class="btn btn-success" id="btnSaveStock">Simpan</button>
</div>
</div>
</div>
</div>

<!-- MODAL DELETE -->
<div class="modal fade" id="modalDelete">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header bg-danger text-white">
    <h5>Hapus Asset</h5>
</div>
<div class="modal-body">
    <input type="hidden" id="delete_id">
    <label>Pilih Alasan:</label>
    <select id="delete_alasan" class="form-control">
        <option value="dijual_untung">Dijual (Untung)</option>
        <option value="dijual_rugi">Dijual (Rugi)</option>
        <option value="dihapus">Dihapus</option>
    </select>
    <label class="mt-2">Keterangan:</label>
    <textarea id="delete_keterangan" class="form-control" rows="3" placeholder="Alasan detail penghapusan..."></textarea>
</div>
<div class="modal-footer">
    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
    <button type="button" class="btn btn-danger" id="btnConfirmDelete">Hapus</button>
</div>
</div>
</div>
</div>

<!-- MODAL DARI STOCK (SAMA) -->
<div class="modal fade" id="modalAssetStock">
<!-- sama seperti sebelumnya, tidak diubah -->
</div>
<script>
$(function(){
let action = 'add';
let table = $('#tableAsset').DataTable({
    ajax:"<?= base_url('asset/get_data'); ?>"
});

// ================= HELPER =================
function formatRupiah(angka){
    if(!angka) return '';
    return angka.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}

function setSelectValue(selector, value){
    setTimeout(()=>{
        $(selector).val(value).trigger('change');
    }, 200);
}

// ================= LOAD SELECTS =================
function loadKas(selected = null){
    $.get("<?= base_url('asset/get_accounts_kas'); ?>",res=>{
        let opt='<option value="">-- PILIH KAS --</option>';
        res.forEach(i=>{
            let sel = (selected && selected == i.id) ? 'selected' : '';
            opt += `<option value="${i.id}" ${sel}>${i.nama_akun}</option>`;
        });
        $('#account_kas').html(opt);
    },'json');
}

function loadAsset(selected = null){
    $.get("<?= base_url('asset/get_accounts_asset'); ?>",res=>{
        let optAsset='<option value="">-- PILIH AKUN ASET --</option>';
        res.forEach(i=>{
            let sel = (selected && selected == i.id) ? 'selected' : '';
            optAsset += `<option value="${i.id}" ${sel}>${i.nama_akun}</option>`;
        });
        $('#account_asset, #s_account_asset').html(optAsset);
    },'json');
}

function loadLokasiAsset(selected = null){
    $.get("<?= base_url('asset/get_lokasi_asset'); ?>",res=>{
        let opt='<option value="">-- PILIH LOKASI --</option>';
        res.forEach(i=>{
            let sel = (selected && selected == i.id) ? 'selected' : '';
            opt += `<option value="${i.id}" ${sel}>${i.nama}</option>`;
        });
        $('#lokasi_asset, #edit_lokasi_asset, #s_lokasi_asset').html(opt);
    },'json');
}

// ================= LOAD ITEMS =================
function loadItems(){
    $.get("<?= base_url('asset/get_items'); ?>",res=>{
        let opt='<option value="">-- PILIH BARANG --</option>';
        res.forEach(i=>{
            opt += `<option value="${i.id}" data-harga="${i.harga_beli}" data-stok="${i.stok}" data-nama="${i.nama_barang}">
                ${i.kode_detail} - ${i.nama_barang} - ( Stok: ${i.stok})
            </option>`;
        });
        $('#s_item').html(opt);
    },'json');
}

// ================= HITUNG PENYUSUTAN MANUAL =================
function hitungSusut(){
    let harga = parseInt($('#harga').val().replace(/\D/g,'')) || 0;
    let residu = parseInt($('#residu').val().replace(/\D/g,'')) || 0;
    let masa = parseInt($('#masa').val()) || 1;
    let susut = (harga - residu) / masa;
    $('#susut').val(formatRupiah(Math.round(susut)));
}

$('#masa, #residu, #harga').on('keyup change',hitungSusut);

// ================= HITUNG SUSUT STOCK =================
$('#s_masa, #s_residu').on('keyup change',function(){
    let harga = parseInt($('#s_harga').val()) || 0;
    let residu = parseInt($('#s_residu').val().replace(/\D/g,'')) || 0;
    let masa = parseInt($('#s_masa').val()) || 1;
    let susut = (harga - residu) / masa;
    $('#s_susut').val(formatRupiah(Math.round(susut)));
});

// ================= TAMBAH ASSET MANUAL =================
$('.btn-add-asset').click(function(){
    action='add';
    $('#modalTitleAsset').text('Tambah Asset');
    $('#modalAsset input[type="text"], #modalAsset input[type="date"], #modalAsset input[type="number"], #modalAsset select').val('');
    $('#id_asset').val('');
    loadKas(); loadAsset(); loadLokasiAsset();
    $('#modalAsset').modal('show');
});

// ================= DETAIL & HISTORY =================
$(document).on('click','.btn-detail',function(){
    let id = $(this).data('id');
    
    $.get("<?= base_url('asset/detail/'); ?>"+id, function(asset){
        $('#detailContent').html(`
            <table class="table table-borderless">
                <tr><td><strong>Kode Asset</strong></td><td>: <strong>${asset.kode_asset || '-'}</strong></td></tr>
                <tr><td><strong>Nama Asset</strong></td><td>: <strong>${asset.nama_asset}</strong></td></tr>
                <tr><td><strong>Lokasi</strong></td><td>: <strong>${asset.nama_lokasi || '-'}</strong></td></tr>
                <tr><td><strong>Harga/Unit</strong></td><td>: <strong>Rp ${formatRupiah(asset.harga_per_unit)}</strong></td></tr>
                <tr><td><strong>Nilai Buku</strong></td><td>: <strong>Rp ${formatRupiah(asset.nilai_buku)}</strong></td></tr>
                <tr><td><strong>Masa Manfaat</strong></td><td>: <strong>${asset.masa_manfaat} bulan</strong></td></tr>
                <tr><td><strong>Sumber</strong></td><td>: <strong>${asset.sumber}</strong></td></tr>
                <tr><td><strong>Keterangan</strong></td><td>: <strong>${asset.keterangan || '-'}</strong></td></tr>
            </table>
        `);

        // Load history
        $.get("<?= base_url('asset/get_history/'); ?>"+id, function(history){
            let rows = '';
            if(history.length === 0){
                rows = '<tr><td colspan="5" class="text-center">Belum ada history</td></tr>';
            }else{
                history.forEach(h=>{
                    let badgeClass = h.tipe=='perolehan' ? 'bg-success' : 
                                   h.tipe=='penambahan' ? 'bg-info' : 
                                   h.tipe=='pengurangan' ? 'bg-warning' : 'bg-secondary';
                    rows += `<tr>
                        <td>${h.created_at}</td>
                        <td><span class="badge ${badgeClass}">${h.tipe}</span></td>
                        <td>Rp ${formatRupiah(h.nilai || 0)}</td>
                        <td>${h.keterangan}</td>
                    </tr>`;
                });
            }
            $('#tableHistory tbody').html(rows);
        },'json');

        $('#modalDetail').modal('show');
    },'json');
});

// ================= EDIT ASSET =================
$(document).on('click','.btn-edit',function(){
    let id = $(this).data('id');
    
    $.get("<?= base_url('asset/detail/'); ?>"+id,function(res){
        $('#edit_id').val(res.id);
        $('#edit_nama').val(res.nama_asset);
        $('#edit_keterangan').val(res.keterangan || '');
        loadLokasiAsset(res.lokasi_asset_id);
        $('#modalEditAsset').modal('show');
    },'json');
});

// ================= UPDATE ASSET =================
$('#btnUpdate').click(function(){
    let btn = $(this);
    let data = {
        id: $('#edit_id').val(),
        nama_asset: $('#edit_nama').val(),
        lokasi_asset: $('#edit_lokasi_asset').val(),
        keterangan: $('#edit_keterangan').val()
    };

    if(!data.nama_asset){
        Swal.fire('Error','Nama asset wajib diisi','error');
        return;
    }

    btn.prop('disabled', true).html('Menyimpan...');
    
    $.post("<?= base_url('asset/update'); ?>", data, function(res){
        if(res.status){
            $('#modalEditAsset').modal('hide');
            table.ajax.reload(null,false);
            Swal.fire('Berhasil','Asset berhasil diupdate','success');
        }
    },'json').always(()=>{
        btn.prop('disabled', false).html('Update');
    });
});

// ================= DELETE =================
$(document).on('click','.btn-delete',function(){
    let id = $(this).data('id');
    $('#delete_id').val(id);
    $('#delete_keterangan').val('');
    $('#modalDelete').modal('show');
});

$('#btnConfirmDelete').click(function(){
    let btn = $(this);
    let keterangan = $('#delete_keterangan').val().trim();
    
    if(!keterangan){
        Swal.fire('Error','Keterangan wajib diisi','error');
        return;
    }

    let data = {
        id: $('#delete_id').val(),
        alasan: $('#delete_alasan').val(),
        keterangan: keterangan
    };

    btn.prop('disabled', true).html('Menghapus...');
    
    $.post("<?= base_url('asset/delete'); ?>", data, function(res){
        if(res.status){
            $('#modalDelete').modal('hide');
            table.ajax.reload(null,false);
            Swal.fire('Berhasil','Asset berhasil dihapus','success');
        }
    },'json').always(()=>{
        btn.prop('disabled', false).html('Hapus');
    });
});

// ================= SAVE ASSET MANUAL =================
$('#btnSave').click(function(){
    let btn = $(this);
    let data = {
        id: $('#id_asset').val(),
        nama_asset: $('#nama_asset').val(),
        harga: $('#harga').val(),
        tanggal: $('#tanggal').val(),
        masa: $('#masa').val(),
        residu: $('#residu').val(),
        account_kas: $('#account_kas').val(),
        account_asset: $('#account_asset').val(),
        lokasi_asset: $('#lokasi_asset').val(),
        keterangan: $('#keterangan').val()
    };

    // Validasi
    if(!data.nama_asset || !data.harga || !data.tanggal || !data.account_kas || !data.account_asset){
        Swal.fire('Error','Semua field wajib diisi','error');
        return;
    }

    btn.prop('disabled', true).html('Menyimpan...');

    let url = action==='add' ? "<?= base_url('asset/save'); ?>" : "<?= base_url('asset/update'); ?>";

    $.post(url, data, function(res){
        if(res.status){
            $('#modalAsset').modal('hide');
            table.ajax.reload(null,false);
            Swal.fire({icon:'success',title:'Berhasil',timer:1500,showConfirmButton:false});
        }
    },'json').always(()=>{
        btn.prop('disabled', false).html('Simpan');
    });
});

// ================= FROM STOCK =================
$('.btn-from-stock').click(function(){
    $('#modalAssetStock input[type="text"], #modalAssetStock input[type="date"], #modalAssetStock input[type="number"], #modalAssetStock select').val('');
    $('#s_item_id, #s_harga').val('');
    loadItems();
    loadAsset();
    loadLokasiAsset();
    $('#modalAssetStock').modal('show');
});

// ================= PILIH ITEM STOCK =================
$(document).on('change','#s_item',function(){
    let selected = $(this).find(':selected');
    let harga = selected.data('harga') || 0;
    let stok = selected.data('stok') || 0;
    $('#s_item_id').val($(this).val());
    $('#s_harga').val(harga);
    $('#s_stok').val(stok);
});

// ================= SAVE FROM STOCK =================
$('#btnSaveStock').click(function(){
    let btn = $(this);
    let data = {
        item_id: $('#s_item').val(),
        s_tanggal: $('#s_tanggal').val(),
        s_masa: $('#s_masa').val(),
        s_residu: $('#s_residu').val(),
        s_lokasi_asset: $('#s_lokasi_asset').val(),
        account_asset: $('#s_account_asset').val()
    };

    // Validasi
    if(!data.item_id || !data.s_tanggal || !data.account_asset || !data.s_lokasi_asset){
        Swal.fire('Error','Item, tanggal, akun asset, dan lokasi wajib diisi','error');
        return;
    }

    btn.prop('disabled', true).html('Menyimpan...');

    $.post("<?= base_url('asset/save_from_stock'); ?>",data,function(res){
        if(res.status){
            $('#modalAssetStock').modal('hide');
            table.ajax.reload(null,false);
            Swal.fire({
                icon:'success',
                title:'Berhasil!',
                text:'Asset dari gudang berhasil dibuat',
                timer:2000,
                showConfirmButton:false
            });
        }else{
            Swal.fire('Error',res.message,'error');
        }
    },'json').always(()=>{
        btn.prop('disabled', false).html('Simpan');
    });
});

});
</script>