<?php
require_once __DIR__ . '/../app/config/config.php';

header('Content-Type: application/json; charset=utf-8');

$lat = isset($_GET['lat']) ? (float)$_GET['lat'] : null;
$lng = isset($_GET['lng']) ? (float)$_GET['lng'] : null;

if ($lat === null || $lng === null) {
  http_response_code(400);
  echo json_encode(['ok' => false, 'error' => 'Missing lat/lng']);
  exit;
}

// Basic validation
if ($lat < -90 || $lat > 90 || $lng < -180 || $lng > 180) {
  http_response_code(400);
  echo json_encode(['ok' => false, 'error' => 'Invalid coordinates']);
  exit;
}

// OpenStreetMap Nominatim reverse geocoding
$url = "https://nominatim.openstreetmap.org/reverse?format=jsonv2&lat=" . urlencode((string)$lat) .
       "&lon=" . urlencode((string)$lng) . "&zoom=18&addressdetails=1";

$ch = curl_init($url);
curl_setopt_array($ch, [
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_CONNECTTIMEOUT => 8,
  CURLOPT_TIMEOUT => 12,
  CURLOPT_USERAGENT => (defined('APP_NAME') ? APP_NAME : 'RentalInspection') . ' (reverse geocode)',
]);

$res = curl_exec($ch);
$err = curl_error($ch);
$code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($res === false || $code < 200 || $code >= 300) {
  http_response_code(502);
  echo json_encode(['ok' => false, 'error' => 'Reverse geocode failed', 'detail' => $err ?: ('HTTP ' . $code)]);
  exit;
}

$data = json_decode($res, true);
$address = $data['display_name'] ?? null;

echo json_encode([
  'ok' => true,
  'address' => $address,
]);
