jQuery(function ($) {
    setInterval(function () {
        var date = new Date(),
            time = date.toLocaleTimeString();
        $(".clock").html(time);
    }, 1000);
});



$(document).ready(function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
    } else {
        swal({ title: 'Oops!', text: 'Maaf, browser Anda tidak mendukung geolokasi HTML5.', icon: 'error', timer: 3000, });
    }
});

// Define callback function for successful attempt
function successCallback(position) {
    var latitude = "" + position.coords.latitude + "," + position.coords.longitude + "";
    $('.latitude').html(latitude);
}

// Define callback function for failed attempt
function errorCallback(error) {
    if (error.code == 1) {
        swal({ title: 'Oops!', text: 'Anda telah memutuskan untuk tidak membagikan lokasi Anda, tetapi tidak apa-apa. Kami tidak akan meminta Anda lagi.', icon: 'error', timer: 3000, });
    } else if (error.code == 2) {
        swal({ title: 'Oops!', text: 'Jaringan tidak aktif atau layanan penentuan posisi tidak dapat dijangkau.', icon: 'error', timer: 3000, });
    } else if (error.code == 3) {
        swal({ title: 'Oops!', text: 'Waktu percobaan habis sebelum bisa mendapatkan data lokasi.', icon: 'error', timer: 3000, });
    } else {
        swal({ title: 'Oops!', text: 'Waktu percobaan habis sebelum bisa mendapatkan data lokasi.', icon: 'error', timer: 3000, });
    }
}

    /** Scan Absensi Dengan mesin */
    $('body').click(function () {
        $('.qrcode').focus();
    });

    setTimeout(function () {
        $('.qrcode').focus().val('');
    }, 100);


    // Submit otomatis
    
// Submit otomatis
let isProcessing = false;
$('.qrcode').on('keydown', function (e) {
    if (isProcessing) return; // Stop jika masih dalam proses

    if (e.which === 13) { // Enter
        e.preventDefault(); // Hindari submit default
        
        let qrcode = $(this).val().trim();
        let latitude = $(".latitude").html();

        if (!qrcode) return; // Stop jika kosong

        isProcessing = true;

        // Buat FormData
        let formData = new FormData();
        formData.append('qrcode', qrcode);
        formData.append('latitude', latitude);

        setTimeout(function () {

            $.ajax({
                type: "POST",
                url: "./sw-proses.php?action=absen",
                data: formData,
                processData: false,
                contentType: false,

                success: function (data) {
                    const [status, message] = data.split("/");

                    if (status === "success") {
                        swal({
                            title: "Berhasil!",
                            text: message,
                            icon: "success",
                            timer: 2500
                        });

                        loaddata();
                        loaddatacouter();
                    } else {
                        swal({
                            title: "Oops!",
                            text: message || data,
                            icon: "error"
                        });
                    }
                },

                error: function (err) {
                    console.error("Error sending data: ", err);
                },

                complete: function () {
                    // Reset input dan buka proses lagi
                    $('.qrcode').val('').focus();
                    isProcessing = false;
                }

            });

        }, 500); // Delay sebelum proses
    }
});


function qrcode_webcame() {
    // Inisialisasi QR Scanner
    let isScanned = false;
    function onScanSuccess(decodedText, decodedResult) {
        if (isScanned) return; // Stop jika masih dalam proses
        isScanned = true;
        var latitude = $(".latitude").html();
        new Audio('../template/vendor/html5-qrcode/audio/beep.mp3').play().catch(console.error);
        $.ajax({
            type: "POST",
            url: "./sw-proses.php?action=absen-webcame",
            data: { qrcode: decodedText, latitude: latitude },
            success: function (data) {
                const [status, message] = data.split("/");
                if (status === 'success') {
                    swal({ title: 'Berhasil!', text: message, icon: 'success', timer: 2500 });
                    loaddata();
                    loaddatacouter();
                } else {
                    swal({ title: 'Oops!', text: data, icon: 'error', timer: 3000 });
                }
            },
            error: function (xhr, status, error) {
                console.error("AJAX Error: " + status + ": " + error);
                swal({ title: 'Oops!', text: 'Terjadi kesalahan saat mengirim data. Silakan coba lagi!', icon: 'error', timer: 3000 });
            }
        });

        setTimeout(() => { isScanned = false; }, 5000);

    }
    const config = {
        fps: 24,
        qrbox: (viewportWidth, viewportHeight) => ({ width: Math.floor(Math.min(viewportWidth, viewportHeight) * 0.7), height: Math.floor(Math.min(viewportWidth, viewportHeight) * 0.7) }),
        rememberLastUsedCamera: true,
        supportedScanTypes: [Html5QrcodeScanType.SCAN_TYPE_CAMERA]
    };

    const html5QrcodeScanner = new Html5QrcodeScanner("reader", config, false);
    html5QrcodeScanner.render(onScanSuccess);
}

loaddata();
function loaddata() {
    $(".data-absensi").html('<div class="text-center text-white"><span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> <p>Loading data...</p></div>');
    $(".data-absensi").load("./sw-proses.php?action=data-absensi");
}

loaddatacouter();
function loaddatacouter() {
    $.ajax({
        type: 'POST',
        url: './sw-proses.php?action=data-counter',
        dataType: 'json',
        success: function (response) {
            $('.total-pegawai').html(response.total_pegawai);
            $('.belum-absen').html(response.belum_absen);
            $('.ontime').html(response.on_time);
            $('.terlambat').html(response.terlambat);
            $('.izin').html(response.izin);
            $('.total-absen').html(response.total_absen);
            $('.persentase').html(response.persentase);
            console.log(response);
        },
        error: function (xhr, status, error) {
            console.error("AJAX Error: " + status + ": " + error);
        }
    });

}


