//'use strict';
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);
}


$("body").on("click", ".datepicker", function () {
    $(this).datepicker({
        format: 'dd-mm-yyyy',
        autoclose: true
    });
    $(this).datepicker("show");
});

/** Module */
loadData();
function loadData() {
    var table;
    var nisn = $('.nisn').val();
    var master_spp = $('.master_spp').val();
    console.log(nisn);
    console.log(master_spp);
    $(document).ready(function () {
        table = $('.datatable').DataTable({
            "scrollX": false,
            "processing": true,
            "serverSide": false,
            "bAutoWidth": true,
            "bSort": false,
            "bStateSave": true,
            "bDestroy": true,
            "paging": true,
            "ssSorting": [[0, 'desc']],
            "iDisplayLength": 25,
            // "order": [[1, 'desc']],

            "aLengthMenu": [
                [25, 30, 50, -1],
                [25, 30, 50, "All"]
            ],
            language: {
                paginate: {
                    previous: "<i class='fas fa-angle-left'>",
                    next: "<i class='fas fa-angle-right'>"
                }
            },
            "ajax": {
                "url": "./sw-mod/pembayaran/sw-datatable.php",
                "type": "POST",
                "data": {
                    nisn: nisn,
                    master_spp: master_spp,
                },
            },

            "footerCallback": function (row, data, start, end, display) {
                var api = this.api();
                var json = api.ajax.json();

                if (json) {
                    $('.status_pembayaran').html(json.status_pembayaran ?? 0);
                    $('.total_pembayaran').html(json.total_pembayaran ?? 0);
                    $('.total_tagihan').html(json.total_tagihan ?? 0);
                    $('.sisa_tagihan').html(json.sisa_tagihan ?? 0);
                }
            },

            fixedColumns: {
                leftColumns:2,
            },

            "columnDefs": [{
                "targets": [0],
                "orderable": false,
            },],

        });
    });
}

function stripHtml(html) {
    let doc = new DOMParser().parseFromString(html, 'text/html');
    return doc.body.textContent || "";
}

$(".jenis_pembayaran").change(function () {
    loadData();
});


$(document).ready(function () {

    var app = {
        check: function (e) {

            // cek tombol ENTER
            if (e.key === "Enter" || e.keyCode === 13) {
                e.preventDefault(); // cegah submit form jika ada

                var nisnVal = $(".nisn").val();

                $.ajax({
                    url: "./sw-mod/pembayaran/sw-proses.php?action=cek-nisn",
                    method: "POST",
                    data: { nisnVal: nisnVal },
                    dataType: "json",
                    success: function (response) {
                        if (response.status === "success") {
                            setTimeout(function () {
                                loadData();
                            }, 500);
                            $(".nama_siswa").val('' + response.data.nama_lengkap + ' ');
                            $(".user_id").val(response.data.user_id);
                            $(".kelas").val(response.data.kelas);


                            $(".result-output")
                                .html('<span class="text-primary">Siswa ditemukan</span>')
                                .fadeIn("slow");
                        } else {
                            $(".siswa, .kelas").val('');
                            $(".result-output")
                                .html('<span class="text-danger">' + response.message + '</span>')
                                .fadeIn("slow");
                        }
                    },
                    error: function () {
                        $(".siswa, .kelas").val('');
                        $(".result-output")
                            .html('<span class="text-danger">Terjadi kesalahan server</span>')
                            .fadeIn("slow");
                    }
                });
            }
        }
    };

    // event keydown / keypress juga bisa
    $(".nisn").on("keydown", app.check);
});



$('.form-add').submit(function (e) {
    e.preventDefault();
    loading();
    var id = $('.id').val();
    var action = (id === '' || id === null) ? 'add' : 'update';
    $.ajax({
        url: './sw-mod/pembayaran/sw-proses.php?action=' + action,
        type: "POST",
        data: new FormData(this),
        processData: false,
        contentType: false,
        cache: false,
        async: false,
        beforeSend: function () {
            loading();
        },
        success: function (data) {
            if (data == 'success') {
                swal({ title: 'Berhasil!', text: 'Data pembayaran berhasil disimpan!', icon: 'success', timer: 2500, });
                $(".jumlah_pembayaran").val('');
                $('.id').val('');
                loadData();
            } else {
                swal({ title: 'Oops!', text: data, icon: 'error', timer: 2500, });
            }
        },
    });
});

/**  Update */
$(document).on('click', '.btn-update', function () {
    var id = $(this).data("id");
    $.ajax({
        type: 'POST',
        url: './sw-mod/pembayaran/sw-proses.php?action=get-data-update',
        data: { id: id },
        dataType: 'json',
        success: function (response) {
            if (response.status === 'success') {
                let data = response.data;
                $('.id').val(data.pembayaran_id);
                $('.user_id').val(data.user_id);
                $('.nisn').val(data.nisn);
                $('.nama_siswa').val(data.nama_siswa);
                $('.jumlah_pembayaran').val(data.nominal);
                $('.metode_pembayaran').val(data.metode_pembayaran).trigger('change');
            } else {
                alert(response.message);
            }
        },
        error: function (xhr) {
            console.log(xhr.responseText);
        }
    });
});


$(document).on('click', 'button[type="reset"]', function () {
    $('.id').val('');
});



/** Hapus data*/
$(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/pembayaran/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();
                        } else {
                            swal({ title: 'Gagal!', text: data, icon: 'error', timer: 2500, });

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


$(document).on('click', '.btn-stts', function () {
    var id = $(this).attr("data-id");
    var status = $(this).attr("data-status");
    $.ajax({
        type: "POST",
        url: "./sw-mod/pembayaran/sw-proses.php?action=status",
        data: { id: id, status: status },
        success: function (data) {
            if (data == 'success') {
                loadData();
                if (status == 'pending') {
                    $(".badge" + id).attr("class", "badge" + id + " badge badge-warning");
                    $(".badge" + id).html("Pending");

                } else if (status == 'berhasil') {
                    $(".badge" + id).attr("class", "badge" + id + " badge badge-success");
                    $(".badge" + id).html("Berhasil");

                } else if (status == 'cancel') {
                    $(".badge" + id).attr("class", "badge" + id + " badge badge-danger");
                    $(".badge" + id).html("Cancel");

                } else {
                    $(".badge" + id).attr("class", "badge" + id + " badge badge-danger");
                    $(".badge" + id).html("Batal");
                }
            } else {
                console.log(data);
            }
        }
    });
});




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 : '');
}


/** Print */
$(document).on('click', '.btn-print', function () {
    var id = $(this).attr("data-id");
    var url = "./sw-mod/pembayaran/sw-print.php?action=print-struk&id=" + id + "";
    window.open(url, '_blank');
});

$(document).on('click', '.btn-download', function () {
    var tipe = $(this).attr("data");
    var nisn = $('.nisn').val();
    var id = $('.master_spp').val();
    var url = "./sw-mod/pembayaran/sw-print.php?action=" + tipe + "&nisn=" + nisn + "&id=" + id+ "";
    window.open(url, '_blank');
});
