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

<?= Html::csrfMetaTags() ?>

<table id="notaTable" class="table table-bordered">
<thead>
<tr>
    <th>No</th>
    <th>Nomor</th>
    <th>Tanggal</th>
    <th>Pelanggan</th>
    <th>Total</th>
    <th>Aksi</th>
</tr>
</thead>
<tbody>
<?php foreach($data as $i=>$row): ?>
<tr data-id="<?= $row->id ?>">
    <td><?= $i+1 ?></td>
    <td><?= $row->nomor ?></td>
    <td><?= $row->tanggal ?></td>
    <td><?= $row->pelanggan ?></td>
    <td><?= number_format($row->total) ?></td>
    <td>
        <?= Html::a('👁', ['view','id'=>$row->id], ['class'=>'btn btn-info btn-sm']) ?>
        <?= Html::a('✏', ['update','id'=>$row->id], ['class'=>'btn btn-warning btn-sm']) ?>
        <!-- <button class="btn btn-danger btn-sm btn-delete">Delete</button> -->
        <?= Html::a('🗑', ['nota/hapus', 'id' => $row->id], [
                    'class' => 'btn btn-danger btn-sm btn-delete',
                    'data-method' => 'post',        // Yii otomatis pakai POST + CSRF
                    'data-confirm' => 'Apakah Anda yakin ingin menghapus data ini?'
                ]) ?>
    </td>
</tr>
<?php endforeach; ?>
</tbody>
</table>

<script>
$(document).ready(function(){
    var table = $('#notaTable').DataTable({
                    order: [[0, 'desc']] // kolom index 0 = id
                });
});

$('#notaTable').on('click', '.btn-delete', function() {
        var btn = $(this);
        var id = btn.data('id');
        var url = btn.data('url');

        if (confirm('Apakah Anda yakin ingin menghapus data ini?')) {
            $.ajax({
                url: url,
                type: 'POST',
                success: function(res) {
                    if (res.status === 'success') {
                        table.row($('#row-' + id)).remove().draw();
                        alert(res.message);
                    } else {
                        alert(res.message);
                    }
                },
                error: function() {
                    alert('Terjadi kesalahan saat menghapus data.');
                }
            });
        }
    });
</script>

