(function ($) {
    "use strict";

    $("#sidebarToggle, #sidebarToggleTop").on("click", function (e) {
        $("body").toggleClass("sidebar-toggled");
        $(".sidebar").toggleClass("toggled");
        if ($(".sidebar").hasClass("toggled")) {
            $(".sidebar .collapse").collapse("hide");
        }
    });

    $(window).resize(function () {
        if ($(window).width() < 768) {
            $(".sidebar .collapse").collapse("hide");
        }
        if ($(window).width() < 480 && !$(".sidebar").hasClass("toggled")) {
            $("body").addClass("sidebar-toggled");
            $(".sidebar").addClass("toggled");
            $(".sidebar .collapse").collapse("hide");
        }
    });

    $(document).on("scroll", function () {
        if ($(this).scrollTop() > 100) {
            $(".scroll-to-top").fadeIn();
        } else {
            $(".scroll-to-top").fadeOut();
        }
    });

    $(document).on("click", "a.scroll-to-top", function (e) {
        var $anchor = $(this);
        $("html, body").stop().animate({
            scrollTop: $($anchor.attr("href")).offset().top,
        }, 1000, "easeInOutExpo");
        e.preventDefault();
    });

})(jQuery);

function openPasswordModal() {
    $("#passwordModal").modal("show");
}

function toggleAdminPassword() {
    const input = document.getElementById("admin_password");
    input.type = (input.type === "password") ? "text" : "password";
}

function confirmLogout() {
    Swal.fire({
        title: "Anda yakin ingin keluar?",
        text: "Anda perlu login kembali.",
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#d33",
        confirmButtonText: "Logout",
        cancelButtonText: "Batal",
    }).then((result) => {
        if (result.isConfirmed) {
            document.getElementById("logoutForm").submit();
        }
    });
}

document.addEventListener("DOMContentLoaded", function () {
    const successEl = document.getElementById('swal-success');
    const errorEl = document.getElementById('swal-error');

    if (successEl && successEl.dataset.message) {
        Swal.fire({
            icon: 'success',
            title: 'Berhasil!',
            text: successEl.dataset.message,
            showConfirmButton: false,
            timer: 1500
        });
    }

    if (errorEl && errorEl.dataset.message) {
        Swal.fire({
            icon: 'error',
            title: 'Gagal!',
            text: errorEl.dataset.message
        });
    }

    // artikel
    const formTambahArtikel = document.getElementById('form-tambah-artikel');
    if (formTambahArtikel) {
        formTambahArtikel.addEventListener('submit', function (e) {
            e.preventDefault();
            Swal.fire({
                title: 'Simpan Artikel?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#4e73df',
                confirmButtonText: 'Ya, Simpan'
            }).then((result) => {
                if (result.isConfirmed) {
                    Swal.fire({ title: 'Memproses...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });
                    formTambahArtikel.submit();
                }
            });
        });
    }

    document.querySelectorAll('.form-edit-artikel').forEach(form => {
        form.addEventListener('submit', function (e) {
            e.preventDefault();
            Swal.fire({
                title: 'Update Artikel?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#1cc88a',
                confirmButtonText: 'Ya, Update'
            }).then((result) => {
                if (result.isConfirmed) {
                    Swal.fire({ title: 'Memproses...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });
                    form.submit();
                }
            });
        });
    });

    document.querySelectorAll('.delete-artikel-form').forEach(form => {
        form.addEventListener('submit', function (e) {
            e.preventDefault();
            Swal.fire({
                title: 'Yakin hapus artikel?',
                text: "Data tidak bisa dikembalikan!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#e74a3b',
                confirmButtonText: 'Ya, Hapus'
            }).then((result) => {
                if (result.isConfirmed) {
                    Swal.fire({ title: 'Menghapus...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });
                    form.submit();
                }
            });
        });
    });

    // faq
    const faqCreateForm = document.getElementById("form-faq-create");
    if (faqCreateForm) {
        faqCreateForm.addEventListener("submit", function (e) {
            e.preventDefault();
            Swal.fire({
                title: "Simpan FAQ?",
                icon: "question",
                showCancelButton: true,
                confirmButtonText: "Simpan"
            }).then((result) => {
                if (result.isConfirmed) { faqCreateForm.submit(); }
            });
        });
    }

    const faqEditForm = document.getElementById("form-faq-edit");
    if (faqEditForm) {
        faqEditForm.addEventListener("submit", function (e) {
            e.preventDefault();
            Swal.fire({
                title: "Update FAQ?",
                icon: "question",
                showCancelButton: true,
                confirmButtonText: "Update"
            }).then((result) => {
                if (result.isConfirmed) { faqEditForm.submit(); }
            });
        });
    }

    document.querySelectorAll(".delete-faq-form").forEach(form => {
        form.addEventListener("submit", function (e) {
            e.preventDefault();
            Swal.fire({
                title: "Yakin hapus FAQ?",
                icon: "warning",
                showCancelButton: true,
                confirmButtonColor: "#d33",
                confirmButtonText: "Ya, hapus!"
            }).then((result) => {
                if (result.isConfirmed) { form.submit(); }
            });
        });
    });

    $(document).ready(function() {
    const successMsg = document.getElementById('swal-success');
    if (successMsg) {
        Swal.fire({
            title: "Berhasil!",
            text: successMsg.getAttribute('data-message'),
            icon: "success",
            showConfirmButton: false,
            timer: 1500,
            timerProgressBar: true
        });
    }
});
    //password admin
    const passwordForm = document.getElementById("adminPasswordForm");

    if (passwordForm) {
        const password = document.getElementById("admin_password");
        const confirm = document.getElementById("admin_password_confirmation");

        function updateRule(element, isValid) {
            if (isValid) {
                element.classList.replace("text-danger", "text-success");
                element.innerHTML = element.innerHTML.replace("✖", "✔");
            } else {
                element.classList.replace("text-success", "text-danger");
                element.innerHTML = element.innerHTML.replace("✔", "✖");
            }
        }

        password.addEventListener("input", () => {
            const val = password.value;
            updateRule(document.getElementById("admin-length"), val.length >= 8);
            updateRule(document.getElementById("admin-uppercase"), /[A-Z]/.test(val));
            updateRule(document.getElementById("admin-number"), /[0-9]/.test(val));
            updateRule(document.getElementById("admin-symbol"), /[^A-Za-z0-9]/.test(val));
        });

        confirm.addEventListener("input", () => {
            const matchText = document.getElementById("admin-match");
            if (password.value === confirm.value && confirm.value !== "") {
                matchText.innerHTML = "✔ Password cocok";
                matchText.className = "small text-success";
            } else {
                matchText.innerHTML = "✖ Password tidak sama";
                matchText.className = "small text-danger";
            }
        });

        passwordForm.addEventListener("submit", function (e) {
            e.preventDefault();

            const val = password.value;
            const isAllValid = val.length >= 8 &&
                /[A-Z]/.test(val) &&
                /[0-9]/.test(val) &&
                /[^A-Za-z0-9]/.test(val) &&
                val === confirm.value;

            if (!isAllValid) {
                Swal.fire({
                    title: "Gagal!",
                    text: "Pastikan semua kriteria password terpenuhi dan konfirmasi cocok.",
                    icon: "error",
                    confirmButtonColor: "#e74a3b"
                });
                return;
            }

            Swal.fire({
                title: "Ubah Password?",
                text: "Anda akan menggunakan password baru untuk login berikutnya.",
                icon: "warning",
                showCancelButton: true,
                confirmButtonColor: "#f6c23e",
                cancelButtonColor: "#858796",
                confirmButtonText: "Ya, Ubah!",
                cancelButtonText: "Batal",
                reverseButtons: true
            }).then((result) => {
                if (result.isConfirmed) {
                    Swal.fire({
                        title: "Memproses...",
                        text: "Sedang mengamankan akun Anda",
                        allowOutsideClick: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });
                    this.submit();
                }
            });
        });
    }
    

    //bantuan
    $(document).on('click', '.btn-delete', function (e) {
        e.preventDefault();
        let form = $(this).closest('form');
        Swal.fire({
            title: 'Hapus Tiket?',
            text: "Data bantuan ini akan dihapus permanen!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#e74a3b',
            cancelButtonColor: '#858796',
            confirmButtonText: 'Ya, Hapus!',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {
                form.submit();
            }
        });
    });

    const replyForms = document.querySelectorAll('.form-reply-bantuan');
    replyForms.forEach(form => {
        form.addEventListener('submit', function (e) {
            e.preventDefault();
            Swal.fire({
                title: 'Kirim Balasan?',
                text: "User akan menerima jawaban Anda segera.",
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#7EBC12',
                cancelButtonColor: '#858796',
                confirmButtonText: 'Ya, Balas!',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    Swal.fire({
                        title: 'Mengirim...',
                        allowOutsideClick: false,
                        didOpen: () => Swal.showLoading()
                    });
                    form.submit();
                }
            });
        });
    });

    $(document).on('click', '.btn-delete-bantuan', function (e) {
        e.preventDefault();
        let form = $(this).closest('form');
        Swal.fire({
            title: 'Hapus Tiket?',
            text: "Data keluhan user akan dihapus permanen dari sistem.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#e74a3b',
            cancelButtonColor: '#858796',
            confirmButtonText: 'Ya, Hapus!',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {
                form.submit();
            }
        });
    });
});


function updateRule(el, valid) {
    if (!el) return;
    if (valid) {
        el.classList.replace("text-danger", "text-success");
        el.innerHTML = el.innerHTML.replace("✖", "✔");
    } else {
        el.classList.replace("text-success", "text-danger");
        el.innerHTML = el.innerHTML.replace("✔", "✖");
    }
}

function refreshPage(btn) {
    const icon = btn.querySelector('i');
    icon.classList.add('fa-spin');

    setTimeout(() => {
        location.reload();
    }, 500);
}


//data user
$(document).on('click', '.btn-delete-user', function (e) {
    e.preventDefault();
    let form = $(this).closest('form');
    Swal.fire({
        title: 'Hapus User?',
        text: "Semua data transaksi dan prediksi user ini akan ikut terhapus!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#e74a3b',
        cancelButtonColor: '#858796',
        confirmButtonText: 'Ya, Hapus!',
        cancelButtonText: 'Batal'
    }).then((result) => {
        if (result.isConfirmed) {
            form.submit();
        }
    });
});



$(document).ready(function () {
    if ($('#dataTable-AdminUser').length > 0) {
        $('#dataTable-AdminUser').DataTable({
            "pageLength": 10,
            "language": {
                "search": "Cari User:",
                "lengthMenu": "Tampilkan _MENU_ user"
            }
        });
    }


    if ($('#tableDetailAdmin').length > 0) {
        $('#tableDetailAdmin').DataTable({
            "pageLength": 10,
            "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "Semua"]],
            "language": {
                "search": "Cari data:",
                "lengthMenu": "Tampilkan _MENU_ baris",
            },
            "order": [],
            "columnDefs": [
                { "orderable": false, "targets": 0 }
            ]
        });
    }


});

