<?php
include "../root.class.php";

$db = new db_safeguard();
$res = $db->query("test_locations", "SELECT * FROM test_locations WHERE 1");

$js_array = "[";
if ($res->num_rows > 0) {
    $first = true;
    while ($row = $res->fetch_assoc()) {
        if ($first) {
            $first = false;
        } else {
            $js_array .= ",";
        }
        $js_array .= "{
            latitude: '" . $row["latitude"] . "',
            longitude: '" . $row["longitude"] . "',
            distance: '" . $row["distance"] . "',
            jobcard: '" . $row["jobcard"] . "',
            notes: '" . $row["notes"] . "'
        }";
    }
}
$js_array .= "]";
?>

<!DOCTYPE html>
<html>

<head>
    <title>Saved Locations Viewer</title>
    <style>
        #map {
            height: 90vh;
            width: 100%;
            margin-top: 10px;
        }

        body {
            font-family: Arial, sans-serif;
            padding: 10px;
        }
    </style>
</head>

<body>
    <h2>Saved Jobcard Locations</h2>
    <div id="map"></div>

    <script>
        // 🔧 Add your saved locations here:
        const savedLocations = <?php echo $js_array; ?>;

        let map;

        function initMap() {
            if (savedLocations.length === 0) {
                alert("No locations to display.");
                return;
            }

            const firstLocation = {
                lat: parseFloat(savedLocations[0].latitude),
                lng: parseFloat(savedLocations[0].longitude)
            };

            map = new google.maps.Map(document.getElementById("map"), {
                center: firstLocation,
                zoom: 15
            });

            savedLocations.forEach((location, index) => {
                const position = {
                    lat: parseFloat(location.latitude),
                    lng: parseFloat(location.longitude)
                };

                const marker = new google.maps.Marker({
                    position,
                    map,
                    label: (index + 1).toString()
                });

                const infoContent = `
                    <strong>Jobcard:</strong> ${location.jobcard}<br>
                    <strong>Distance:</strong> ${location.distance} m<br>
                    <strong>Notes:</strong> ${location.notes}<br>
                    <strong>Lat:</strong> ${location.latitude}<br>
                    <strong>Lng:</strong> ${location.longitude}
                `;

                const infoWindow = new google.maps.InfoWindow({
                    content: infoContent
                });

                marker.addListener('click', () => {
                    infoWindow.open(map, marker);
                });
            });
        }
    </script>

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

</html>