<?php
declare(strict_types=1);

/**
 * 新增店家 GPS：優先 Google Geocoding；僅在金鑰未設定或明確允許時才 OSM 備援。
 */

require_once __DIR__ . DIRECTORY_SEPARATOR . 'google_geocode.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'osm_nominatim.php';

/** 設為 false 時，已設定 Google 金鑰則不再自動改用 OSM（方便排查金鑰問題） */
if (!defined('FATE_GEOCODE_OSM_FALLBACK')) {
    define('FATE_GEOCODE_OSM_FALLBACK', true);
}

if (!function_exists('fate_store_geocode_address')) {
    /**
     * @return array{ok:bool,lat?:float,lng?:float,display_name?:string,google_map_location?:string,error?:string,precision?:string,provider?:string,google_fallback?:bool,google_error?:string,google_configured?:bool}
     */
    function fate_store_geocode_address(string $city, string $district, string $street, string $zip = ''): array
    {
        $googleConfigured = fate_google_geocode_configured();
        $googleErr = null;

        if ($googleConfigured) {
            $google = fate_google_geocode_address($city, $district, $street, $zip);
            if (!empty($google['ok'])) {
                $google['google_configured'] = true;

                return $google;
            }
            if (empty($google['skip'])) {
                $googleErr = (string) ($google['error'] ?? 'Google 查詢失敗');
            }
        }

        if ($googleConfigured && !FATE_GEOCODE_OSM_FALLBACK) {
            return [
                'ok' => false,
                'google_configured' => true,
                'error' => $googleErr ?? 'Google 無法取得座標，請檢查金鑰、Geocoding API 與地址，或手動填入 GPS。',
            ];
        }

        if (!$googleConfigured && !FATE_GEOCODE_OSM_FALLBACK) {
            return [
                'ok' => false,
                'google_configured' => false,
                'error' => '請於後台「網站與模版」設定 Google Geocoding API 金鑰（google_geocoding）。',
            ];
        }

        $osm = fate_osm_geocode_address($city, $district, $street);
        if (!empty($osm['ok'])) {
            $osm['provider'] = 'osm';
            $osm['google_configured'] = $googleConfigured;
            if ($googleErr !== null && $googleErr !== '') {
                $osm['google_fallback'] = true;
                $osm['google_error'] = $googleErr;
            } elseif (!$googleConfigured) {
                $osm['google_fallback'] = true;
                $osm['google_error'] = '未設定 Google API 金鑰（已改用 OSM）';
            }

            return $osm;
        }

        $osmErr = (string) ($osm['error'] ?? '找不到符合的座標');
        if ($googleErr !== null && $googleErr !== '') {
            return [
                'ok' => false,
                'google_configured' => $googleConfigured,
                'error' => $googleErr . '；備援 OSM：' . $osmErr,
            ];
        }

        return [
            'ok' => false,
            'google_configured' => $googleConfigured,
            'error' => $osmErr,
        ];
    }
}

if (!function_exists('fate_store_geocode_search')) {
    /**
     * @return array{ok:bool,lat?:float,lng?:float,display_name?:string,google_map_location?:string,error?:string,precision?:string,provider?:string,google_fallback?:bool,google_error?:string,google_configured?:bool}
     */
    function fate_store_geocode_search(string $query): array
    {
        $googleConfigured = fate_google_geocode_configured();
        $googleErr = null;

        if ($googleConfigured) {
            $google = fate_google_geocode_search($query);
            if (!empty($google['ok'])) {
                $google['google_configured'] = true;

                return $google;
            }
            if (empty($google['skip'])) {
                $googleErr = (string) ($google['error'] ?? 'Google 查詢失敗');
            }
        }

        if ($googleConfigured && !FATE_GEOCODE_OSM_FALLBACK) {
            return [
                'ok' => false,
                'google_configured' => true,
                'error' => $googleErr ?? 'Google 無法取得座標。',
            ];
        }

        $osm = fate_osm_geocode_search($query);
        if (!empty($osm['ok'])) {
            $osm['provider'] = 'osm';
            $osm['google_configured'] = $googleConfigured;
            if ($googleErr !== null && $googleErr !== '') {
                $osm['google_fallback'] = true;
                $osm['google_error'] = $googleErr;
            } elseif (!$googleConfigured) {
                $osm['google_fallback'] = true;
                $osm['google_error'] = '未設定 Google API 金鑰（已改用 OSM）';
            }

            return $osm;
        }

        $osmErr = (string) ($osm['error'] ?? '找不到符合的座標');
        if ($googleErr !== null && $googleErr !== '') {
            return [
                'ok' => false,
                'google_configured' => $googleConfigured,
                'error' => $googleErr . '；備援 OSM：' . $osmErr,
            ];
        }

        return ['ok' => false, 'google_configured' => $googleConfigured, 'error' => $osmErr];
    }
}
