<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 Barang Dalam Perjalanan</h5>
                <div class="text-end">
                    <button class="btn btn-warning btn-add btn-add-item mr-2">Tambah Barang</button>
                </div>
            </div>

            <div class="table-responsive">
                <table id="tableItems" class="table modern-table w-100">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>Tanggal Beli</th>
                            <th>Kode Barang</th>
                            <th>Nama</th>
                            <th style="max-width: 150px;">Gudang</th>
                            <th>Stok</th>
                            <th>Harga Beli</th>
                            <th>Harga Jual</th>
                            <th>Create at</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                </table>
            </div>

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

<!-- MODAL -->
<div class="modal fade" id="modalItem">
<div class="modal-dialog modal-dialog-centered modal-xl">
<div class="modal-content">

<div class="modal-header bg-warning text-white">
    <h5>Item</h5>
</div>

<div class="modal-body">

<input type="hidden" id="id">

<div class="row">
    <div class="col-md-6">
        <div id="group_tanggal">
            <label>Tanggal Pembelian</label>
            <input type="date" id="tanggal_beli" class="form-control">
        </div>
    </div>
    <div class="col-md-6">
        <div id="group_kode">
            <label class="mt-2">Kode Barang</label>
            <select id="kode_barang" class="form-control select-search"></select>
        </div>
    </div>
</div>

<label>Nama Barang</label>
<input type="text" id="nama_barang" class="form-control">

<div class="row">
    <div class="col-md-2">
        <div id="group_qty">
            <label class="mt-2">Jumlah Barang</label>
            <input type="number" id="qty" class="form-control">
        </div>
    </div>
    <div class="col-md-2">
        <div id="group_tracking_qty">
            <label class="mt-2">Jml / (Roll, Box, Dus)</label>
            <input type="number" id="tracking_qty" class="form-control">
        </div>
    </div>
    <div class="col-md-4">
        <label class="mt-2">Harga Beli</label>
        <div class="input-group">
            <span class="input-group-text">Rp</span>
            <input type="text" id="harga_beli" class="form-control format-rupiah">
        </div>
    </div>
    <div class="col-md-4">
        <label class="mt-2">Harga Jual</label>
        <div class="input-group">
            <span class="input-group-text">Rp</span>
            <input type="text" id="harga_jual" class="form-control format-rupiah">
        </div>
    </div>
</div>

<div  id="group_warehouse">
    <label class="mt-2">Gudang</label>
    <select id="warehouse_id" class="form-control"></select>
</div>

<!-- <div class="row">
    <label class="mt-2">Akun Kas</label>
    <div class="col-md-7">
        <div id="group_account">
            <select id="account_kas" class="form-control"></select>
        </div>
    </div>
    <div class="col-md-5">
        <div class="input-group">
            <span class="input-group-text">Rp</span>
            <input type="text" id="account[]" class="form-control format-rupiah">
        </div>
    </div>
</div>
<button class="btn btn-warning btn-sm mt-4">Tambah Account</button> -->

<hr>
<label class="font-weight-bold">
    Pembayaran
</label>
<div id="accountContainer">
    <div class="row account-row mb-2">
        <div class="col-md-6">
            <select
                name="account_kas[]"
                class="form-control account_kas">
            </select>
        </div>
        <div class="col-md-4">
            <div class="input-group">
                <span class="input-group-text">Rp</span>
                <input
                    type="text"
                    name="nominal[]"
                    class="form-control nominal format-rupiah">
            </div>
        </div>
        <div class="col-md-2">
            <button
                type="button"
                class="btn btn-sm btn-danger btn-remove-account w-100"
                disabled>
                Hapus
            </button>
        </div>
    </div>
</div>
<div class="mt-2">
    <button
        type="button"
        id="btnTambahAccount"
        class="btn btn-warning btn-sm">
        + Tambah Account
    </button>
</div>
<div class="mt-3">
    <div class="row">
        <div class="col-md-4">
            <!-- total qty * harga beli -->
            <h5>
                Total :
                <span id="totalHppBarang">
                    Rp 0
                </span>
            </h5>
        </div>
        <div class="col-md-4">
            <!-- total accounting -->
            <h5>
                Total :
                <span id="totalAccount">
                    Rp 0
                </span>
            </h5>
        </div>
        <div class="col-md-4">
            <!-- balance accounting + total hpp barang -->
            <h5>
                Total :
                <span id="totalAll">
                    Rp 0
                </span>
            </h5>
        </div>
    </div>
</div>



</div>

<div class="modal-footer">
    <button class="btn btn-warning" id="btnSimpan">Simpan</button>
</div>

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

<!-- MODAL DETAIL -->
<div class="modal fade" id="modalDetail">
<div class="modal-dialog modal-lg">
<div class="modal-content">

<div class="modal-header bg-warning text-white">
    <h5>Detail Item</h5>
</div>

<div class="modal-body" id="detailContent"></div>

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


<script>

$(function(){

let action = 'add';
let selectedItemId = null;
let accountOption = '';

// ================= DATATABLE =================
let table = $('#tableItems').DataTable({
    ajax: {
        url: "<?= base_url('items/get_data'); ?>",
        data: function (d) {
            d.s = `draft`;
        }
    }
});

// ================= LOAD AKUN KAS =================
// function loadKas(){
//     $.get("<?= base_url('items/get_accounts'); ?>",res=>{
//         let opt='<option value="">-- PILIH KAS --</option>';
//         res.forEach(a=>{
//             opt += `<option value="${a.id}">${a.nama_akun}</option>`;
//         });
//         $('#account_kas').html(opt);
//     },'json');
// }
function loadKas(){
    $.get("<?= base_url('items/get_accounts'); ?>",function(res){
        accountOption = '<option value="">-- PILIH KAS --</option>';
        res.forEach(function(a){
            accountOption += `
                <option value="${a.id}">
                    ${a.nama_akun}
                </option>
            `;
        });
        $('.account_kas').html(accountOption);
    },'json');
}

// ================= LOAD GUDANG =================
function loadGudang(){
    $.get("<?= base_url('warehouses/list'); ?>",res=>{
        let opt='<option value="">-- PILIH GUDANG --</option>';
        res.forEach(w=>{
            opt += `<option value="${w.id}">${w.nama}</option>`;
        });
        $('#warehouse_id, #adjust_warehouse').html(opt);
    },'json');
}

function loadKode() {
    $.get("<?= base_url('kodebarang/list'); ?>", function(res) {

        let opt = '<option value="">-- PILIH KODE --</option>';

        res.forEach(function(a){
            opt += `
                <option value="${a.id}"
                        data-type="${a.tracking_type}">
                    ${a.kode_barang} - ${a.nama}
                </option>
            `;
        });

        $('#kode_barang').html(opt).trigger('change');
    }, 'json');
}

function addAccountRow(){
    let html = `
    <div class="row account-row mb-2">
        <div class="col-md-6">
            <select
                name="account_kas[]"
                class="form-control account_kas">
                ${accountOption}
            </select>
        </div>
        <div class="col-md-4">
            <div class="input-group">
                <span class="input-group-text">
                    Rp
                </span>
                <input
                    type="text"
                    name="nominal[]"
                    class="form-control nominal format-rupiah">
            </div>
        </div>
        <div class="col-md-2">
            <button
                type="button"
                class="btn btn-sm btn-danger btn-remove-account w-100">
                Hapus
            </button>
        </div>
    </div>
    `;
    $('#accountContainer').append(html);
    hitungTotal();
}

$(document).on('change', '#kode_barang', function () {

    let type = $(this).find(':selected').data('type');

    if(type == 'QTY'){
        $('#group_tracking_qty').show();
    }else{
        $('#group_tracking_qty').hide();
        $('#tracking_qty').val('');
    }

});

$('#btnTambahAccount').click(function(){
    addAccountRow();
});

$(document).on('click','.btn-remove-account',function(){
    $(this).closest('.account-row').remove();
    hitungTotal();
});

// function hitungTotal(){
//     let total = 0;
//     $('.nominal').each(function(){
//         let angka = $(this)
//             .val()
//             .replace(/\./g,'')
//             .replace(/,/g,'');
//         total += Number(angka || 0);
//     });
//     $('#totalAccount').text(formatRupiah(total.toString()));
// }

$(document).on('keyup','.nominal',function(){
    hitungTotal();
});

$(document).on('keyup','#harga_beli',function(){
    hitungTotal();
});

$(document).on('keyup change','#qty',function(){
    hitungTotal();
});

// ================= RESET FORM =================
function resetForm(){
    $('#id').val('');
    $('#nama_barang').val('');
    $('#qty').val('');
    $('#harga_beli').val('');
    $('#harga_jual').val('');
    $('#tanggal_beli').val('');
    $('#tracking_qty').val('');
    $('#group_tracking_qty').hide();
    $('#accountContainer').html(`
    <div class="row account-row mb-2">
        <div class="col-md-6">
            <select
                name="account_kas[]"
                class="form-control account_kas">
                ${accountOption}
            </select>
        </div>
        <div class="col-md-4">
            <div class="input-group">
                <span class="input-group-text">Rp</span>
                <input
                    type="text"
                    name="nominal[]"
                    class="form-control nominal format-rupiah">
            </div>
        </div>
        <div class="col-md-2">
            <button
                class="btn btn-sm btn-danger btn-remove-account w-100"
                disabled>
                Hapus
            </button>
        </div>
    </div>
    `);
    $('#totalAccount').text('Rp 0');
    $('#totalHppBarang').text('Rp 0');

    $('#totalAll')
        .text('Balance')
        .removeClass('text-danger')
        .addClass('text-success');

    $('#btnSimpan').prop('disabled',true);
}

// ================= INIT LOAD =================
loadGudang();
loadKas();
loadKode();

// ================= ADD =================
$('.btn-add-item').click(function(){
    action='add';
    resetForm();

    $('#qty').closest('div').show();
    $('#kode_barang').closest('div').show();
    $('#warehouse_id').closest('div').show();
    $('#account_kas').closest('div').show();
    $('#modalItem').modal('show');
    loadGudang();
    loadKas();
    loadKode();
});

// ================= EDIT =================
$(document).on('click','.btn-editItem',function(){

    let id = $(this).data('id');
    action='edit';

    $.get("<?= base_url('items/detail_simple/'); ?>"+id,function(res){

        $('#id').val(res.id);
        $('#nama_barang').val(res.nama_barang);
        $('#harga_beli').val(res.harga_beli);
        $('#harga_jual').val(res.harga_jual);

        // 🔥 FIX DI SINI
        $('#group_qty').hide();
        $('#group_account').hide();
        $('#group_kode').hide();
        $('#group_warehouse').hide();
        $('#group_tanggal').hide();

        $('#modalItem').modal('show');

    },'json');


});

// ================= SAVE =================
$('#btnSimpan').click(function(){

    let btn = $(this);

    let qtys = parseFloat($('#qty').val()) || 0;

    let totalHpp = qtys * rupiahToNumber($('#harga_beli').val());

    let totalAccount = 0;

    $('.nominal').each(function(){

        totalAccount += rupiahToNumber($(this).val());

    });

    if(totalHpp != totalAccount){

        Swal.fire({
            icon:'warning',
            title:'Belum Balance',
            text:'Total pembayaran harus sama dengan Total Harga Beli.'
        });

        return;
    }

    let account = [];
    $('.account-row').each(function(){
        account.push({
            account_id: $(this).find('.account_kas').val(),
            nominal: $(this)
                .find('.nominal')
                .val()
        });
    });
    // data.accounts = account;

    let data = {
        id: $('#id').val(),
        kode_id: $('#kode_barang').val(),
        nama_barang: $('#nama_barang').val(),
        qty: $('#qty').val(),
        harga_beli: $('#harga_beli').val(),
        harga_jual: $('#harga_jual').val(),
        warehouse_id: $('#warehouse_id').val(),
        // account_kas: $('#account_kas').val(),
        account_kas: account,
        tanggal_beli: $('#tanggal_beli').val(),
        tracking_qty: $('#tracking_qty').val(),
        status: `draft`
    };

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

    // 🔥 loading state
    btn.prop('disabled', true).html('Menyimpan...');

    $.post(url, data, function(res){

        if(res.status){

            $('#modalItem').modal('hide');
            table.ajax.reload(null,false);

            Swal.fire({
                icon: 'success',
                title: 'Berhasil',
                text: res.message || 'Data berhasil disimpan',
                timer: 1500,
                showConfirmButton: false
            });

        }else{

            Swal.fire({
                icon: 'error',
                title: 'Gagal',
                text: res.message || 'Terjadi kesalahan'
            });
        }

    },'json')
    .fail(function(){

        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'Koneksi ke server gagal'
        });

    })
    .always(function(){
        btn.prop('disabled', false).html('Simpan');
    });

});


// ================= PRINT BARCODE =================
$(document).on('click', '.btn-print', function () {

    let id = $(this).data('id');

    Swal.fire({
        title: 'Cetak Barcode',
        html: `
            <div class="text-left">

                <div class="form-group">
                    <label for="print_column" class="font-weight-bold">
                        Jumlah Kolom
                    </label>
                    <select id="print_column" class="form-control">
                        <option value="1">1 Kolom</option>
                        <option value="2">2 Kolom</option>
                        <option value="3" selected>3 Kolom (Rekomendasi)</option>
                    </select>
                </div>

                <div class="form-group mb-0">
                    <label for="duplicat" class="font-weight-bold">
                        Jumlah Cetak per Barcode
                    </label>
                    <select id="duplicat" class="form-control">
                        <option value="1" selected>1 Label</option>
                        <option value="2">2 Label</option>
                    </select>
                </div>

            </div>
        `,
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Cetak',
        cancelButtonText: 'Batal',
        confirmButtonColor: '#f0ad4e',
        preConfirm: () => {

            let column = $('#print_column').val();
            let duplicat = $('#duplicat').val();

            return {
                column: column,
                duplicat: duplicat
            };

        }

    }).then((result) => {

        if (!result.isConfirmed) {
            return;
        }

        window.open(
            "<?= base_url('items/print_barcode/'); ?>" +
            id +
            "?column=" + result.value.column +
            "&duplicat=" + result.value.duplicat,
            "_blank"
        );

    });

});

// ================= DELETE =================
$(document).on('click','.btn-delete',function(){

    let id = $(this).data('id');
    let btn = $(this);

    Swal.fire({
        title: 'Hapus data?',
        text: "Data tidak bisa dikembalikan!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Ya, hapus!',
        cancelButtonText: 'Batal'
    }).then((result) => {

        if(result.isConfirmed){

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

            $.get("<?= base_url('items/delete/'); ?>"+id,function(res){

                if(res.status){

                    table.ajax.reload(null,false);

                    Swal.fire({
                        icon: 'success',
                        title: 'Berhasil',
                        text: res.message || 'Data berhasil dihapus',
                        timer: 1500,
                        showConfirmButton: false
                    });

                }else{

                    Swal.fire({
                        icon: 'error',
                        title: 'Gagal',
                        text: res.message || 'Gagal menghapus data'
                    });
                }

            },'json')
            .fail(function(){

                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'Koneksi ke server gagal'
                });

            })
            .always(function(){
                btn.prop('disabled', false).html('Hapus');
            });

        }
    });

});


// ================= POSTING =================
$(document).on('click','.btn-updatePosting',function(){

    let id = $(this).data('id');
    let btn = $(this);

    if(btn.data('loading')) return;

    Swal.fire({
        title: 'Konfirmasi Penerimaan Barang',
        text: 'Pastikan barang sudah diterima dan sesuai pesanan. Stok akan otomatis ditambahkan ke gudang.',
        icon: 'info',
        showCancelButton: true,
        confirmButtonColor: '#28a745',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Ya, Terima Barang',
        cancelButtonText: 'Batal'
    }).then((result) => {

        if(result.isConfirmed){

            btn.data('loading', true)
               .prop('disabled', true)
               .html('Memposting...');

            $.post("<?= base_url('items/posting'); ?>", {
                id: id
                // tambahkan CSRF kalau perlu
            }, function(res){

                if(res && res.status){

                    table.ajax.reload(null,false);

                    Swal.fire({
                        icon: 'success',
                        title: 'Berhasil',
                        text: res.message || 'Data berhasil diposting',
                        timer: 1500,
                        showConfirmButton: false
                    });

                }else{

                    Swal.fire({
                        icon: 'error',
                        title: 'Gagal',
                        text: res?.message || 'Gagal memposting data'
                    });
                }

            },'json')
            .fail(function(xhr){

                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: xhr.responseJSON?.message || 'Server error ('+xhr.status+')'
                });

            })
            .always(function(){
                btn.prop('disabled', false)
                   .html('Posting')
                   .data('loading', false);
            });

        }
    });

});

// ================= DETAIL =================
$(document).on('click','.btn-detail',function(){

    let id = $(this).data('id');

    $.get("<?= base_url('items/detail/'); ?>"+id,function(res){

        let html = `
            <b>Nama :</b> ${res.item.nama_barang}<br>
            <b>Harga Beli :</b> ${formatRupiah(res.item.harga_beli)}<br>
            <b>Harga Jual :</b> ${formatRupiah(res.item.harga_jual)}
            <hr>
            <h6>Riwayat Stok</h6>
            <table class="table table-sm table-bordered">
            <tr>
                <th>Tanggal</th>
                <th>Gudang</th>
                <th>Qty</th>
                <th>Tipe</th>
                <th>Keterangan</th>
            </tr>
        `;

        res.logs.forEach(l=>{
            html += `
            <tr>
                <td>${l.created_at ?? '-'}</td>
                <td>${l.gudang ?? '-'}</td>
                <td>${l.qty}</td>
                <td>${l.tipe}</td>
                <td>${l.keterangan ?? ''}</td>
            </tr>`;
        });

        html += `</table>`;

        $('#detailContent').html(html);
        $('#modalDetail').modal('show');

    },'json');

});

function rupiahToNumber(value){

    if(!value) return 0;

    return parseInt(
        value.toString()
             .replace(/[^\d]/g,'')
    ) || 0;

}

function hitungTotal(){

    // ==========================
    // HPP BARANG
    // ==========================

    let qty         = parseFloat($('#qty').val()) || 0;
    let hargaBeli   = rupiahToNumber($('#harga_beli').val());

    let totalHpp = qty * hargaBeli;


    // ==========================
    // ACCOUNTING
    // ==========================

    let totalAccount = 0;

    $('.nominal').each(function(){

        totalAccount += rupiahToNumber($(this).val());

    });


    // ==========================
    // BALANCE
    // ==========================

    let balance = totalAccount - totalHpp;


    $('#totalHppBarang').text(formatRupiah(totalHpp.toString()));
    $('#totalAccount').text(formatRupiah(totalAccount.toString()));

    if(balance == 0){

        $('#totalAll')
            .removeClass('text-danger')
            .addClass('text-success')
            .text('Balance');

        $('#btnSimpan').prop('disabled',false);

    }else{

        let prefix = balance > 0 ? '+' : '-';

        $('#totalAll')
            .removeClass('text-success')
            .addClass('text-danger')
            .text(prefix + ' ' + formatRupiah(Math.abs(balance).toString()));

        $('#btnSimpan').prop('disabled',true);

    }

}

});
</script>