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

/* @var $model app\models\TemplateNota */

?>

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

<?= Html::activeHiddenInput($model, 'id', ['id'=>'template-nota-id']) ?>

<?= $form->field($model, 'name')->textInput(['id'=>'template-nota-name']) ?>
<?= $form->field($model, 'file')->textInput(['id'=>'template-nota-file']) ?>
<?= $form->field($model, 'is_active')->checkbox(['id'=>'template-nota-active']) ?>

<div class="form-group">
    <button type="button" id="btn-save-template-nota" class="btn btn-primary">Simpan</button>
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
</div>

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

<script>
    var csrfParam = $('meta[name=csrf-param]').attr('content');
var csrfToken = $('meta[name=csrf-token]').attr('content');
// Modal sudah bind via href/data-target
$('#modal-template-nota').on('show.bs.modal', function(event){
    var button = $(event.relatedTarget);
    var url = button.attr('href');
    $('#modal-template-nota-content').html('<div class="text-center p-3">Loading...</div>');
    $.get(url, function(data){
        $('#modal-template-nota-content').html(data);
    });
});

// Simpan Add/Edit
$(document).off('click','#btn-save-template-nota').on('click','#btn-save-template-nota', function(e){
    e.preventDefault();

    var id = $('#template-nota-id').val();
    var postData = {
        id: id,
        name: $('#template-nota-name').val(),
        file: $('#template-nota-file').val(),
        is_active: $('#template-nota-active').is(':checked') ? 1 : 0
    };

    var csrfParam = $('meta[name=csrf-param]').attr('content');
    var csrfToken = $('meta[name=csrf-token]').attr('content');
    postData[csrfParam] = csrfToken;

    var url = id 
        ? '<?= \yii\helpers\Url::to(["setting/edit-template-nota"]) ?>' + '&id=' + id
        : '<?= \yii\helpers\Url::to(["setting/add-template-nota"]) ?>';

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

    $.post(url, postData, function(res){
        swal.close();
        if(res.success){
            $('#modal-template-nota').modal('hide');
            templateNotaTable.ajax.reload(null,false);
            swal("Berhasil!", res.message, "success");
        } else {
            swal("Gagal!", res.message, "error");
        }
    },'json').fail(function(){
        swal.close();
        swal("Error!", "Server error!", "error");
    });
});

</script>