<?php

$def_image = '/pic/glasses.jpg';
$image = isset($_GET['image']) ? $_GET['image'] : $def_image;

require_once 'exifgps.inc.php';

function image_exif_gps($file) {
  if (
    ($exif = @exif_read_data($_SERVER['DOCUMENT_ROOT'] . '/' . $file, 0, true)) !== false &&
    isset($exif['GPS']) && $exif['GPS']
  ) {
    exif_gps_vars($exif, $lat, $lon, $alt);
    // $d = print_r($exif['GPS'], true);
    // Return a JavaScript dictionary containing all useful GPS info
    return "{isValid: true, lat: $lat, lon: $lon, alt: $alt, file: \"$file\"}" .
      (isset($d) ? "\n/* $d*/": '');
  }
  else
    return "{isValid: false, file: \"$file\"}";
}

require 'app.inc.php';
require 'appmenu.inc.php';

$app = new Application('Map from EXIF GPS data', $menu);

$app->head_add = <<<JS
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" crossorigin="" />
JS;

$app->header();
?>

<h2><a href="<?php echo preg_replace('#^/album/#', '/album/-image/', $image) ?>"><?php echo $image ?></a></h2>
<p></p>

<div id="map" class="float" style="width: 900px; height: 900px; margin: 7px 14px 14px 0;"></div>

<div class="float">
<img src="<?php echo $image ?>" alt="<?php echo $image ?>" width="120" />
<?php if ($image == $def_image) { ?>
<p>© 2006 <a href="https://www.senklo.ch/">matthias hänni</a></p>
<?php } ?>
</div>

<?php
$exif = image_exif_gps($image);
echo <<<MAP
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" crossorigin=""></script>

<script>
const data = $exif;
if (data.isValid) {
    const latlon = [data.lat, data.lon];
    const zoom = 14;

    const map = L.map("map").setView(latlon, zoom);

    map.attributionControl.setPrefix(false);

    L.tileLayer("https://tile.osm.ch/osm-swiss-style/{z}/{x}/{y}.png", {
      attribution:
        'Data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' +
        ' <a href="https://opendatacommons.org/licenses/odbl/">ODbL</a>' +
        ' | Map by <a href="https://sosm.ch/">SOSM</a>'
    }).addTo(map);

    const marker = new L.marker(latlon).addTo(map);
} else {
    const map = document.getElementById('map');
    map.innerHTML = "<p>Keine GPS-Infos in diesem Bild.</p>";
}
</script>
MAP;
?>

<!--
<div class="float">
<form method="post" action="exifupd.php">
<input type="hidden" name="image" value="<?php echo $image ?>" />
<label for="lat">Latitude:</label>
<input type="text" id="lat" name="lat" /><br />
<label for="lon">Longitude:</label>
<input type="text" id="lon" name="lon" /><br />
<button type="submit">Update</button>
</form>
</div>
-->

<?php $app->footer(); ?>