<?php
// Pyrk shared map settings.
// Reads Google Maps key from app_settings.google_maps_api_key first,
// then falls back to config/google.maps_browser_key.
// If a Google key exists, maps use Google. Otherwise the system safely stays on OSM.

if (!function_exists('pyrk_map_setting_value')) {
    function pyrk_map_setting_value(string $key, string $default = ''): string
    {
        try {
            if (!class_exists('App\\Core\\Database')) return $default;
            $pdo = \App\Core\Database::connection();
            $stmt = $pdo->prepare('SELECT setting_value FROM app_settings WHERE setting_key = ? LIMIT 1');
            $stmt->execute([$key]);
            $value = $stmt->fetchColumn();
            if ($value === false || $value === null || trim((string)$value) === '') return $default;
            return trim((string)$value);
        } catch (Throwable) {
            return $default;
        }
    }
}

if (!function_exists('pyrk_map_context')) {
    function pyrk_map_context(): array
    {
        $config = $GLOBALS['config'] ?? [];

        $googleKey = pyrk_map_setting_value(
            'google_maps_api_key',
            (string)($config['google']['maps_browser_key'] ?? '')
        );

        $providerSetting = strtolower(pyrk_map_setting_value(
            'maps_provider',
            (string)($config['maps']['provider'] ?? 'osm')
        ));

        // Once the browser key exists in app_settings, use Google Maps automatically.
        $provider = $googleKey !== '' ? 'google' : ($providerSetting === 'google' ? 'google' : 'osm');

        $center = $config['maps']['default_center']
            ?? ($config['google']['default_center'] ?? ['lat' => 33.8938, 'lng' => 35.5018]);

        return [
            'provider' => $provider,
            'google_key' => $googleKey,
            'center' => $center,
            'osm_tile_url' => $config['maps']['osm']['tile_url'] ?? 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
            'osm_attribution' => $config['maps']['osm']['tile_attribution'] ?? '&copy; OpenStreetMap contributors',
        ];
    }
}
