$(function () {
    $(".overlay").hide();
    $(".pilih").click(function () {
        $(".overlay").show();
        var id = $(this).attr("data-id");
        $("#hadiah" + id).prop("checked", true);
        pilih_hadiah(id);
    });
    $(".pilih_hadiah").click(function () {
        $(".overlay").show();
        var id = $(this).val();
        $(this).prop("checked", true);
        pilih_hadiah(id);
    });

    function pilih_hadiah(id) {
        var token = $("meta[name='csrf-token']").attr("content");
        $.ajax({
            type: "POST",
            url: "pilih-hadiah",
            dataType: "JSON",
            data: {
                id: id,
                _token: token,
            },
            success: function (data) {
                if (data.hasil == "ada") {
                    $(".overlay").hide();
                    toastr.success("Item berhasil di pilih.");
                    $("#nama").val(data.nama);
                    $("#stok").val(data.stok);
                    $("#poin").val(data.poin);
                    $("#kode").val(data.kode);
                } else if (data.hasil == "kosong") {
                    $(".overlay").hide();
                    Swal.fire({
                        icon: "error",
                        title: "Oops..",
                        text: "Stok item telah habis!",
                    }).then((result) => {
                        if (result.isConfirmed) {
                            document.location.href = "";
                        }
                    });
                }
            },
        });
    }

    $("#member").on({
        keypress: function () {
            typed_into = true;
        },
        change: function () {
            var kode = $("#member").val();
            var token = $("meta[name='csrf-token']").attr("content");
            if (kode == null) {
                $("#member").focus();
                $("#member").val("");
            } else {
                $.ajax({
                    type: "POST",
                    url: "cari-member-item",
                    dataType: "JSON",
                    data: {
                        kode: kode,
                        _token: token,
                    },
                    success: function (data) {
                        if (data.hasil == "ada") {
                            $("#member").val(data.nama);
                            $("#member").focus();
                            $(".member").remove();

                            $("#id_member").val(data.id);
                            $("#kode_member").val(data.kode);
                            $("#poin_member").val(data.poin);
                            $("#alamat").val(data.alamat);
                        } else if (data.hasil == "kosong") {
                            nama_member(kode);
                        }
                    },
                });
            }
        },
    });

    function nama_member(nama) {
        var token = $("meta[name='csrf-token']").attr("content");
        if (nama == null) {
            $("#member").focus();
            $("#member").val("");
        } else {
            $.ajax({
                type: "post",
                url: "cari-member",
                data: {
                    nama: nama,
                    _token: token,
                },
                success: function (data) {
                    if (data == "kosong") {
                        toastr.error("Member tidak terdaftar .");
                        $(".member").remove();
                        $("#member").focus();
                    } else {
                        $(".member").remove();
                        $(".show_member").append(
                            '<div class="member"><ul class="list-group">' +
                                data +
                                "</ul></div>"
                        );
                    }
                },
            });
        }
    }

    $(".show_member").on("click", ".pilih", function () {
        var token = $("meta[name='csrf-token']").attr("content");
        var kode = $(this).attr("data-kd");
        $.ajax({
            type: "POST",
            url: "cari-member-item",
            dataType: "JSON",
            data: {
                kode: kode,
                _token: token,
            },
            success: function (data) {
                $("#member").val(data.nama);
                $("#member").focus();
                $(".member").remove();

                $("#id_member").val(data.id);
                $("#kode_member").val(data.kode);
                $("#poin_member").val(data.poin);
                $("#alamat").val(data.alamat);
            },
        });
    });

    $(".simpan").click(function () {
        var token = $("meta[name='csrf-token']").attr("content");
        var id = $("#id_member").val();
        var nm = $("#member").val();
        var kode = $("#kode").val();
        var poin = $("#poin").val();
        var stok = $("#stok").val();
        var poin_member = $("#poin_member").val();

        if (id == 0) {
            toastr.warning("Silahkan pilih member .");
        } else if (kode == 0) {
            toastr.warning("Silahkan pilih Item Hadiah .");
        } else if (stok == 0) {
            Swal.fire({
                icon: "error",
                title: "Opss..",
                text: "Maaf, Stok Item telah habis, silahkan cari item lain!",
            });
        } else if (parseInt(poin_member) < parseInt(poin)) {
            Swal.fire({
                icon: "error",
                title: "Opss..",
                text: "Maaf, poin anda tidak mencukupi, silahkan cari item lain!",
            });
        } else {
            Swal.fire({
                title: "Pastikan dengan benar",
                text:
                    "Member atas nama ( " +
                    nm +
                    " ) , Akan menukarkan poin belanja",
                icon: "warning",
                showCancelButton: true,
                confirmButtonColor: "#3085d6",
                cancelButtonColor: "#d33",
                confirmButtonText: "Ya, Tukarkan poin!",
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        type: "POST",
                        url: "simpan-penukaran",
                        data: {
                            id: id,
                            kode: kode,
                            poin: poin,
                            _token: token,
                        },
                        success: function (data) {
                            cetak(data);
                        },
                    });
                }
            });
        }
    });

    $("#view").on("click", ".cetak", function () {
        var id = $(this).attr("data-id");
        $(this).html('<i class="fas fa-spinner fa-spin"></i> ');
        $(this).attr("disabled", true);
        cetak(id);
    });

    function cetak(id) {
        var token = $("meta[name='csrf-token']").attr("content");
        var cekprint = $("#ckprint").val();

        if (cekprint == "N") {
            $.ajax({
                type: "POST",
                url: "cetak-penukaran",
                data: {
                    id: id,
                    _token: token,
                },
                success: function (data) {
                    $(".tampil_data").html(data);
                    $("#hidedata").hide();

                    let timerInterval;
                    Swal.fire({
                        title: "Mohon tunggu sebentar!",
                        html: "Proses mempersiapkan data <b></b> milliseconds.",
                        timer: 2000,
                        timerProgressBar: true,
                        didOpen: () => {
                            Swal.showLoading();
                            const timer = Swal.getPopup().querySelector("b");
                            timerInterval = setInterval(() => {
                                timer.textContent = `${Swal.getTimerLeft()}`;
                            }, 100);
                        },
                        willClose: () => {
                            clearInterval(timerInterval);
                        },
                    }).then((result) => {
                        /* Read more about handling dismissals below */
                        if (result.dismiss === Swal.DismissReason.timer) {
                            // $('#hidedata').hide();
                            $("#hidedata").hide();
                            printPageArea("print");
                            document.location.href = "";
                        }
                    });
                },
            });
        } else {
            var id = id;
            $.ajax({
                type: "POST",
                url: "cetak-penukaran",
                data: {
                    id: id,
                    _token: token,
                },
                success: function (data) {
                    Swal.fire({
                        icon: "success",
                        title: "Berhasil  ",
                        text: "Penukaran poin ke item berhasil disimpan",
                    }).then((result) => {
                        if (result.isConfirmed) {
                            document.location.href = "";
                        }
                    });
                },
            });
        }
    }

    function printPageArea(areaID) {
        var printContent = document.getElementById(areaID).innerHTML;
        var originalContent = document.body.innerHTML;
        document.body.innerHTML = printContent;
        window.print();
        document.body.innerHTML = originalContent;
    }

    // ceklis
    $("#cekall").change(function () {
        if ($(this).prop("checked")) {
            $(".ceklis").prop("checked", true);
        } else {
            $(".ceklis").prop("checked", false);
        }
    });

    $("#pilih_hapus").click(function () {
        var allVals = [];
        $(".ceklis:checked").each(function () {
            allVals.push($(this).val());
        });
        var token = $("meta[name='csrf-token']").attr("content");

        if (allVals.length <= 0) {
            Toast.fire({
                icon: "error",
                title: "Ceklis data yang akan dihapus!!!.",
            });
        } else {
            Swal.fire({
                title: "Pastikan dengan benar!",
                text: "Data yang anda pilih akan dihapus!",
                icon: "warning",
                showCancelButton: true,
                confirmButtonColor: "#3085d6",
                cancelButtonColor: "#d33",
                confirmButtonText: "Ya, Hapus!",
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        type: "DELETE",
                        url: "deleteall-penukaran",
                        data: {
                            allVals: allVals,
                            _token: token,
                        },
                        beforeSend: function () {
                            $("#pilih_hapus").html(
                                '<i class="fas fa-spinner fa-spin"></i> Tunggu..'
                            );
                            $("#pilih_hapus").attr("disabled", true);
                        },
                        success: function (data) {
                            // alert(data)
                            $("#pilih_hapus").html(
                                '<i class="fa fa-trash"></i> Hapus'
                            );
                            $("#pilih_hapus").attr("disabled", true);
                            Swal.fire({
                                icon: "success",
                                title: "Berhasil",
                                text: "Data berhasil dihapus!",
                            }).then((result) => {
                                if (result.isConfirmed) {
                                    document.location.href = "";
                                }
                            });
                        },
                    });
                }
            });
        }
    });
});
