<?php
use yii\widgets\ActiveForm;
use yii\helpers\Html;
use yii\helpers\Url;
use nota\models\Voucher;

$this->title = "Update Nota";

$voucher = Voucher::find()->where(['id'=>$model->voucher_id])->one();
if(isset($voucher)){
  $kode = $voucher->kode;
}else{
  $kode = '';
}
?>

<?php $form = ActiveForm::begin(['id'=>'nota-form']); ?>

<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">
    <?= Html::checkbox(
        'ppnUse',
        $model->ppn > 0 ? true : false,
        ['id'=>'ppnCheck','class'=>'form-check-input','value'=>1]
    ) ?>
    <label class="form-check-label">Gunakan PPN 11%</label>
</div>

<!-- Hidden Voucher -->
<input type="hidden" id="voucherId" name="voucher_id" value="<?= $model->voucher_id ?>">
<input type="hidden" id="voucherValue" name="voucher_value" value="<?= $model->voucher ?>">
<input type="hidden" id="voucherType" name="voucher_type" value="<?= $model->voucher_type ?>">

<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">

    <?php foreach($model->items as $i=>$item): ?>
    <tr>
        <td>
            <select name="items[<?= $i ?>][barang_id]" class="form-control barang">
                <?php foreach($barangList as $b): ?>
                    <option value="<?= $b->id ?>"
                        data-harga="<?= $b->harga ?>"
                        data-stok="<?= $b->stok ?>"
                        <?= $item->barang_id==$b->id?'selected':'' ?>>
                        <?= $b->nama ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </td>
        <td>
            <input type="number"
                   name="items[<?= $i ?>][qty]"
                   class="form-control qty"
                   value="<?= $item->qty ?>">
        </td>
        <td>
            <input type="number"
                   name="items[<?= $i ?>][diskon]"
                   class="form-control diskon"
                   value="<?= $item->diskon ?>">
        </td>
        <td>
            <input type="number"
                   class="form-control harga"
                   value="<?= $item->harga ?>"
                   readonly>
        </td>
        <td>
            <input type="number"
                   class="form-control subtotal"
                   value="<?= $item->subtotal ?>"
                   readonly>
        </td>
        <td>
            <button type="button" class="btn btn-danger remove">✖</button>
        </td>
    </tr>
    <?php endforeach; ?>

    </tbody>
</table>

<hr>

<div class="row mt-4">

<!-- ================= LEFT : TOTAL ================= -->
<div class="col-md-6">
<div class="card shadow-sm">
<div class="card-header bg-dark text-white">
<strong>Ringkasan Pembayaran</strong>
</div>

<div class="card-body">

<div class="mb-3">
<label>Kode Voucher</label>
<div class="input-group">
<input type="text" id="voucherCode" class="form-control" placeholder="Masukkan kode voucher" value="<?= $kode ?>">
<button type="button" id="cekVoucher" class="btn btn-primary">Cek</button>
</div>
</div>

<hr>

<div class="d-flex justify-content-between mb-2">
<span>Total</span>
<strong>Rp <span id="total">0</span></strong>
</div>

<div class="d-flex justify-content-between mb-2 text-danger" id="voucherRow" style="display:none;">
<span>Voucher</span>
<strong>- Rp <span id="voucherDisplay">0</span></strong>
</div>

<div class="d-flex justify-content-between mb-2">
<span>PPN 11%</span>
<strong>Rp <span id="ppn">0</span></strong>
</div>

<hr>

<div class="d-flex justify-content-between fs-4">
<strong>Grand Total</strong>
<strong class="text-success">
Rp <span id="grandTotal">0</span>
</strong>
</div>

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

<!-- ================= RIGHT : PAYMENT ================= -->
<div class="col-md-6">
<div class="card shadow-sm">
<div class="card-header bg-primary text-white">
<strong>Metode Pembayaran</strong>
</div>

<div class="card-body">

<?= $form->field($model, 'payment_method_id')->dropDownList(
\yii\helpers\ArrayHelper::map(\nota\models\PaymentMethod::find()->all(), 'id', 'name'),
['prompt' => '-- Pilih Metode Pembayaran --']
)->label(false) ?>

<?php
if($model->payment_method_id==1){
  $xs = 'display:block;';
}else{
  $xs = 'display:none;';
}
?>
<div id="tunaiFields" style="<?=$xs?>">

<div class="mb-3">
<label>Uang Diterima</label>
<input type="number" id="uangDiterima" class="form-control form-control" name="uang_diterima" value="<?=$model->uang_diterima?>">
</div>

<div class="mb-3">
<label>Kembalian</label>
<input type="number" id="kembalian" class="form-control form-control bg-light" name="kembalian" value="<?=$model->kembalian?>" readonly>
</div>

</div>

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

</div>

<hr>
<br>
<?= Html::submitButton('Update',['class'=>'btn btn-success']) ?>
<?php ActiveForm::end(); ?>

<script>

$(document).ready(function(){

// =======================
// Fungsi sinkronisasi hidden input
// =======================
function syncHiddenInputs() {
    $('#hidden-items').html('');
    $('#item-table tr').each(function(index){
        let barang = $(this).find('.barang').val();
        let qty    = $(this).find('.qty').val();
        let diskon = $(this).find('.diskon').val();
        let harga  = $(this).find('.harga').val();

        $('#hidden-items').append(`
            <input type="hidden" name="items[${index}][barang_id]" value="${barang}">
            <input type="hidden" name="items[${index}][qty]" value="${qty}">
            <input type="hidden" name="items[${index}][diskon]" value="${diskon}">
            <input type="hidden" name="items[${index}][harga]" value="${harga}">
        `);
    });
}

// =======================
// Sebelum submit form
// =======================
$('form#nota-form').on('beforeSubmit', function(e){
    syncHiddenInputs();
});

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

// =======================
// Load modal produk
// =======================
$('#modal-item').on('show.bs.modal', function(event){
    var button = $(event.relatedTarget);
    var url = button.attr('href');
    $('#modal-item-content').html('<div class="text-center p-3">Loading...</div>');

    $.get(url, function(html){
        $('#modal-item-content').html(html);
        // initSelect2();
    });
});

// =======================
// Tambah produk dari modal ke tabel Nota
// =======================
$(document).on('click', '.btn-add-item', function(){
    let btn = $(this);
    let trModal = btn.closest('tr');
    let id = btn.data('id');
    let nama = btn.data('nama');
    let harga = btn.data('harga');
    let stok = btn.data('stok');
    let qty = parseInt(trModal.find('.modal-qty').val() || 1);

    if(qty < 1) qty = 1;
    if(qty > stok) qty = stok;

    // CEK duplikat
    let exists = false;
    $('#item-table select.barang').each(function(){
        if($(this).val() == id){
            exists = true;
            let oldQty = parseInt($(this).closest('tr').find('.qty').val()||0);
            let newQty = oldQty + qty;
            if(newQty > stok) newQty = stok;
            $(this).closest('tr').find('.qty').val(newQty);
            hitungRow($(this).closest('tr'));
            swal("Barang Sudah Ada", `${nama} sudah ada, qty digabungkan`, "info");
            return false;
        }
    });

    if(exists){
        var modal = bootstrap.Modal.getInstance(document.getElementById('modal-item'));
        modal.hide();
        return;
    }

    // Tambah row baru
    let index = $('#item-table tr').length;
    let row = `<tr>
        <td>
            <select name="items[${index}][barang_id]" class="form-control barang">
                <option value="${id}" selected data-harga="${harga}" data-stok="${stok}">${nama}</option>
            </select>
        </td>
        <td><input type="number" name="items[${index}][qty]" class="form-control qty" value="${qty}" min="1"></td>
        <td><input type="number" name="items[${index}][diskon]" class="form-control diskon" value="0" min="0" max="100"></td>
        <td><input type="number" class="form-control harga" value="${harga}" readonly></td>
        <td><input type="number" class="form-control subtotal" value="${qty*harga}" readonly></td>
        <td><button type="button" class="btn btn-danger btn-sm remove">✖</button></td>
    </tr>`;

    $('#item-table').append(row);
    // initSelect2();
    hitungTotal();

    var modal = bootstrap.Modal.getInstance(document.getElementById('modal-item'));
    modal.hide();
    // hitungTotal();
});

// =======================
// Remove row
// =======================
$('#item-table').on('click', '.remove', function(){
    $(this).closest('tr').remove();
    hitungTotal();
});

// =======================
// Qty/Diskon input
// =======================
$('#item-table').on('input', '.qty, .diskon', function(){
    let tr = $(this).closest('tr');
    let val = $(this).val();

    // Cegah huruf
    if(!/^\d*$/.test(val)){
        $(this).val(val.replace(/\D/g,''));
        return;
    }

    let qty = parseInt(tr.find('.qty').val()||0);
    let diskon = parseFloat(tr.find('.diskon').val()||0);
    let stok = parseInt(tr.find('.barang option:selected').data('stok')||0);

    if(qty > stok){
        tr.find('.qty').val(stok);
        swal("Stok Tidak Cukup", `Stok barang hanya ${stok}`, "warning");
        qty = stok;
    }

    if(isNaN(qty) || qty < 1) tr.find('.qty').val(1);
    if(isNaN(diskon) || diskon < 0) tr.find('.diskon').val(0);
    if(diskon > 100) tr.find('.diskon').val(100);

    hitungRow(tr);
});

// =======================
// Hitung subtotal row
// =======================
function hitungRow(tr){
    let qty = parseFloat(tr.find('.qty').val()||0);
    let harga = parseFloat(tr.find('.harga').val()||0);
    let diskon = parseFloat(tr.find('.diskon').val()||0);
    tr.find('.subtotal').val(qty*harga*(1-diskon/100));
    hitungTotal();
}

// =======================
// Hitung total, PPN, Grand Total
// =======================
// function hitungTotal(){
//     let total = 0;
//     $('.subtotal').each(function(){ total += parseFloat($(this).val()||0); });
//     $('#total').text(total.toLocaleString());
//     let ppn = $('#ppnCheck').is(':checked') ? total*0.11 : 0;
//     $('#ppn').text(ppn.toLocaleString());
//     $('#grandTotal').text((total+ppn).toLocaleString());
// }

function hitungTotal(){

    let total = 0;

    $('#item-table .subtotal').each(function(){
        total += parseFloat($(this).val()) || 0;
    });

    let voucherValue = parseFloat($('#voucherValue').val()) || 0;
    let voucherType  = $('#voucherType').val();

    let discount = 0;

    if(voucherValue > 0){

        if(voucherType === 'percent'){
            discount = total * (voucherValue / 100);
        } else {
            discount = voucherValue;
        }

        if(discount > total) discount = total;

        $('#voucherRow').show();
        $('#voucherDisplay').text(Math.round(discount).toLocaleString());

    } else {

        $('#voucherRow').hide();
        $('#voucherDisplay').text('0');
    }

    let totalAfterVoucher = total - discount;

    let ppn = $('#ppnCheck').is(':checked')
        ? Math.round(totalAfterVoucher * 0.11)
        : 0;

    let grandTotal = totalAfterVoucher + ppn;

    $('#total').text(Math.round(total).toLocaleString());
    $('#ppn').text(ppn.toLocaleString());
    $('#grandTotal').text(grandTotal.toLocaleString());
}

$('#nota-payment_method_id').on('change', function(){
    var metode = $(this).val();
    // Misal: id metode Tunai = 1, sesuaikan dengan DB kamu
    if(metode == '1'){ 
        $('#tunaiFields').show();
    } else {
        $('#tunaiFields').hide();
        $('#uangDiterima').val(0);
        $('#kembalian').val(0);
    }
    hitungKembalian();
});

// Trigger setiap user mengetik uang diterima
$('#uangDiterima').on('input', function(){
    // console.log("Uang diterima:", $(this).val());
    hitungKembalian();
});


// Fungsi hitung kembalian
function hitungKembalian(){

    let grandTotal = parseFloat($('#grandTotal').text().replace(/,/g,'')) || 0;
    let uangDiterima = parseFloat($('#uangDiterima').val().replace(/,/g,'')) || 0;

    let kembalian = uangDiterima - grandTotal;

    if(kembalian < 0) kembalian = 0;

    // 🔥 Bulatkan ke ratusan terdekat
    kembalian = Math.round(kembalian / 100) * 100;

    $('#kembalian').val(kembalian);
}

// =======================
// PPN checkbox
// =======================
$('#ppnCheck').on('change', function(){
    hitungTotal();
    hitungKembalian();
});


// =======================
// Cek Voucher
// =======================
$('#cekVoucher').on('click', function(){
    let kode = $('#voucherCode').val().trim();
    if(!kode){
        swal("Perhatian", "Masukkan kode voucher", "warning");
        return;
    }

    $.get('<?= \yii\helpers\Url::to(['nota/check-voucher']) ?>', {kode: kode}, function(res){
        if(res.status === 'ok'){
            $('#voucherId').val(res.id);
            $('#voucherValue').val(res.value);
            $('#voucherType').val(res.type);

            swal("Voucher Valid", 
                 'Voucher valid: ' + res.type + ' - ' + res.value + (res.type=='percent'?'%':''), 
                 "success");

        } else {
            $('#voucherId').val('');
            $('#voucherValue').val(0);
            $('#voucherType').val('');

            swal("Voucher Tidak Valid", res.message, "error");
        }

        // Hitung ulang total setelah voucher berhasil/invalid
        hitungTotal();
    }, 'json');
});


// =======================
// Recalculate saat halaman load (setelah error)
// =======================
setTimeout(function(){
    hitungTotal();
}, 100);



});


</script>