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

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

    // Check if inside 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);
                document.getElementById("message").innerText = "Location saved at " + new Date().toLocaleTimeString();
            },
            error: function (xhr, status, error) {
                console.error("Error saving location:", error);
            }
        });
    } else {
        console.log("Location is outside Sri Lanka.");
    }
}

function showError(error) {
    let message = "❌ GPS permission denied. Please enable it in browser settings.";
    if (error.code === error.PERMISSION_DENIED) {
        document.getElementById("message").innerText = message;
        alert("Please enable GPS location on your device.");

        localStorage.setItem("gpsPermission", "denied");

        window.location.href = "location_denied.php";
    } else if (error.code === error.POSITION_UNAVAILABLE) {
        document.getElementById("message").innerText = "❌ Location information is unavailable.";
    } else if (error.code === error.TIMEOUT) {
        document.getElementById("message").innerText = "❌ The request to get user location timed out.";
    }
}

// Initial permission check and start tracking every 5 seconds
window.onload = function () {
    
    
    if (!localStorage.getItem("gpsPermission")) {
        document.getElementById("message").innerText = "Checking GPS permission...";
    } else {
        let gpsStatus = localStorage.getItem("gpsPermission") === "granted"
            ? "GPS permission granted."
            : "GPS permission denied.";
        document.getElementById("message").innerText = gpsStatus;
    }

    // Start tracking immediately
    getLocation();

    // Track location every 5 seconds
    setInterval(getLocation, 5000);
};