
function loading() {
    $('.btn-save').prop("disabled", true);
    // add spinner to button
    $('.btn-save').html(
        '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Loading...'
    );
    window.setTimeout(function () {
        $('.btn-save').prop("disabled", false);
        $('.btn-save').html('<i class="far fa-save"></i> Simpan'
        );
    }, 2000);
}

$('.timepicker').timepicker({
    showInputs: false,
    showMeridian: false,
    use24hours: true,
    format: 'HH:mm'
})

loadData();
function loadData() {
    var table;
    var modifikasi = $('.modifikasi').html();
    var hapus = $('.hapus').html();
    $(document).ready(function () {
        //datatables
        table = $('.datatable').DataTable({
            "scrollY": false,
            "scrollX": false,
            "processing": true,
            "serverSide": false,
            "bAutoWidth": true,
            "bSort": true,
            "bStateSave": true,
            "bDestroy": true,
            "paging": true,
            "ssSorting": [[0, 'desc']],
            "iDisplayLength": 15,
            // "order": [[1, 'desc']],

            "aLengthMenu": [
                [15, 30, 50, -1],
                [15, 30, 50, "All"]
            ],
            language: {
                paginate: {
                    previous: "<i class='fas fa-angle-left'>",
                    next: "<i class='fas fa-angle-right'>"
                }
            },
            "ajax": {
                "url": "./sw-mod/master-spp/sw-datatable.php",
                "type": "POST",
                "data": {
                    modifikasi: modifikasi,
                    hapus: hapus,
                },
            },
            "columnDefs": [{
                "targets": [0],
                "orderable": false,
            },],
        });
    });
}

$(document).on('click', '.btn-reset', function () {
    $(".form-add").trigger("reset");
    $('.id').val('');
});

$(".form-add").validate({
    // Specify validation rules
    rules: {
        field: {
            required: true
        },
    },

    // Specify validation error messages
    messages: {
        field: {
            required: "Silahkan masukkan data sesuai inputan",
        },
    },
    // in the "action" attribute of the form when valid
    submitHandler: submitForm_Add
});

/* handle form submit */
function submitForm_Add() {
    var data = $(".form-add").serialize();
    $.ajax({
        type: 'POST',
        url: './sw-mod/master-spp/sw-proses.php?action=add',
        data: data,
        cache: false,
        async: false,
        beforeSend: function () {
            loading();
        },
        success: function (data) {
            if (data == 'success') {
                swal({ title: 'Berhasil!', text: 'Data berhasil disimpan!', icon: 'success', timer: 2500, });
                $(".form-add").trigger("reset");
                $('.id').val('');
                loadData();
            } else {
                swal({ title: 'Oops!', text: data, icon: 'error', timer: 2500, });
            }
        }
    });
    return false;
}

$(document).on('click', '.btn-update', function () {
    var id = $(this).attr('data-id');
    $.ajax({
        type: 'POST',
        url: './sw-mod/master-spp/sw-proses.php?action=get-data-update',
        data: { id: id },
        dataType: 'json',
        success: function (response) {
            $('.id').val(response.id);
            $('.jenis_pembayaran').val(response.jenis_pembayaran);
            $('.tahun_ajaran').val(response.tahun_ajaran);
            $('.kelas').val(response.kelas);
            $('.nominal').val(response.nominal);
        },
        error: function (response) {
            console.log(response.responseText);
        }
    });
});


$(document).on('click', '.btn-delete', function () {
    var id = $(this).attr("data-id");
    swal({
        text: "Anda yakin ingin menghapus data ini?",
        icon: "warning",
        buttons: {
            cancel: true,
            confirm: true,
        },
        value: "yes",
    })

        .then((value) => {
            if (value) {
                loading();
                $.ajax({
                    url: './sw-mod/master-spp/sw-proses.php?action=delete',
                    type: 'POST',
                    data: { id: id },
                    success: function (data) {
                        if (data == 'success') {
                            swal({ title: 'Berhasil!', text: 'Data berhasil dihapus!', icon: 'success', timer: 2500, });
                            loadData();
                            $('.id').val('');
                        } else {
                            swal({ title: 'Gagal!', text: data, icon: 'error', timer: 2500, });

                        }
                    }
                });
            } else {
                return false;
            }
        });
});



document.addEventListener('DOMContentLoaded', function () {
    var inputElements = document.querySelectorAll('.rupiah');

    inputElements.forEach(function (input) {
        input.addEventListener('keyup', function (e) {
            this.value = formatRupiah(this.value);
        });
    });
});

function formatRupiah(angka, prefix) {
    var number_string = angka.replace(/[^,\d]/g, '').toString(),
        split = number_string.split(','),
        sisa = split[0].length % 3,
        rupiah = split[0].substr(0, sisa),
        ribuan = split[0].substr(sisa).match(/\d{3}/gi);

    if (ribuan) {
        var separator = sisa ? '.' : '';
        rupiah += separator + ribuan.join('.');
    }

    rupiah = split[1] !== undefined ? rupiah + ',' + split[1] : rupiah;
    return prefix === undefined ? rupiah : (rupiah ? 'Rp. ' + rupiah : '');
}
