(function ($) {
    "use strict";

    //sidebar dan scroll
    $("#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 () {
        var scrollDistance = $(this).scrollTop();
        if (scrollDistance > 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();
    });

    //riwayat prediksi
    window.confirmDownload = function(url) {
        if (confirm("Apakah Anda yakin ingin mengunduh laporan riwayat prediksi ini dalam format Excel?")) {
            window.location.href = url;
        }
    };

    //master data
    $(document).ready(function() {
        

        if($('#dataTable-Master').length) {
            $('#dataTable-Master').DataTable({
                "pageLength": 10,
                "lengthMenu": [ [10, 50, 100, -1], [10, 50, 100, "Semua"] ],
                "language": {
                    "search": "Cari (Tanggal/Jumlah):",
                    "lengthMenu": "Tampilkan _MENU_ data",
                    "zeroRecords": "Data tidak ditemukan",
                    "info": "Menampilkan _START_ sampai _END_ dari _TOTAL_ data",
                    "paginate": {
                        "next": "Selanjutnya",
                        "previous": "Sebelumnya"
                    }
                },
                "order": [[1, "desc"]]
            });
        }

        //verifikasi persiapan prediksi
        $('#btnSiapkanPrediksi').on('click', function() {
            const count = $(this).data('count');
            const urlPrediksi = $(this).data('url');

            if (count < 365) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Data Belum Cukup',
                    text: 'Data Anda baru ' + count + ' baris. Minimal dibutuhkan 365 hari agar prediksi akurat.',
                    confirmButtonColor: '#7EBC12'
                });
            } else {
                Swal.fire({
                    title: 'Data Siap!',
                    text: "Data telah diverifikasi. Lanjut ke menu prediksi?",
                    icon: 'success',
                    showCancelButton: true,
                    confirmButtonColor: '#7EBC12',
                    cancelButtonColor: '#858796',
                    confirmButtonText: 'Ya, Prediksi Sekarang',
                    cancelButtonText: 'Kembali'
                }).then((result) => {
                    if (result.isConfirmed) {
                        window.location.href = urlPrediksi;
                    }
                });
            }
        });

        //import
        $('#formImportPenjualan').on('submit', function(e) {
            e.preventDefault();
            let form = this;

            Swal.fire({
                title: 'Mulai Import?',
                text: "Pastikan format file sudah benar.",
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#7EBC12',
                cancelButtonColor: '#858796',
                confirmButtonText: 'Ya, Import!',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    Swal.fire({
                        title: 'Sedang Memproses...',
                        allowOutsideClick: false,
                        didOpen: () => { Swal.showLoading(); }
                    });
                    form.submit();
                }
            });
        });

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

        $('.custom-file-input').on('change', function() {
            var fileName = $(this).val().split("\\").pop();
            $(this).next('.custom-file-label').addClass("selected").html(fileName);
        });

        //update manual masterdata
        $(document).on('submit', '.form-update-manual', function(e) {
            e.preventDefault();
            let form = this;
            Swal.fire({
                title: 'Simpan Perubahan?',
                text: "Jumlah penjualan akan diperbarui.",
                icon: 'info',
                showCancelButton: true,
                confirmButtonColor: '#36b9cc',
                confirmButtonText: 'Simpan',
            }).then((result) => {
                if (result.isConfirmed) {
                    form.submit();
                }
            });
        });
    });

})(jQuery);


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

function confirmCreateManual() {
    Swal.fire({
        title: 'Buat Data Manual?',
        text: "Isi data manual hanya dilakukan 1 per satu untuk menghindari duplikasi data.",
        icon: 'info',
        showCancelButton: true,
        confirmButtonText: 'Lanjutkan',
        confirmButtonColor: '#7EBC12',
        cancelButtonText: 'Batal'
    }).then((result) => {
        if (result.isConfirmed) {
            $('#createManualModal').modal('show');
        }
    });
}

function confirmDeleteAll() {
    Swal.fire({
        title: 'Hapus SEMUA data?',
        text: "Seluruh histori penjualan Anda akan dikosongkan permanen!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#858796',
        confirmButtonText: 'Ya, Hapus Semua!',
        cancelButtonText: 'Batal'
    }).then((result) => {
        if (result.isConfirmed) {
            document.getElementById('deleteAllForm').submit();
        }
    });
}

window.showImportError = function(msg) {
    Swal.fire({
        icon: 'error',
        title: 'Gagal Memproses Data!',
        html: `
            <div class="text-left small">
                <p>Terjadi kesalahan pada file atau data Anda:</p>
                <ul class="mb-0">
                    <li>Pastikan header: <strong>tanggal_penjualan</strong> dan <strong>jumlah</strong>.</li>
                    <li>Sistem menolak jika ada <strong>tanggal duplikat</strong> atau <strong>jumlah bernilai 0</strong>.</li>
                </ul>
            </div>
        `,
        confirmButtonColor: '#e74a3b'
    });
};

document.addEventListener("DOMContentLoaded", function () {

    const successEl = document.getElementById('swal-success');
    if (successEl && successEl.dataset.message) {
        Swal.fire({
            icon: 'success',
            title: 'Berhasil!',
            text: successEl.dataset.message,
            showConfirmButton: false,
            timer: 2000
        });
    }

    //bantuan
    const formBantuan = document.getElementById('form-kirim-bantuan');
    if (formBantuan) {
        formBantuan.addEventListener('submit', function (e) {
            e.preventDefault();
            Swal.fire({
                title: 'Kirim Pesan Bantuan?',
                text: "Pastikan data sudah benar agar admin dapat membantu Anda.",
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#4e73df',
                cancelButtonColor: '#858796',
                confirmButtonText: 'Ya, Kirim!',
                cancelButtonText: 'Batal'
            }).then((result) => {
                if (result.isConfirmed) {
                    Swal.fire({ 
                        title: 'Mengirim...', 
                        allowOutsideClick: false, 
                        didOpen: () => Swal.showLoading() 
                    });
                    formBantuan.submit();
                }
            });
        });
    }

    //edit profile
    const profileForm = document.getElementById("profileForm");
    if (profileForm) {
        const editBtn = document.getElementById("editBtn");
        const updateBtn = document.getElementById("updateBtn");
        const cancelBtn = document.getElementById("cancelBtn");
        const inputs = profileForm.querySelectorAll("input, textarea");

        if(editBtn) {
            editBtn.addEventListener("click", function () {
                inputs.forEach((input) => input.removeAttribute("disabled"));
                editBtn.classList.add("hidden");
                updateBtn.classList.remove("hidden");
                cancelBtn.classList.remove("hidden");
            });
        }

        if(cancelBtn) cancelBtn.addEventListener("click", () => location.reload());

        profileForm.addEventListener("submit", function (e) {
            e.preventDefault();
            Swal.fire({
                title: "Update Profil?",
                text: "Data akan diperbarui",
                icon: "warning",
                showCancelButton: true,
                confirmButtonText: "Update",
                cancelButtonText: "Batal",
                confirmButtonColor: "#7ebc12",
            }).then((result) => {
                if (result.isConfirmed) {
                    Swal.fire({ title: "Memproses...", allowOutsideClick: false, didOpen: () => Swal.showLoading() });
                    profileForm.submit();
                }
            });
        });
    }

    //edit password
    const passwordForm = document.getElementById("passwordForm");
    if (passwordForm) {
        const passwordInput = passwordForm.querySelector("input[name='password']");
        const confirmInput = passwordForm.querySelector("input[name='password_confirmation']");

        if(passwordInput) passwordInput.addEventListener("input", () => checkPassword(passwordInput));
        if(confirmInput) confirmInput.addEventListener("input", () => checkMatch(passwordInput, confirmInput));

        passwordForm.addEventListener("submit", function (e) {
            e.preventDefault();
            const valid = (passwordInput.value.length >= 8);
            if (!valid) {
                Swal.fire({ icon: "error", title: "Password tidak valid" });
                return;
            }

            Swal.fire({
                title: "Ubah Password?",
                text: "Pastikan password sudah benar",
                icon: "warning",
                showCancelButton: true,
                confirmButtonText: "Ubah",
                confirmButtonColor: "#eab308",
            }).then((result) => {
                if (result.isConfirmed) {
                    Swal.fire({ title: "Memproses...", allowOutsideClick: false, didOpen: () => Swal.showLoading() });
                    passwordForm.submit();
                }
            });
        });
    }
});

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

function checkMatch(p1, p2) {
    const matchText = document.getElementById("pw-match");
    if (!matchText) return;
    if (p1.value === p2.value && p2.value !== "") {
        matchText.innerHTML = "✔ Password cocok";
        matchText.className = "text-success small";
    } else {
        matchText.innerHTML = "✖ Password tidak sama";
        matchText.className = "text-danger small";
    }
}

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

function toggleNewPassword() {
    const input = document.getElementById("new_password");
    const icon = document.getElementById("eyeNewPassword");
    if (input.type === "password") {
        input.type = "text";
        icon.classList.replace("fa-eye", "fa-eye-slash");
    } else {
        input.type = "password";
        icon.classList.replace("fa-eye-slash", "fa-eye");
    }
}

function refreshPage(btn) {
    const icon = btn.querySelector('i');
    icon.classList.add('fa-spin');
    setTimeout(() => { location.reload(); }, 500);
}