<?php
/* ============================================================================
 *  config/maps.php — Google Maps reverse-geocoding for attendance punches.
 *  Turns GPS lat/lng into a human place name (village, district). The API key
 *  stays here on the server and is never sent to the browser.
 *
 *  SETUP: 1) Google Cloud Console → enable "Geocoding API".
 *         2) Create an API key, restrict it to the Geocoding API (and by your
 *            server IP for safety), then paste it below.
 * ==========================================================================*/

/** PASTE YOUR GOOGLE MAPS API KEY HERE */
if (!defined('GOOGLE_MAPS_API_KEY')) {
    define('GOOGLE_MAPS_API_KEY', '');   // e.g. 'AIzaSy....'
}

/**
 * Reverse geocode a coordinate to a short place name like
 * "ບ້ານ ໂພນປ່າເປົ້າ, ສີສັດຕະນາກ" (village, district).
 * Returns null on failure / when no key is set (never throws).
 */
if (!function_exists('maps_place_name')) {
    function maps_place_name($lat, $lng): ?string {
        $key = GOOGLE_MAPS_API_KEY;
        if ($key === '' || $lat === null || $lng === null) return null;
        $lat = (float)$lat; $lng = (float)$lng;
        if ($lat === 0.0 && $lng === 0.0) return null;

        $url = 'https://maps.googleapis.com/maps/api/geocode/json'
             . '?latlng=' . rawurlencode($lat . ',' . $lng)
             . '&language=lo'
             . '&key=' . rawurlencode($key);

        $json = maps__http_get($url);
        if (!$json) return null;
        $data = json_decode($json, true);
        if (!is_array($data) || ($data['status'] ?? '') !== 'OK' || empty($data['results'])) return null;

        /* collect components by type from the most specific result */
        $pick = function(array $types) use ($data): ?string {
            foreach ($data['results'] as $res) {
                foreach (($res['address_components'] ?? []) as $c) {
                    foreach ($types as $t) {
                        if (in_array($t, $c['types'] ?? [], true)) return $c['long_name'];
                    }
                }
            }
            return null;
        };

        $village  = $pick(['sublocality_level_1','sublocality','neighborhood','administrative_area_level_3']);
        $district = $pick(['administrative_area_level_2','locality','administrative_area_level_1']);

        $parts = array_values(array_unique(array_filter([$village, $district])));
        if ($parts) return mb_substr(implode(', ', $parts), 0, 180);

        /* fallback: first formatted address */
        $fa = $data['results'][0]['formatted_address'] ?? null;
        return $fa ? mb_substr($fa, 0, 180) : null;
    }
}

/** Small HTTP GET helper (curl, falls back to file_get_contents). */
if (!function_exists('maps__http_get')) {
    function maps__http_get(string $url): ?string {
        if (function_exists('curl_init')) {
            $ch = curl_init($url);
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT        => 6,
                CURLOPT_CONNECTTIMEOUT => 4,
                CURLOPT_SSL_VERIFYPEER => true,
            ]);
            $out = curl_exec($ch);
            curl_close($ch);
            return $out !== false ? $out : null;
        }
        $ctx = stream_context_create(['http' => ['timeout' => 6]]);
        $out = @file_get_contents($url, false, $ctx);
        return $out !== false ? $out : null;
    }
}