<?php
/**
 * Resolves ISO 3166-1 alpha-2 country codes (as stored in the stats tables by
 * the geo lookup) to human-readable names for the admin dashboard.
 *
 * Two sources, in order:
 *   1. ext-intl / ICU — always current, and matches the names users already see
 *      in their browser and OS.
 *   2. inc/stats/country-names.php — a generated fallback map for hosts built
 *      without ext-intl. Regenerate with bin/generate-country-names.php.
 *
 * Unknown or empty codes fall back to the raw code (never a blank cell), so a
 * newly-issued territory still renders something meaningful.
 */

if (!defined('ABSPATH')) {
    exit;
}

class AF_Country_Names {

    /** @var array|null Lazily-loaded fallback map. */
    private static $map = null;

    /** @var bool|null Cached ext-intl availability. */
    private static $has_intl = null;

    /**
     * Full country name for a 2-letter code, e.g. 'GB' => 'United Kingdom'.
     *
     * @param string $code ISO 3166-1 alpha-2 code (case-insensitive).
     * @return string Display name, or the code itself if unrecognised.
     */
    public static function get($code) {
        $code = strtoupper(trim((string) $code));
        if ($code === '') {
            return '';
        }

        if (self::$has_intl === null) {
            self::$has_intl = class_exists('\Locale') && method_exists('\Locale', 'getDisplayRegion');
        }

        if (self::$has_intl) {
            $name = \Locale::getDisplayRegion('-' . $code, 'en');
            // ICU echoes the input back when it doesn't know the region.
            if (!empty($name) && $name !== $code) {
                return $name;
            }
        }

        if (self::$map === null) {
            $file = __DIR__ . '/country-names.php';
            $map  = file_exists($file) ? include $file : array();
            self::$map = is_array($map) ? $map : array();
        }

        return isset(self::$map[$code]) ? self::$map[$code] : $code;
    }

    /**
     * Add a `country_name` key to each row of a stats result set.
     *
     * @param array  $rows Result rows (associative).
     * @param string $key  Column holding the country code.
     * @return array
     */
    public static function decorate($rows, $key = 'country') {
        foreach ((array) $rows as $i => $row) {
            if (is_array($row) && isset($row[$key])) {
                $rows[$i]['country_name'] = self::get($row[$key]);
            }
        }
        return $rows;
    }
}
