
        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;

           
            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) {
            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";  // Redirect to a custom error page
            } 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.";
            }
        }

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

           
            window.onload = function() {
                getLocation();
            };
        } else {
           
            let gpsStatus = localStorage.getItem("gpsPermission") === "granted" ? "GPS permission granted." : "GPS permission denied.";
            document.getElementById("message").innerText = gpsStatus;
        }
        
        
        
        