function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(fetchLocation, showError);
    } else {
        alert("GPS is not supported by your browser.");
    }
}

function fetchLocation(position) {
    let latitude = position.coords.latitude;
    let longitude = position.coords.longitude;

    // Check if the location is within Sri Lanka
    if (latitude >= 5.9 && latitude <= 9.9 && longitude >= 79.5 && longitude <= 82.0) {
        localStorage.setItem("gpsPermission", "granted");

        $.ajax({
            url: "./location_data.php",
            type: "POST",
            data: { lat: latitude, lon: longitude },
            success: function (response) {
                console.log("Location saved:", response);
            },
            error: function (xhr, status, error) {
                console.error("Error saving location:", error);
            }
        });
    } else {
        console.log("Location is outside Sri Lanka.");
    }
}

function showError(error) {
    document.getElementById("message").innerText = "❌ GPS permission denied. Please enable it in browser settings.";
    alert("Please enable GPS location on your device.");
    localStorage.setItem("gpsPermission", "denied");
}

if (!localStorage.getItem("gpsPermission")) {
    document.getElementById("message").innerText = "Checking GPS permission...";

    window.onload = function() {
        getLocation();
    };
}
