<!DOCTYPE html>
<html>

<head>
    <title>Jobcard Location Capture</title>
    <style>
        #map {
            height: 70vh;
            width: 100%;
            margin-top: 10px;
        }

        #coords {
            font-family: monospace;
            margin: 10px 0;
        }

        #form-section {
            margin-top: 20px;
        }

        label {
            display: block;
            margin-top: 8px;
        }

        input,
        textarea {
            width: 100%;
            padding: 5px;
        }

        button {
            margin-top: 10px;
            padding: 8px 16px;
        }

        #result {
            margin-top: 15px;
            font-family: monospace;
            white-space: pre-wrap;
        }
    </style>
</head>

<body>

    <h2>Jobcard Location Capture</h2>

    <div id="form-section">
        <label for="distance">Distance (in meters):</label>
        <input type="number" id="distance" placeholder="e.g., 100">

        <label for="jobcard">Jobcard Number:</label>
        <input type="text" id="jobcard" placeholder="e.g., JB123456">

        <label for="notes">Notes:</label>
        <textarea id="notes" rows="3" placeholder="Describe the job here..."></textarea>

        <button onclick="getLocation()">📍 Get Current Location</button>
        <button onclick="saveLocation()">💾 Save</button>
    </div>

    <div id="coords"></div>
    <div id="map"></div>
    <div id="result"></div>

    <script>
        let map;
        let marker;

        function getLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                    position => {
                        const lat = position.coords.latitude;
                        const lng = position.coords.longitude;
                        const userLocation = { lat, lng };

                        document.getElementById("coords").textContent =
                            `Latitude: ${lat.toFixed(6)}, Longitude: ${lng.toFixed(6)}`;

                        if (!map) {
                            map = new google.maps.Map(document.getElementById("map"), {
                                center: userLocation,
                                zoom: 18
                            });
                        } else {
                            map.setCenter(userLocation);
                        }

                        if (marker) marker.setMap(null);
                        marker = new google.maps.Marker({
                            position: userLocation,
                            map: map,
                            draggable: true,
                            title: "Drag me to adjust location"
                        });

                        const infoWindow = new google.maps.InfoWindow({
                            content: `Latitude: ${lat.toFixed(6)}<br>Longitude: ${lng.toFixed(6)}`
                        });

                        infoWindow.open(map, marker);
                    },
                    error => {
                        alert("Error getting location: " + error.message);
                    },
                    {
                        enableHighAccuracy: true,
                        timeout: 10000,
                        maximumAge: 0
                    }
                );
            } else {
                alert("Geolocation is not supported by your browser.");
            }
        }

        function saveLocation() {
            if (!marker) {
                alert("Please get your location first.");
                return;
            }

            const position = marker.getPosition();
            const lat = position.lat();
            const lng = position.lng();

            const distance = parseFloat(document.getElementById("distance").value);
            const jobcard = document.getElementById("jobcard").value.trim();
            const notes = document.getElementById("notes").value.trim();

            if (isNaN(distance) || !jobcard) {
                alert("Please enter a valid distance and jobcard number.");
                return;
            }

            const locationData = {
                latitude: lat.toFixed(6),
                longitude: lng.toFixed(6),
                distance: distance,
                jobcard: jobcard,
                notes: notes
            };

            // Show as pretty-printed JSON
            document.getElementById("result").textContent =
                `📍 Saved Location Info:\n` + JSON.stringify(locationData, null, 4);

            // Send to the server
            const xhr = new XMLHttpRequest();
            xhr.open("POST", "save.php", true);
            xhr.setRequestHeader("Content-Type", "application/json");
            xhr.onload = function () {
                alert(xhr.responseText);
            };
            xhr.onerror = function () {
                alert("Request error occurred!");
            };
            xhr.send(JSON.stringify(locationData));
        }
    </script>

    <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCXu62pAxEnoWh-eXMpYBkGsz_iX-EVm2k">
    </script>
</body>

</html>