<!--begin::Global Javascript Bundle(mandatory for all pages)-->
<script src="assets/plugins/global/plugins.bundle.js"></script>
<script src="assets/js/scripts.bundle.js"></script>

<!-- Datatable -->
<!--<script src="assets/vendor/datatable/datatables.min.js"></script> -->

<!-- SweetAlert2 JS -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<!--end::Global Javascript Bundle-->


<!-- Select2 CDN -->
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<!-- Viewer -->
<link href="../assets/viewerjs/dist/viewer.css" rel="stylesheet">
<script src="../assets/viewerjs/dist/viewer.js"></script>

<script>

    const isDebug = true;

    if (!isDebug) {
        console.log = function () { };
        console.warn = function () { };
        console.error = function () { };
    }


    //Global Function
    var timeoutFetching = 30000;
    var timeoutSaving = 30000;
    var arrAksesList = [];
    var globalUsername = "";
    var globalKodeAnggota = "";

    const headc_txtNama = document.getElementById("headc_txtNama");
    const headc_txtEmail = document.getElementById("headc_txtEmail");
    const headc_txtNoTelp = document.getElementById("headc_txtNoTelp");

    function swalErrorPopUp(onConfirmCallback = () => { }, tipe = "", msgP = "") {

        var title = "Error";
        var msg = "Terjadi kesalahan saat mengirim data.";

        if (tipe == "timeout") {
            title = "Time Out";
            msg = "Proses mengirim data melebihi batas waktu.";
        }

        if (msgP != "") {
            msg = msgP;
        }

        Swal.fire({
            icon: 'error',
            title: title,
            text: msg,
            showCancelButton: true,
            confirmButtonText: 'Coba lagi',
            cancelButtonText: 'Batalkan',
            allowOutsideClick: false,
            willOpen: () => {
                setCSSLink()
            }

        }).then((result) => {
            if (result.isConfirmed) {
                onConfirmCallback(); // Callback function provided by user to handle confirmation action
            }
        });
    }
    function swalPopUp(tipe = "", msgP = "", target = null) {

        var title = "Error";
        var msg = "Terjadi kesalahan saat mengirim data.";

        if (tipe == "timeout") {
            title = "Time Out";
            msg = "Proses mengirim data melebihi batas waktu.";
        }

        if (msgP != "") {
            msg = msgP;
        }

        Swal.fire({
            icon: 'error',
            title: title,
            text: msg,
            showCancelButton: false,
            confirmButtonText: 'OK',
            allowOutsideClick: false,
            target: target,
            willOpen: () => {
                setCSSLink()
            }
        }).then((result) => {
            if (result.isConfirmed) {
            }
        });
    }
    function showLoadingDialog(didOpenCallback, timeoutCallback, cancelCallback, _cancelButton = true, _inputTimeout = false) {

        var timeoutSet = timeoutFetching;

        if (_inputTimeout) {
            timeoutSet = timeoutSaving;
        }

        var loadingDialog = Swal.fire({
            title: 'Fetching Data...',
            html: "Otomatis batal dalam <b></b> detik.",
            timer: timeoutSet,
            timerProgressBar: true,
            allowOutsideClick: false,
            showCancelButton: _cancelButton,
            cancelButtonText: 'Batalkan',
            showConfirmButton: false,
            willOpen: () => {
                setCSSLink()
            },
            didOpen: () => {
                Swal.showLoading();
                const timer = Swal.getPopup().querySelector("b");
                timerInterval = setInterval(() => {
                    // Ambil waktu tersisa dalam milidetik
                    var timeLeft = Swal.getTimerLeft();
                    // Ubah waktu dalam detik
                    var secondsLeft = Math.ceil(timeLeft / 1000);
                    // Tampilkan waktu dalam detik
                    timer.textContent = `${secondsLeft}`;
                }, 100);

                // Panggil callback didOpenCallback jika diberikan
                if (didOpenCallback) {
                    didOpenCallback();
                }
            },
            willClose: () => {
                clearInterval(timerInterval);
            }
        }).then((result) => {
            if (result.dismiss === Swal.DismissReason.timer) {
                console.log("I was closed by the timer");

                timeoutCallback();

            } else if (result.dismiss == 'cancel') {
                console.log('cancel');

                cancelCallback();
            }


        });
    } // showLoadingDialog



    window.showUnauthorizedAlert = function showUnauthorizedAlert(_akses) {
        Swal.fire({
            title: "Anda tidak memiliki otoritas",
            html: "Hanya pengguna dengan otoritas  <b><p>" + _akses + "</p></b> yang dapat mengakses halaman ini.",
            icon: "warning",
            allowEscapeKey: false,
            allowOutsideClick: false,
            showCancelButton: false,
            confirmButtonText: "OK",
            willOpen: () => {
                setCSSLink()
            },
            didOpen: function () {
                document.getElementById("content-overlay").classList.add("blur-content");
                document.getElementById("content-overlay").classList.remove("d-none");
                Swal.getPopup().style.zIndex = "10000";
            },
            didClose: function () {
                document.getElementById("content-overlay").classList.remove("blur-content");
                document.getElementById("content-overlay").classList.add("d-none");
                window.location.href = "index.php";
            },
        });
    }



    function CekSesi({ getUID_F = "", getTransaction = 0, getDelivery = 0 } = {}) {
        return new Promise((resolve, reject) => {
            document.getElementById("content-overlay").classList.add("blur-content");
            document.getElementById("content-overlay").classList.remove("d-none");


            // Mengambil nilai input
            var isCanceled = false;



            var xhr = new XMLHttpRequest();
            var url = "proxy/user_proxy.php";

            var didOpenCallback = () => {
                // Kirim data ke server menggunakan AJAX setelah dialog loading ditampilkan
                var formData = new FormData();
                formData.append('action', 'get_data');

                if (getUID_F != "") { formData.append('UID_F', getUID_F); }
                if (getTransaction > 0) { formData.append('getTransaction', '1'); }
                if (getDelivery > 0) { formData.append('getDelivery', '1'); }



                xhr.onreadystatechange = function () {
                    if (!isCanceled) {
                        if (xhr.readyState === XMLHttpRequest.DONE) {
                            if (xhr.status === 200) {
                                // Respon dari server
                                //console.log(xhr.responseText);

                                if (isCanceled) {
                                    console.log("AJAX di cancel");
                                } else {
                                    var rawResponse = xhr.responseText;
                                    console.log("Raw response:", rawResponse);


                                    var response = JSON.parse(xhr.responseText);
                                    console.log(response);

                                    if (response.Status === 1) {
                                        // Status sukses
                                        Swal.close();

                                        document.getElementById("content-overlay").classList.remove("blur-content");
                                        document.getElementById("content-overlay").classList.add("d-none");

                                        localStorage.removeItem('arrAksesList');

                                        if (response && response.data_member && response.data_member.length > 0) {
                                            let user = response.data_member[0];
                                            let CustomerName = user.CustomerName;
                                            let CustomerCode = user.CustomerCode;
                                            let MembershipPoint = Math.floor(user.MembershipPoint).toLocaleString("id-ID");

                                            headc_txtNama.textContent = CustomerName;
                                        }

                                        if (response && response.data_list && response.data_list.length > 0) {
                                            let user = response.data_list[0];
                                            headc_txtEmail.textContent = user.Email;
                                            headc_txtNoTelp.textContent = user.NoTelp;
                                        }

                                        resolve(response); // Mengembalikan response

                                    } else {
                                        // Status gagal / error
                                        Swal.close();

                                        let msg = response.Keterangan || "Terjadi kesalahan yang tidak diketahui.";
                                        /*
                                        Swal.fire({
                                            icon: 'error',
                                            title: 'Invalid User',
                                            text: msg,
                                            confirmButtonText: 'OK',
                                            willOpen: () => {
                                                setCSSLink();
                                            },
                                        }).then((result) => {
                                            if (result.isConfirmed) {
                                                window.location.href = 'index.php';
                                            }
                                        });*/

                                        reject(msg);
                                    }

                                }
                            } else {
                                // Penanganan kesalahan 
                                var msg = "Terjadi kesalahan saat mengirim data.";
                                swalErrorPopUp(() => {
                                    CekSesi();
                                }, "", msg);
                            }
                        }
                    } // Iscanceled
                };

                xhr.open('POST', url, true);
                xhr.send(formData);
            }


            showLoadingDialog(didOpenCallback,
                () => {
                    isCanceled = true;
                    xhr.abort(); // Membatalkan proses AJAX

                    title = "Time Out";
                    msg = "Proses mengirim data melebihi batas waktu.";

                    Swal.fire({
                        icon: 'error',
                        title: title,
                        text: msg,
                        showCancelButton: true,
                        confirmButtonText: 'Coba lagi',
                        cancelButtonText: 'Batalkan',
                        allowOutsideClick: false,
                        willOpen: () => {
                            setCSSLink()
                        }
                    }).then((result) => {
                        if (result.isConfirmed) {
                            CekSesi(); // Callback function provided by user to handle confirmation action
                        } else if (result.dismiss === Swal.DismissReason.cancel) {
                            window.location.href = 'index.php'; // Redirect ke halaman login.php saat tombol "Batalkan" ditekan
                        }
                    });

                    reject("Timeout");
                },
                () => {
                    isCanceled = true;
                    xhr.abort(); // Membatalkan proses AJAX
                    Swal.close();
                    reject("Cancel");
                },
                false);

        });

    }; // CekSesi


    function SesiHabis() {
        var msg = "Sesi sudah habis, silahkan login kembali";

        // Menampilkan pesan swal
        Swal.fire({
            icon: 'error', // Jenis ikon (info, warning, error, success)
            title: 'Invalid Session',
            text: msg, // Keterangan pesan dari variabel msg
            confirmButtonText: 'OK',
            allowOutsideClick: false,
            willOpen: () => {
                setCSSLink()
            },
        }).then((result) => {
            // Redirect ke halaman login.php jika tombol OK diklik
            if (result.isConfirmed) {
                window.location.href = 'index.php';
            }
        });
    } // Sesi 


    function getUrlParameter(sParam) {
        var sPageURL = window.location.search.substring(1),
            sURLVariables = sPageURL.split('&'),
            sParameterName,
            i;

        for (i = 0; i < sURLVariables.length; i++) {
            sParameterName = sURLVariables[i].split('=');

            if (sParameterName[0] === sParam) {
                return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
            }
        }
    };

    function setQueryStringParameter(name, value) {
        const params = new URLSearchParams(window.location.search);
        params.set(name, value);
        window.history.replaceState({}, "", decodeURIComponent(
            `${window.location.pathname}?${params}`));
    }

    function clearAllUrlParameters() {
        // Menggunakan replaceState untuk memperbarui URL tanpa query string
        window.history.replaceState({}, "", window.location.pathname);
    }

    function toggleRemoveButton(show) {
        const imageInputElements = document.querySelectorAll('[data-kt-image-input="true"]');

        imageInputElements.forEach(function (element) {
            try {
                const removeButton = element.querySelector('[data-kt-image-input-action="remove"]');
                if (removeButton) {
                    // Menampilkan tombol remove
                    removeButton.style.display = show ? 'inline-block' : 'none';
                } else {
                    throw new Error("Tombol remove tidak ditemukan pada elemen ini.");
                }
            } catch (error) {
                console.error("Error: ", error.message); // Menangani jika tombol remove tidak ditemukan
            }
        });
    }

    function resetImagePreview() {
        const imageInputElements = document.querySelectorAll('[data-kt-image-input="true"]');

        imageInputElements.forEach(function (element) {
            try {
                // Cari elemen preview gambar
                const imageWrapper = element.querySelector('.image-input-wrapper');
                const inputElement = element.querySelector('input[type="file"]');
                const hiddenInput = element.querySelector('input[type="hidden"]');

                // Set gambar preview ke placeholder
                if (imageWrapper) {
                    KTUtil.css(imageWrapper, "background-image", "url('assets/media/svg/files/blank-image.svg')");
                    element.classList.add("image-input-empty");
                    element.classList.remove("image-input-changed");
                }

                // Reset input file dan hidden field
                if (inputElement) {
                    inputElement.value = ''; // Clear file input
                }
                if (hiddenInput) {
                    hiddenInput.value = '0'; // Set hidden field to indicate no image selected
                }

            } catch (error) {
                console.error("Error: ", error.message);
            }
        });
    }

    function formatDate(dateString) {
        const options = { year: 'numeric', month: 'long', day: 'numeric' };
        const date = new Date(dateString);  // Mengubah string tanggal menjadi objek Date
        return date.toLocaleDateString('en-GB', options);  // Format tanggal dengan locale 'en-GB' (untuk format dd Month yyyy)
    }



    function toggleOverlay(show) {
        const overlay = document.getElementById("content-overlay");
        overlay.classList.toggle("blur-content", show);
        overlay.classList.toggle("d-none", !show);
    }

    function showErrorMessage(title, msg, redirect = false) {
        Swal.fire({
            icon: 'error',
            title,
            text: msg,
            confirmButtonText: 'OK',
            willOpen: setCSSLink,
        }).then((result) => {
            if (redirect && result.isConfirmed) {
                window.location.href = 'index.php';
            }
        });
    }

    function sendRequest(url, formData) {
        return new Promise((resolve, reject) => {
            let isCanceled = false;
            let xhr = new XMLHttpRequest();

            xhr.onreadystatechange = function () {
                if (!isCanceled && xhr.readyState === XMLHttpRequest.DONE) {
                    console.log("Raw Response:", xhr.responseText); // Log semua response mentah

                    if (xhr.status === 200) {
                        try {
                            let response = JSON.parse(xhr.responseText);

                            if (response.Status == 0) {
                                reject(response.Keterangan);
                            } else {
                                toggleOverlay(false);
                                resolve(response);
                            }
                        } catch (err) {
                            console.error("JSON Parse Error:", err);
                            showErrorMessage("Invalid JSON", "Respon dari server tidak valid.");
                            reject("Invalid JSON");
                        }
                    } else {
                        showErrorMessage("Error", "Terjadi kesalahan saat mengirim data.");
                        reject("Request Error");
                    }
                }
            };

            xhr.open('POST', url, true);
            xhr.send(formData);

            showLoadingDialog(() => { },
                () => {
                    isCanceled = true;
                    xhr.abort();
                    showErrorMessage("Time Out", "Proses mengirim data melebihi batas waktu.", true);
                    reject("Timeout");
                },
                () => {
                    isCanceled = true;
                    xhr.abort();
                    Swal.close();
                    reject("Cancel");
                },
                false
            );
        });
    }


    // Fungsi ambil data form sebagai object
    function getFormData(form) {
        const data = {};
        form.querySelectorAll("input, select, textarea").forEach(input => {
            data[input.name] = input.value;
        });
        return data;
    }


</script>