<?php
declare(strict_types=1);

/**
 * 台灣城市／地區 JSON API（會員權限版）。
 */
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'app.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_public_session.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_public_member_auth.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'taiwan_cities.php';

fate_public_session_start();
$member = fate_public_member_current();
if ($member === null) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized'], JSON_UNESCAPED_UNICODE);
    exit;
}

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

try {
    $action = isset($_GET['action']) ? (string) $_GET['action'] : '';

    if ($action === 'getCities') {
        $cities = fate_taiwan_cities_list();
        echo json_encode($cities, JSON_UNESCAPED_UNICODE);
        exit;
    }

    if ($action === 'getDistricts' && isset($_GET['city'])) {
        $city = trim((string) $_GET['city']);
        $districts = fate_taiwan_districts_for_city($city);
        if ($districts === []) {
            echo json_encode(['error' => '找不到城市「' . $city . '」的地區資料'], JSON_UNESCAPED_UNICODE);
            exit;
        }
        echo json_encode($districts, JSON_UNESCAPED_UNICODE);
        exit;
    }

    echo json_encode(['error' => 'Invalid action'], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    http_response_code(500);
    error_log('fate member_cities_api: ' . $e->getMessage());
    echo json_encode(['error' => $e->getMessage()], JSON_UNESCAPED_UNICODE);
}
