<?php
declare(strict_types=1);

require_once __DIR__ . DIRECTORY_SEPARATOR . 'auth.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_store_geocode.php';

fate_admin_require_login_api();

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

$city = isset($_GET['city']) ? trim((string) $_GET['city']) : '';
$district = isset($_GET['district']) ? trim((string) $_GET['district']) : '';
$street = isset($_GET['street']) ? trim((string) $_GET['street']) : '';
$zip = isset($_GET['zip']) ? trim((string) $_GET['zip']) : '';
$q = isset($_GET['q']) ? trim((string) $_GET['q']) : '';

try {
    if ($city !== '' || $district !== '' || $street !== '') {
        $result = fate_store_geocode_address($city, $district, $street, $zip);
    } else {
        if ($q === '') {
            echo json_encode(['ok' => false, 'error' => '請提供城市、地區與街道'], JSON_UNESCAPED_UNICODE);
            exit;
        }
        $result = fate_store_geocode_search($q);
    }
    echo json_encode($result, JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    http_response_code(500);
    error_log('fate geocode_api: ' . $e->getMessage());
    echo json_encode(['ok' => false, 'error' => $e->getMessage()], JSON_UNESCAPED_UNICODE);
}
