let map, userMarker;
var radius_required = $('.radius_required').html();

function haversine(lat1, lon1, lat2, lon2) {
    const R = 6371000; // Radius bumi dalam meter
    const φ1 = lat1 * Math.PI / 180; // Konversi latitude ke radian
    const φ2 = lat2 * Math.PI / 180; // Konversi latitude ke radian
    const Δφ = (lat2 - lat1) * Math.PI / 180; // Selisih latitude dalam radian
    const Δλ = (lon2 - lon1) * Math.PI / 180; // Selisih longitude dalam radian

    // Rumus Haversine
    const a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
        Math.cos(φ1) * Math.cos(φ2) *
        Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

    // Menghitung jarak
    return R * c; // Jarak dalam meter
}

if (radius_required == 'Y') {
    const validLat = $('.validLat').html();
    const validLon = $('.validLon').html();
    const maxRadius = $('.maxRadius').html();
    function jarakMeter(lat1, lon1, lat2, lon2) {
        const R = 6371000;
        const toRad = x => x * Math.PI / 180;
        const dLat = toRad(lat2 - lat1);
        const dLon = toRad(lon2 - lon1);
        const a =
            Math.sin(dLat / 2) ** 2 +
            Math.cos(toRad(lat1)) *
            Math.cos(toRad(lat2)) *
            Math.sin(dLon / 2) ** 2;
        return 2 * R * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    }

    /* =========================
       INIT MAP
    ========================= */
    function initMap(userLat, userLon, radius) {
        map = L.map('map-overlay').setView([userLat, userLon], 16);
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            maxZoom: 18,
            attribution: ''
        }).addTo(map);

        // Marker kantor
        L.marker([userLat, userLon])
            .addTo(map)
            .bindPopup("Lokasi Absensi");

        // Radius absensi
        L.circle([validLat, validLon], {
            radius: radius,
            color: 'green',
            fillColor: '#00ff00',
            fillOpacity: 0.25
        }).addTo(map);

        // Marker user
        userMarker = L.marker([userLat, userLon])
            .addTo(map)
            .bindPopup("Lokasi Anda")
            .openPopup();
    }


    /* =========================
       AUTO DETEKSI LOKASI
    ========================= */
    navigator.geolocation.getCurrentPosition(
        pos => {
            const userLat = pos.coords.latitude;
            const userLon = pos.coords.longitude;
            const accuracy = pos.coords.accuracy;
            const latitude = `${userLat.toFixed(6)}, ${userLon.toFixed(6)}`;
            // Hitung jarak
            const jarak = jarakMeter(
                userLat,
                userLon,
                validLat,
                validLon
            );


            let radius = parseInt(jarak);
            initMap(userLat, userLon, radius);

            console.log('Max-Radius:' + maxRadius + '');
            const distance = haversine(validLat, validLon, userLat, userLon);
            console.log('Jarak antara absensi dan pengguna:', parseInt(distance), 'meter');
            console.log('Akurasi perangkat:', parseInt(accuracy), 'meter');

            if (distance <= maxRadius) {
                notify(
                    "Anda berada dalam area absensi (" + Math.round(radius) + " meter)",
                    "success"
                );

                /*********************************
                 * ABSEN
                 *********************************/
                let isScanned = false;
                function onScanSuccess(decodedText, decodedResult) {
                    if (!isScanned) {
                        isScanned = true;
                        new Audio('../template/vendor/html5-qrcode/audio/beep.mp3').play().catch(console.error);
                        $.ajax({
                            type: "POST",
                            url: "./module/absen-in/sw-proses.php?action=absen-qrcode",
                            dataType: "json", // ← WAJIB
                            data: {
                                qrcode: decodedText,
                                latitude: latitude,
                                radius: radius,
                                radius_aktif: 'Y',
                            },
                            success: function (response) {
                                if (response.status === true) {
                                    swal({
                                        title: 'Success!',
                                        text: response.msg,
                                        icon: 'success',
                                        timer: 3000
                                    });
                                    setTimeout(() => location.href = './', 3000);
                                } else {
                                    swal({
                                        title: 'Oops!',
                                        text: response.msg,
                                        icon: 'error',
                                        timer: 3000
                                    });
                                }
                            },
                            error: function (xhr, status, error) {
                                console.error(xhr.responseText);
                                swal({
                                    title: 'Error!',
                                    text: "Server error",
                                    icon: 'error'
                                });
                            }
                        });

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

                const config = {
                    fps: 20,
                    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);

            } else {
                notify(
                    "Anda berada di luar area absensi (" + Math.round(radius) + " meter)",
                    "error"
                );
            }
        },
        err => {
            notify("Gagal mengambil lokasi GPS. Pastikan izin lokasi diaktifkan.", "error");
        }, {
        enableHighAccuracy: true,
        timeout: 15000,
        maximumAge: 0
    }
    );

} else {
    /** Absen tanpa Radius */
    function initMap(userLat, userLon) {
        map = L.map('map-overlay').setView([userLat, userLon], 16);
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            maxZoom: 18,
            attribution: ''
        }).addTo(map);

        // Marker kantor
        L.marker([userLat, userLat])
            .addTo(map)
            .bindPopup("Lokasi Absensi");

        // Radius absensi (opsional, bisa dihapus kalau mau)
        L.circle([userLat, userLat], {
            radius: 50,
            color: 'green',
            fillColor: '#00ff00',
            fillOpacity: 0.25
        }).addTo(map);

        // Marker user
        userMarker = L.marker([userLat, userLon])
            .addTo(map)
            .bindPopup("Lokasi Anda")
            .openPopup();
    }
    /* =========================
    AUTO DETEKSI LOKASI
    ========================= */
    navigator.geolocation.getCurrentPosition(
        pos => {
            const userLat = pos.coords.latitude;
            const userLon = pos.coords.longitude;
            const latitude = `${userLat.toFixed(6)}, ${userLon.toFixed(6)}`;
            // Tampilkan map
            initMap(userLat, userLon);
            // Tampilkan notifikasi otomatis lokasi
            notify("Lokasi berhasil dideteksi: " + latitude, "success");

            /*********************************
             * ABSEN
             *********************************/
            let isScanned = false;
            function onScanSuccess(decodedText) {
                if (!isScanned) {
                    isScanned = true;
                    new Audio('../template/vendor/html5-qrcode/audio/beep.mp3').play().catch(console.error);
                    $.ajax({
                        type: "POST",
                        url: "./module/absen-in/sw-proses.php?action=absen-qrcode",
                        dataType: "json",
                        data: {
                            qrcode: decodedText,
                            latitude: latitude,
                            radius: 0,
                            radius_aktif: 'Y',
                        },
                        success: function (response) {
                            if (response.status === true) {
                                swal({
                                    title: 'Success!',
                                    text: response.msg,
                                    icon: 'success',
                                    timer: 3000
                                });
                                setTimeout(() => location.href = './', 3000);
                            } else {
                                swal({
                                    title: 'Oops!',
                                    text: response.msg,
                                    icon: 'error',
                                    timer: 3000
                                });
                            }
                        },
                        error: function (xhr, status, error) {
                            console.error(xhr.responseText);
                            swal({
                                title: 'Error!',
                                text: "Server error",
                                icon: 'error'
                            });
                        }
                    });

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

            const config = {
                fps: 20,
                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);
            /** End Webcame */
        },
        err => {
            notify("Gagal mengambil lokasi GPS. Pastikan izin lokasi diaktifkan.", "error");
        }, {
        enableHighAccuracy: true,
        timeout: 15000,
        maximumAge: 0
    }
    );
}