<?php
use yii\helpers\Html;
use yii\helpers\Url;
?>

<p>
    <?= Html::a('Tambah Barang', Url::to(['barang/form']), [
        'class'=>'btn btn-success btn-sm',
        'data-toggle'=>'modal',
        'data-target'=>'#modal-barang'
    ]) ?>
</p>

<table id="table-barang" class="table table-bordered table-striped w-100">
    <thead>
        <tr>
            <th>ID</th>
            <th>Kode</th>
            <th>Nama</th>
            <th>Harga</th>
            <th>Stok</th>
            <th>Status</th>
            <th>Aksi</th>
        </tr>
    </thead>
</table>

<div class="modal fade" id="modal-barang">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-body" id="modal-barang-content"></div>
    </div>
  </div>
</div>

<script>
// declare global
var tableBarang;

$(document).ready(function(){
    tableBarang = $('#table-barang').DataTable({
        ajax: '<?= Url::to(["barang/list"]) ?>',
        order: [[0, 'desc']], // ← tambahkan ini
        columns: [
            {data:'id'},
            {data:'kode'},
            {data:'nama'},
            {data:'harga', render: $.fn.dataTable.render.number(',', '.', 0, '')},
            {data:'stok'},
            {data:'status'},
            {data:'action', orderable:false, searchable:false}
        ]
    });
});


$(document).ready(function(){


    // Modal Add/Edit
    $('#modal-barang').on('show.bs.modal', function(event){
        var button = $(event.relatedTarget);
        var url = button.attr('href');
        $('#modal-barang-content').html('<div class="text-center p-3">Loading...</div>');
        $.get(url, function(data){
            $('#modal-barang-content').html(data);
        });
    });

    // Submit form via AJAX
    $(document).on('beforeSubmit','#barang-form', function(e){
        e.preventDefault();
        var form = $(this);
        $.post(form.attr('action'), form.serialize(), function(res){
            if(res.success){
                $('#modal-barang').modal('hide');
                tableBarang.ajax.reload(null,false);
                swal("Berhasil!", res.message,"success");
            } else {
                swal("Gagal!", res.message,"error");
            }
        },'json').fail(function(){
            swal("Error!","Kesalahan server!","error");
        });
        return false;
    });

    // Delete Barang
    $(document).on('click','.btn-delete-barang', function(){
        var id = $(this).data('id');
        var csrfParam = $('meta[name=csrf-param]').attr('content');
        var csrfToken = $('meta[name=csrf-token]').attr('content');

        swal({
            title:"Yakin ingin menghapus?",
            text:"Data tidak bisa dikembalikan!",
            icon:"warning",
            buttons:["Batal","Hapus"],
            dangerMode:true
        }).then(function(willDelete){
            if(willDelete){
                var postData = {id:id};
                postData[csrfParam] = csrfToken;
                $.post('<?= Url::to(['barang/delete']) ?>', postData, function(res){
                    if(res.success){
                        tableBarang.ajax.reload(null,false);
                        swal("Terhapus!", res.message,"success");
                    } else {
                        swal("Gagal!", res.message,"error");
                    }
                },'json').fail(function(){
                    swal("Error!","Kesalahan server!","error");
                });
            }
        });
    });

});


$(document).off('click','#btn-save-barang').on('click','#btn-save-barang', function(e){
    e.preventDefault();
    var form = $('#barang-form');

    swal({
        title: "Menyimpan...",
        text: "Silakan tunggu",
        buttons: false,
        closeOnClickOutside: false,
        closeOnEsc: false,
        icon: "info"
    });

    $.post(form.attr('action'), form.serialize(), function(res){
        swal.close();
        if(res.success){
            // close modal
            $('#modal-barang').modal('hide');

            // reload DataTable global
            if(tableBarang){
                tableBarang.ajax.reload(null, false);
            }

            swal("Berhasil!", res.message, "success");
        } else {
            swal("Gagal!", res.message || "Gagal menyimpan", "error");
        }
    }, 'json').fail(function(){
        swal("Error!", "Kesalahan server", "error");
    });
});

</script>
