<?php

use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use wbraganca\dynamicform\DynamicFormWidget;

$this->title = 'Nota Kasir Test';
?>

<div class="transaction-create">

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

<?php DynamicFormWidget::begin([
    'widgetContainer' => 'dynamicform_wrapper',
    'widgetBody' => '.container-items',
    'widgetItem' => '.item',
    'limit' => 50,
    'min' => 1,
    'insertButton' => '.add-item',
    'deleteButton' => '.remove-item',
    'model' => $modelsAddress[0],
    'formId' => 'dynamic-form',
    'formFields' => [
        'barang',
        'qty',
        'harga',
        'total',
    ],
]); ?>

<div class="dynamicform_wrapper">

    <table class="table table-bordered">

        <thead>
            <tr>
                <th>Barang</th>
                <th width="120">Qty</th>
                <th width="150">Harga</th>
                <th width="150">Total</th>
                <th width="50"></th>
            </tr>
        </thead>

        <tbody class="container-items">

            <?php foreach ($modelsAddress as $index => $model): ?>
            <tr class="item">

                <td>
                    <?= $form->field($model, "[{$index}]barang")->textInput()->label(false) ?>
                </td>

                <td>
                    <?= $form->field($model, "[{$index}]qty")
                        ->textInput([
                            'class'=>'form-control qty',
                            'onkeyup'=>'calcRow(this)'
                        ])->label(false) ?>
                </td>

                <td>
                   
                </td>

                <td>
                </td>

                <td class="text-center">
                    <button type="button" class="remove-item btn btn-danger btn-xs">
                        X
                    </button>
                </td>

            </tr>
            <?php endforeach; ?>

        </tbody>

    </table>

    <button type="button" class="add-item btn btn-success">
        + Tambah Barang
    </button>

</div>

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

<br>

<div class="form-group text-right">
    <?= Html::submitButton('Simpan', ['class'=>'btn btn-primary']) ?>
</div>

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

</div>

<script>
function calcRow(el){

    let row = $(el).closest('tr');

    let qty   = parseFloat(row.find('.qty').val()) || 0;
    let harga = parseFloat(row.find('.harga').val()) || 0;

    row.find('.total').val(qty * harga);
}
</script>
