<?php
use yii\widgets\ActiveForm;
use yii\helpers\Html;

/** @var $model app\models\Nota */
/** @var $barangList app\models\Barang[] */
?>

<?php $form = ActiveForm::begin(); ?>

<div class="row">
  <div class="col-md-6">
    <?= $form->field($model,'pelanggan')->textInput() ?>
  </div>
  <div class="col-md-4">
    <?= $form->field($model,'tanggal')->input('date') ?>
  </div>
</div>

<div class="form-check">
    <input type="checkbox" class="form-check-input" id="ppnCheck" name="ppnUse" value="1"
        <?= $model->ppn ? 'checked' : '' ?>>
    <label class="form-check-label" for="ppnCheck">Gunakan PPN 11%</label>
</div>

<hr>

<table class="table table-bordered">
<thead>
<tr>
<th>Barang</th>
<th width="10%">Qty</th>
<th width="10%">Diskon %</th>
<th width="15%">Harga</th>
<th width="15%">Subtotal</th>
<th width="5%"></th>
</tr>
</thead>

<tbody id="item-table"></tbody>
</table>

<button type="button" id="addRow" class="btn btn-secondary">➕ Tambah Item</button>

<hr>

<h4>Total: Rp <span id="total">0</span></h4>
<h4>PPN 11%: Rp <span id="ppn">0</span></h4>
<h4>Grand Total: Rp <span id="grandTotal">0</span></h4>

<br>
<?= Html::submitButton('Simpan Nota',['class'=>'btn btn-success btn-lg']) ?>

<?php ActiveForm::end(); ?>

<!-- SELECT2 -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<!-- SWEETALERT V1 -->
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>

<script>
document.addEventListener('DOMContentLoaded',function(){

const tableBody = document.getElementById('item-table');
const addBtn = document.getElementById('addRow');
const totalEl = document.getElementById('total');
const ppnEl = document.getElementById('ppn');
const grandEl = document.getElementById('grandTotal');
const ppnCheck = document.getElementById('ppnCheck');

let index = 0;

/* ===== SELECT2 ===== */
function initSelect2(){
 $('.select-barang').select2({width:'100%'});
}
initSelect2();

/* ===== ADD ROW ===== */
addBtn.addEventListener('click',()=>{
let row = `
<tr>
<td>
<select name="items[${index}][barang_id]" class="form-control barang select-barang">
  <option value="">-- pilih barang --</option>
  <?php foreach($barangList as $b): ?>
  <option value="<?= $b->id ?>" data-harga="<?= $b->harga ?>" data-stok="<?= $b->stok ?>"><?= $b->nama ?></option>
  <?php endforeach; ?>
</select>
</td>
<td><input type="number" min="1" name="items[${index}][qty]" class="form-control qty"></td>
<td><input type="number" min="0" max="100" name="items[${index}][diskon]" class="form-control diskon" value="0"></td>
<td><input type="number" name="items[${index}][harga]" class="form-control harga" readonly></td>
<td><input type="number" class="form-control subtotal" readonly></td>
<td><button type="button" class="btn btn-danger btn-sm remove">✖</button></td>
</tr>`;
tableBody.insertAdjacentHTML('beforeend', row);
initSelect2();
index++;
});

/* ===== CHANGE BARANG ===== */
$(document).on('change','.barang',function(){
 const tr = this.closest('tr');
 const opt = this.options[this.selectedIndex];
 if(!opt.value) return;
 tr.querySelector('.harga').value = opt.dataset.harga;
 if(!tr.querySelector('.qty').value) tr.querySelector('.qty').value = 1;
 hitungRow(tr);
});

/* ===== QTY / DISKON INPUT ===== */
tableBody.addEventListener('input', e=>{
 if(e.target.classList.contains('qty') || e.target.classList.contains('diskon')){
   const tr = e.target.closest('tr');
   hitungRow(tr);
 }
});

/* ===== REMOVE ===== */
tableBody.addEventListener('click', e=>{
 if(e.target.classList.contains('remove')){
   e.target.closest('tr').remove();
   hitungTotal();
 }
});

/* ===== QTY INPUT VALIDASI STOK DENGAN SWEETALERT ===== */
/* ===== VALIDASI HANYA ANGKA + ALERT SWEETALERT ===== */
tableBody.addEventListener('keydown', e=>{
  // hanya untuk qty dan diskon
  if(e.target.classList.contains('qty') || e.target.classList.contains('diskon')){
    // allow: backspace, delete, tab, escape, enter, arrow keys
    if([46,8,9,27,13,37,38,39,40].indexOf(e.keyCode) !== -1) return;

    // hanya angka 0-9
    if((e.keyCode < 48 || e.keyCode > 57) && (e.keyCode < 96 || e.keyCode > 105)){
      e.preventDefault(); // cegah input
      swal({
        title: "Input Tidak Valid",
        text: "Hanya boleh angka!",
        icon: "warning",
        button: "OK"
      });
    }
  }
});

// event input untuk paste / drag
tableBody.addEventListener('input', e=>{
  if(e.target.classList.contains('qty') || e.target.classList.contains('diskon')){
    // hapus karakter non-angka
    const val = e.target.value.replace(/\D/g,'');
    if(val !== e.target.value){
      e.target.value = val;
      swal({
        title: "Input Tidak Valid",
        text: "Hanya boleh angka!",
        icon: "warning",
        button: "OK"
      });
    }

    // validasi stok untuk qty
    if(e.target.classList.contains('qty')){
      const tr = e.target.closest('tr');
      const qty = parseFloat(e.target.value||0);
      const stok = parseFloat(tr.querySelector('.barang').selectedOptions[0]?.dataset.stok || 0);

      if(qty > stok){
        e.target.value = stok;
        swal({
          title: "Stok Tidak Cukup",
          text: `Stok barang hanya ${stok}`,
          icon: "warning",
          button: "OK"
        });
      }
    }

    const tr = e.target.closest('tr');
    hitungRow(tr);
  }
});


/* ===== HITUNG ===== */
function hitungRow(tr){
 const qty = parseFloat(tr.querySelector('.qty').value||0);
 const harga = parseFloat(tr.querySelector('.harga').value||0);
 const diskon = parseFloat(tr.querySelector('.diskon').value||0);
 tr.querySelector('.subtotal').value = qty*harga*(1-diskon/100);
 hitungTotal();
}

function hitungTotal(){
 let total = 0;
 document.querySelectorAll('.subtotal').forEach(el=>total+=parseFloat(el.value||0));
 totalEl.innerText = total.toLocaleString();
 const ppn = ppnCheck.checked ? total*0.11 : 0;
 ppnEl.innerText = ppn.toLocaleString();
 grandEl.innerText = (total+ppn).toLocaleString();
}

/* ===== PPN CHECKBOX ===== */
ppnCheck.addEventListener('change', hitungTotal);

});
</script>
