<?php
/**
 * Bilingual content helpers (English + local language).
 *
 * English is the default on public pages. Base fields hold local copy;
 * *_en fields hold English. Local is shown when the visitor uses a matching
 * locale (e.g. Swedish). Optional dual-language mode shows both.
 *
 * @package Maca_Menu_List
 */

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

/**
 * Visitor / site locale string.
 *
 * @return string
 */
function maca_menulist_get_visitor_locale() {
    if (function_exists('determine_locale')) {
        return determine_locale();
    }

    return get_locale();
}

/**
 * WordPress site locale (Settings → General → Site Language).
 *
 * Uses the stored site language, not the visitor or admin UI locale.
 *
 * @return string
 */
function maca_menulist_get_site_locale() {
    if (defined('WPLANG')) {
        $constant_locale = WPLANG;

        if (is_string($constant_locale) && $constant_locale !== '') {
            return $constant_locale;
        }
    }

    $locale = get_option('WPLANG', '');

    if (!is_string($locale)) {
        $locale = '';
    }

    $locale = trim($locale);

    if ($locale === '' || $locale === 'en' || $locale === 'en_US') {
        return 'en_US';
    }

    return $locale;
}

/**
 * Whether the site language is English (no local/English menu choice needed).
 *
 * @return bool
 */
function maca_menulist_site_locale_is_english() {
    $locale = strtolower(str_replace('-', '_', maca_menulist_get_site_locale()));

    if (in_array($locale, array('en', 'en_us', 'en_gb', 'en_au', 'en_ca', 'en_nz', 'en_za'), true)) {
        return true;
    }

    return strpos($locale, 'en_') === 0;
}

/**
 * Known language labels for admin fallbacks and flags.
 *
 * @return array<string, string>
 */
function maca_menulist_get_local_language_options() {
    return array(
        'sv' => __('Swedish', 'maca-restu-pro'),
        'no' => __('Norwegian', 'maca-restu-pro'),
        'nb' => __('Norwegian', 'maca-restu-pro'),
        'nn' => __('Norwegian', 'maca-restu-pro'),
        'da' => __('Danish', 'maca-restu-pro'),
        'fi' => __('Finnish', 'maca-restu-pro'),
        'de' => __('German', 'maca-restu-pro'),
        'fr' => __('French', 'maca-restu-pro'),
        'es' => __('Spanish', 'maca-restu-pro'),
        'it' => __('Italian', 'maca-restu-pro'),
        'nl' => __('Dutch', 'maca-restu-pro'),
        'pl' => __('Polish', 'maca-restu-pro'),
        'pt' => __('Portuguese', 'maca-restu-pro'),
        'cs' => __('Czech', 'maca-restu-pro'),
        'en' => __('English', 'maca-restu-pro'),
    );
}

/**
 * ISO 639-1 language code from the WordPress site locale.
 *
 * @return string
 */
function maca_menulist_get_local_language_code() {
    $locale = strtolower(maca_menulist_get_site_locale());
    $code = sanitize_key(substr($locale, 0, 2));

    return $code !== '' ? $code : 'en';
}

/**
 * Human-readable label for the site (local) language.
 *
 * @return string
 */
function maca_menulist_get_local_language_label() {
    $locale = maca_menulist_get_site_locale();

    if (function_exists('locale_get_display_name')) {
        $display = locale_get_display_name($locale, $locale);

        if (is_string($display) && $display !== '') {
            return $display;
        }
    }

    if (!function_exists('wp_get_available_translations')) {
        require_once ABSPATH . 'wp-admin/includes/translation-install.php';
    }

    if (function_exists('wp_get_available_translations')) {
        $translations = wp_get_available_translations();

        if (isset($translations[ $locale ]['native_name']) && is_string($translations[ $locale ]['native_name'])) {
            return $translations[ $locale ]['native_name'];
        }
    }

    $options = maca_menulist_get_local_language_options();
    $code = maca_menulist_get_local_language_code();

    if (isset($options[ $code ])) {
        return $options[ $code ];
    }

    return __('Local language', 'maca-restu-pro');
}

/**
 * Admin label for local-language content fields.
 *
 * @return string
 */
function maca_menulist_get_local_language_name() {
    return maca_menulist_get_local_language_label();
}

/**
 * Whether bilingual menu settings (switcher, dual-language display) are available.
 *
 * Requires active Pro subscription on the Pro plugin; unavailable in the free plugin.
 *
 * @return bool
 */
function maca_menulist_bilingual_menus_available() {
    if (!defined('MACA_MENULIST_PRO') || !MACA_MENULIST_PRO) {
        return false;
    }

    if (!function_exists('maca_menulist_pro_has_feature')) {
        return false;
    }

    return maca_menulist_pro_has_feature('bilingual_menus');
}

/**
 * Whether guest UI string overrides are available in admin settings.
 *
 * @return bool
 */
function maca_menulist_guest_ui_strings_available() {
    if (!defined('MACA_MENULIST_PRO') || !MACA_MENULIST_PRO) {
        return false;
    }

    if (!function_exists('maca_menulist_pro_has_feature')) {
        return false;
    }

    return maca_menulist_pro_has_feature('guest_ui_strings');
}

/**
 * Whether both local and English should appear on public menus.
 *
 * @return bool
 */
function maca_menulist_dual_language_menu_enabled() {
    if (!maca_menulist_bilingual_menus_available()) {
        return false;
    }

    return get_option('maca_menulist_dual_language_menu', '0') === '1';
}

/**
 * Guest menu language preference from cookie.
 *
 * @return string local|en|auto
 */
function maca_menulist_get_menu_language_preference() {
    if (isset($_COOKIE['maca_menu_lang'])) {
        $pref = sanitize_key((string) wp_unslash($_COOKIE['maca_menu_lang']));

        if (in_array($pref, array('local', 'en'), true)) {
            return $pref;
        }
    }

    return 'auto';
}

/**
 * Whether guests can choose between site language and English on menus.
 *
 * @return bool
 */
function maca_menulist_menu_has_language_choice() {
    return !maca_menulist_site_locale_is_english();
}

/**
 * Whether the language switcher should appear on public menus.
 *
 * @return bool
 */
function maca_menulist_menu_language_switcher_enabled() {
    if (!maca_menulist_bilingual_menus_available()) {
        return false;
    }

    if (!maca_menulist_menu_has_language_choice()) {
        return false;
    }

    if (maca_menulist_dual_language_menu_enabled()) {
        return false;
    }

    return get_option('maca_menulist_menu_language_switcher', '1') === '1';
}

/**
 * Whether the current visitor should see local-language content only.
 *
 * @return bool
 */
function maca_menulist_should_use_local_content() {
    static $cached = null;
    static $computing = false;

    if ($cached !== null) {
        return $cached;
    }

    if ($computing) {
        return !maca_menulist_site_locale_is_english();
    }

    $computing = true;

    if (maca_menulist_dual_language_menu_enabled()) {
        $cached = false;
        $computing = false;
        return $cached;
    }

    if (maca_menulist_site_locale_is_english()) {
        $cached = true;
        $computing = false;
        return $cached;
    }

    $pref = maca_menulist_get_menu_language_preference();

    if ($pref === 'local') {
        $cached = true;
        $computing = false;
        return $cached;
    }

    if ($pref === 'en') {
        $cached = false;
        $computing = false;
        return $cached;
    }

    $local_code = maca_menulist_get_local_language_code();

    $cached = strpos(strtolower(maca_menulist_get_visitor_locale()), $local_code) === 0;
    $computing = false;

    return $cached;
}

/**
 * Translate guest-facing UI strings based on menu language preference.
 *
 * When the guest chose English (or auto-detected English), msgids are returned
 * as-is. Otherwise the site locale translation is used.
 *
 * @param string $text English message id.
 * @return string
 */
function maca_menulist_guest_ui_string($text) {
    return maca_menulist_resolve_guest_ui_string($text);
}

/**
 * Plural form of maca_menulist_guest_ui_string().
 *
 * @param string $single Singular English message id.
 * @param string $plural Plural English message id.
 * @param int    $count  Item count.
 * @return string
 */
function maca_menulist_guest_ui_string_plural($single, $plural, $count) {
    $pick = ($count === 1) ? $single : $plural;

    return maca_menulist_resolve_guest_string($pick, maca_menulist_should_use_local_content());
}

/**
 * Encode a Unicode code point as a UTF-8 string (no mbstring required).
 *
 * @param int $codepoint Unicode scalar value.
 * @return string
 */
function maca_menulist_utf8_chr($codepoint) {
    $codepoint = (int) $codepoint;

    if ($codepoint <= 0x7F) {
        return chr($codepoint);
    }

    if ($codepoint <= 0x7FF) {
        return chr(0xC0 | ($codepoint >> 6))
            . chr(0x80 | ($codepoint & 0x3F));
    }

    if ($codepoint <= 0xFFFF) {
        return chr(0xE0 | ($codepoint >> 12))
            . chr(0x80 | (($codepoint >> 6) & 0x3F))
            . chr(0x80 | ($codepoint & 0x3F));
    }

    if ($codepoint <= 0x10FFFF) {
        return chr(0xF0 | ($codepoint >> 18))
            . chr(0x80 | (($codepoint >> 12) & 0x3F))
            . chr(0x80 | (($codepoint >> 6) & 0x3F))
            . chr(0x80 | ($codepoint & 0x3F));
    }

    return '';
}

/**
 * Build a regional indicator flag emoji from an ISO 3166-1 alpha-2 country code.
 *
 * @param string $country_code Two-letter country code, e.g. SE, GB.
 * @return string
 */
function maca_menulist_country_code_to_flag_emoji($country_code) {
    $country_code = strtoupper((string) $country_code);

    if (strlen($country_code) !== 2 || !ctype_alpha($country_code)) {
        return maca_menulist_utf8_chr(0x1F3F3) . maca_menulist_utf8_chr(0xFE0F);
    }

    static $known_flags = array(
        // Regional indicator pairs as raw UTF-8 (works without mbstring).
        'SE' => "\xF0\x9F\x87\xB8\xF0\x9F\x87\xAA",
        'GB' => "\xF0\x9F\x87\xAC\xF0\x9F\x87\xA7",
        'NO' => "\xF0\x9F\x87\xB3\xF0\x9F\x87\xB4",
        'DK' => "\xF0\x9F\x87\xA9\xF0\x9F\x87\xB0",
        'FI' => "\xF0\x9F\x87\xAB\xF0\x9F\x87\xAE",
        'DE' => "\xF0\x9F\x87\xA9\xF0\x9F\x87\xAA",
        'FR' => "\xF0\x9F\x87\xAB\xF0\x9F\x87\xB7",
        'ES' => "\xF0\x9F\x87\xAA\xF0\x9F\x87\xB8",
        'IT' => "\xF0\x9F\x87\xAE\xF0\x9F\x87\xB9",
        'NL' => "\xF0\x9F\x87\xB3\xF0\x9F\x87\xB1",
        'PL' => "\xF0\x9F\x87\xB5\xF0\x9F\x87\xB1",
        'PT' => "\xF0\x9F\x87\xB5\xF0\x9F\x87\xB9",
        'CZ' => "\xF0\x9F\x87\xA8\xF0\x9F\x87\xBF",
        'US' => "\xF0\x9F\x87\xBA\xF0\x9F\x87\xB8",
    );

    if (isset($known_flags[ $country_code ])) {
        return $known_flags[ $country_code ];
    }

    $emoji = '';

    for ($i = 0; $i < 2; $i++) {
        $emoji .= maca_menulist_utf8_chr(0x1F1E6 + ord($country_code[ $i ]) - ord('A'));
    }

    return $emoji !== '' ? $emoji : maca_menulist_utf8_chr(0x1F3F3) . maca_menulist_utf8_chr(0xFE0F);
}

/**
 * Regional flag emoji for a language code.
 *
 * @param string $code ISO 639-1 language code.
 * @return string
 */
function maca_menulist_get_flag_emoji_for_locale($code) {
    return maca_menulist_country_code_to_flag_emoji(maca_menulist_get_country_code_for_language($code));
}

/**
 * ISO 3166-1 alpha-2 code for a language slug.
 *
 * @param string $code ISO 639-1 language code.
 * @return string
 */
function maca_menulist_get_country_code_for_language($code) {
    $code = sanitize_key((string) $code);
    $country_map = array(
        'sv' => 'SE',
        'no' => 'NO',
        'nb' => 'NO',
        'nn' => 'NO',
        'da' => 'DK',
        'fi' => 'FI',
        'de' => 'DE',
        'fr' => 'FR',
        'es' => 'ES',
        'it' => 'IT',
        'nl' => 'NL',
        'pl' => 'PL',
        'pt' => 'PT',
        'cs' => 'CZ',
        'en' => 'GB',
    );

    if (isset($country_map[ $code ])) {
        return $country_map[ $code ];
    }

    $fallback = strtoupper(substr($code, 0, 2));

    return (strlen($fallback) === 2 && ctype_alpha($fallback)) ? $fallback : 'SE';
}

/**
 * Inline SVG flag icons (reliable on all hosts; no emoji font required).
 *
 * @param string $country_code ISO 3166-1 alpha-2 country code.
 * @return string
 */
function maca_menulist_get_flag_svg($country_code) {
    $country_code = strtoupper((string) $country_code);

    static $svgs = array(
        'SE' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 16" role="img" aria-hidden="true"><rect width="22" height="16" fill="#005293"/><rect x="6" width="2" height="16" fill="#fecb00"/><rect y="7" width="22" height="2" fill="#fecb00"/></svg>',
        'GB' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 30" role="img" aria-hidden="true"><rect width="60" height="30" fill="#012169"/><path stroke="#fff" stroke-width="6" d="M0,0 60 30M60,0 0 30"/><path stroke="#c8102e" stroke-width="4" d="M0,0 60 30M60,0 0 30"/><path stroke="#fff" stroke-width="10" d="M30,0v30M0,15h60"/><path stroke="#c8102e" stroke-width="6" d="M30,0v30M0,15h60"/></svg>',
        'NO' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 16" role="img" aria-hidden="true"><rect width="22" height="16" fill="#ba0c2f"/><rect x="6" width="4" height="16" fill="#fff"/><rect y="6" width="22" height="4" fill="#fff"/><rect x="7" width="2" height="16" fill="#00205b"/><rect y="7" width="22" height="2" fill="#00205b"/></svg>',
        'DK' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 16" role="img" aria-hidden="true"><rect width="22" height="16" fill="#c8102e"/><rect x="6" width="2" height="16" fill="#fff"/><rect y="7" width="22" height="2" fill="#fff"/></svg>',
        'FI' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 16" role="img" aria-hidden="true"><rect width="22" height="16" fill="#fff"/><rect x="6" width="2" height="16" fill="#003580"/><rect y="7" width="22" height="2" fill="#003580"/></svg>',
        'DE' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 16" role="img" aria-hidden="true"><rect width="22" height="16" fill="#ffce00"/><rect width="22" height="11" fill="#dd0000"/><rect width="22" height="5" fill="#000"/></svg>',
        'FR' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 16" role="img" aria-hidden="true"><rect width="22" height="16" fill="#ef4135"/><rect width="15" height="16" fill="#fff"/><rect width="8" height="16" fill="#0055a4"/></svg>',
        'ES' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 16" role="img" aria-hidden="true"><rect width="22" height="16" fill="#c60b1e"/><rect y="4" width="22" height="8" fill="#ffc400"/></svg>',
        'IT' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 16" role="img" aria-hidden="true"><rect width="22" height="16" fill="#ce2b37"/><rect width="15" height="16" fill="#fff"/><rect width="8" height="16" fill="#009246"/></svg>',
        'NL' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 16" role="img" aria-hidden="true"><rect width="22" height="16" fill="#21468b"/><rect width="22" height="11" fill="#fff"/><rect width="22" height="5" fill="#ae1c28"/></svg>',
        'PL' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 16" role="img" aria-hidden="true"><rect width="22" height="16" fill="#dc143c"/><rect width="22" height="8" fill="#fff"/></svg>',
        'PT' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 16" role="img" aria-hidden="true"><rect width="22" height="16" fill="#ff0000"/><rect width="9" height="16" fill="#006600"/></svg>',
        'CZ' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 16" role="img" aria-hidden="true"><rect width="22" height="16" fill="#d7141a"/><rect width="22" height="8" fill="#fff"/><path fill="#11457e" d="M0,0 11,8 0,16z"/></svg>',
        'US' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 16" role="img" aria-hidden="true"><rect width="22" height="16" fill="#b22234"/><g fill="#fff"><rect y="1" width="22" height="1"/><rect y="3" width="22" height="1"/><rect y="5" width="22" height="1"/><rect y="7" width="22" height="1"/><rect y="9" width="22" height="1"/><rect y="11" width="22" height="1"/><rect y="13" width="22" height="1"/></g><rect width="9" height="7" fill="#3c3b6e"/></svg>',
    );

    return isset($svgs[ $country_code ]) ? $svgs[ $country_code ] : '';
}

/**
 * Render a flag icon for the language switcher.
 *
 * @param string $country_code ISO 3166-1 alpha-2 country code.
 * @return string HTML markup.
 */
function maca_menulist_render_flag_icon($country_code) {
    $country_code = strtoupper((string) $country_code);
    $class = 'maca-lang-flag maca-lang-flag--' . sanitize_html_class(strtolower($country_code));
    $svg = maca_menulist_get_flag_svg($country_code);

    if ($svg !== '') {
        return '<span class="' . esc_attr($class) . '" aria-hidden="true">' . $svg . '</span>';
    }

    return '<span class="' . esc_attr($class) . ' maca-lang-flag--emoji" aria-hidden="true">' . maca_menulist_country_code_to_flag_emoji($country_code) . '</span>';
}

/**
 * URL to switch public menu language.
 *
 * @param string $lang local|en
 * @return string
 */
function maca_menulist_get_menu_language_switch_url($lang) {
    $lang = sanitize_key($lang);

    if (!in_array($lang, array('local', 'en'), true)) {
        return home_url('/');
    }

    return add_query_arg('maca_lang', $lang);
}

/**
 * Persist guest menu language from query string.
 */
function maca_menulist_init_menu_language() {
    if (
        is_admin()
        || !isset($_GET['maca_lang'])
        || !maca_menulist_bilingual_menus_available()
        || !maca_menulist_menu_has_language_choice()
    ) {
        return;
    }

    $lang = sanitize_key(wp_unslash($_GET['maca_lang']));

    if (!in_array($lang, array('local', 'en'), true)) {
        return;
    }

    $path = defined('COOKIEPATH') ? COOKIEPATH : '/';
    $domain = defined('COOKIE_DOMAIN') ? COOKIE_DOMAIN : '';

    setcookie(
        'maca_menu_lang',
        $lang,
        time() + YEAR_IN_SECONDS,
        $path,
        $domain,
        is_ssl(),
        true
    );

    $_COOKIE['maca_menu_lang'] = $lang;
}

/**
 * Render compact flag language switcher for public menus.
 *
 * @param array<string, string> $args {
 *     @type string $context Display context: inline, qr.
 * }
 */
function maca_menulist_render_menu_language_switcher($args = array()) {
    if (!maca_menulist_menu_language_switcher_enabled()) {
        return;
    }

    $args = wp_parse_args(
        is_array($args) ? $args : array(),
        array(
            'context' => 'inline',
        )
    );

    $use_local = maca_menulist_should_use_local_content();
    $local_code = maca_menulist_get_local_language_code();
    $local_label = maca_menulist_get_local_language_label();
    $local_country = maca_menulist_get_country_code_for_language($local_code);
    $local_url = maca_menulist_get_menu_language_switch_url('local');
    $en_url = maca_menulist_get_menu_language_switch_url('en');

    echo '<nav class="maca-menu-lang-switcher maca-menu-lang-switcher--' . esc_attr($args['context']) . '" aria-label="' . esc_attr__('Menu language', 'maca-restu-pro') . '">';

    echo '<a href="' . esc_url($local_url) . '" class="maca-lang-btn' . ($use_local ? ' is-active' : '') . '" title="' . esc_attr($local_label) . '" aria-label="' . esc_attr($local_label) . '"' . ($use_local ? ' aria-current="true"' : '') . '>';
    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Static SVG/emoji flag markup from helper.
    echo maca_menulist_render_flag_icon($local_country);
    echo '</a>';

    echo '<a href="' . esc_url($en_url) . '" class="maca-lang-btn' . (!$use_local ? ' is-active' : '') . '" title="' . esc_attr__('English', 'maca-restu-pro') . '" aria-label="' . esc_attr__('English', 'maca-restu-pro') . '"' . (!$use_local ? ' aria-current="true"' : '') . '>';
    // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Static SVG/emoji flag markup from helper.
    echo maca_menulist_render_flag_icon('GB');
    echo '</a>';

    echo '</nav>';
}

add_action('init', 'maca_menulist_init_menu_language', 10);

/**
 * Combine local and English for dual-language display (English first).
 *
 * @param string $local   Local-language value.
 * @param string $english English value.
 * @return string
 */
function maca_menulist_format_dual_language_text($local, $english) {
    $local = trim((string) $local);
    $english = trim((string) $english);

    if ($local !== '' && $english !== '' && $local !== $english) {
        return $english . ' / ' . $local;
    }

    if ($english !== '') {
        return $english;
    }

    return $local;
}

/**
 * Pick the appropriate bilingual string for frontend display.
 *
 * @param string $local   Local-language value (name, title, …).
 * @param string $english English value (name_en, title_en, …).
 * @return string
 */
function maca_menulist_get_bilingual_field($local, $english) {
    $local = trim((string) $local);
    $english = trim((string) $english);

    if (maca_menulist_dual_language_menu_enabled()) {
        return maca_menulist_format_dual_language_text($local, $english);
    }

    if (maca_menulist_should_use_local_content()) {
        return $local !== '' ? $local : $english;
    }

    return $english !== '' ? $english : $local;
}

/**
 * Read a bilingual field from a row object.
 *
 * @param object|null $object    Database row object.
 * @param string      $local_key Local field property name.
 * @param string      $en_key    English field property name.
 * @return string
 */
function maca_menulist_get_object_bilingual_field($object, $local_key, $en_key) {
    if (!is_object($object)) {
        return '';
    }

    $local = isset($object->{$local_key}) ? (string) $object->{$local_key} : '';
    $english = isset($object->{$en_key}) ? (string) $object->{$en_key} : '';

    return maca_menulist_get_bilingual_field($local, $english);
}

/**
 * Admin list label showing both languages when they differ.
 *
 * @param string $local   Local-language value.
 * @param string $english English value.
 * @return string
 */
function maca_menulist_get_admin_bilingual_label($local, $english) {
    $local = trim((string) $local);
    $english = trim((string) $english);

    if ($local !== '' && $english !== '' && $local !== $english) {
        return $local . ' / ' . $english;
    }

    if ($local !== '') {
        return $local;
    }

    return $english;
}

/**
 * Whether admin forms should show separate local-language fields.
 * English sites use the primary fields only; *_en fields are hidden.
 *
 * @return bool
 */
function maca_menulist_admin_show_local_content_fields() {
    return !maca_menulist_site_locale_is_english();
}

/**
 * Admin label for the primary content field.
 *
 * @param string $field_label Base field name, already translated.
 * @return string
 */
function maca_menulist_admin_primary_field_label($field_label) {
    if (maca_menulist_admin_show_local_content_fields()) {
        return maca_menulist_bilingual_field_label($field_label, false);
    }

    return $field_label;
}

/**
 * Admin list/table label for bilingual content rows.
 *
 * @param string $local   Local-language value.
 * @param string $english English value.
 * @return string
 */
function maca_menulist_get_admin_content_label($local, $english) {
    if (maca_menulist_admin_show_local_content_fields()) {
        return maca_menulist_get_admin_bilingual_label($local, $english);
    }

    $local = trim((string) $local);

    if ($local !== '') {
        return $local;
    }

    return trim((string) $english);
}

/**
 * Whether required bilingual admin content is missing.
 *
 * @param string $local   Local-language value.
 * @param string $english English value.
 * @return bool
 */
function maca_menulist_admin_content_field_missing($local, $english) {
    if (maca_menulist_admin_show_local_content_fields()) {
        return trim((string) $local) === '' && trim((string) $english) === '';
    }

    return trim((string) $local) === '';
}

/**
 * Build an admin form field label, e.g. "Title (Local language)".
 *
 * @param string $field_label Base field name, already translated.
 * @param bool   $english     True for English field, false for local.
 * @return string
 */
function maca_menulist_bilingual_field_label($field_label, $english = false) {
    if ($english) {
        /* translators: %s: field name, e.g. Title */
        return sprintf(__('%s (English)', 'maca-restu-pro'), $field_label);
    }

    return sprintf(
        /* translators: 1: field name, 2: local language label */
        __('%1$s (%2$s)', 'maca-restu-pro'),
        $field_label,
        maca_menulist_get_local_language_name()
    );
}

/**
 * Admin submenu slug => menu label and optional browser page title.
 *
 * @return array<string, array{menu: string, page?: string}>
 */
function maca_menulist_get_admin_submenu_translations() {
    maca_menulist_load_textdomain();

    return array(
        'maca-restu-dashboard' => array(
            'menu' => __('Översikt', 'maca-restu-pro'),
            'page' => __('Översikt', 'maca-restu-pro'),
        ),
        'maca-restu-onboarding' => array(
            'menu' => __('Kom igång', 'maca-restu-pro'),
            'page' => __('Kom igång', 'maca-restu-pro'),
        ),
        'maca-restu-pro' => array(
            'menu' => __('Kategorier', 'maca-restu-pro'),
            'page' => __('Menykategorier', 'maca-restu-pro'),
        ),
        'maca-restu-menus' => array(
            'menu' => __('Menyer', 'maca-restu-pro'),
            'page' => __('Menyfiler', 'maca-restu-pro'),
        ),
        'maca-restu-settings' => array(
            'menu' => __('Inställningar', 'maca-restu-pro'),
        ),
        'maca-restu-guide' => array(
            'menu' => __('Guide', 'maca-restu-pro'),
        ),
        'maca-restu-support' => array(
            'menu' => __('Support', 'maca-restu-pro'),
        ),
        'maca-restu-qr' => array(
            'menu' => __('QR-koder', 'maca-restu-pro'),
        ),
        'maca-restu-dish-categories' => array(
            'menu' => __('Menykategorier', 'maca-restu-pro'),
            'page' => __('Menykategorier', 'maca-restu-pro'),
        ),
        'maca-restu-dishes' => array(
            'menu' => __('Rätter', 'maca-restu-pro'),
        ),
        'maca-restu-group-import-backup' => array(
            'menu' => __('Import & säkerhetskopiering', 'maca-restu-pro'),
        ),
        'maca-restu-import-pdf' => array(
            'menu' => __('Importera från PDF', 'maca-restu-pro'),
            'page' => __('Importera rätter från PDF', 'maca-restu-pro'),
        ),
        'maca-restu-dish-csv' => array(
            'menu' => __('Importera/exportera CSV', 'maca-restu-pro'),
            'page' => __('Importera och exportera rätter (CSV)', 'maca-restu-pro'),
        ),
        'maca-restu-allergens' => array(
            'menu' => __('Allergener', 'maca-restu-pro'),
        ),
        'maca-restu-dish-stats' => array(
            'menu' => __('Rättstatistik', 'maca-restu-pro'),
            'page' => __('Rättstatistik', 'maca-restu-pro'),
        ),
        'maca-restu-orders' => array(
            'menu' => __('Beställningar', 'maca-restu-pro'),
            'page' => __('Beställningar', 'maca-restu-pro'),
        ),
        'maca-restu-personal' => array(
            'menu' => __('Personal', 'maca-restu-pro'),
            'page' => __('Personal', 'maca-restu-pro'),
        ),
        'maca-restu-waiters' => array(
            'menu' => __('Personal', 'maca-restu-pro'),
            'page' => __('Personal', 'maca-restu-pro'),
        ),
        'maca-restu-campaigns' => array(
            'menu' => __('Kampanjmenyer', 'maca-restu-pro'),
            'page' => __('Kampanjmenyer', 'maca-restu-pro'),
        ),
        'maca-restu-payments' => array(
            'menu' => __('Betalningar', 'maca-restu-pro'),
            'page' => __('Gästbetalningar', 'maca-restu-pro'),
        ),
        'maca-restu-payment-history' => array(
            'menu' => __('Betalningshistorik', 'maca-restu-pro'),
            'page' => __('Betalningshistorik', 'maca-restu-pro'),
        ),
        'maca-restu-bookings' => array(
            'menu' => __('Bordsbokningar', 'maca-restu-pro'),
        ),
        'maca-restu-site-chat' => array(
            'menu' => __('Chatt', 'maca-restu-pro'),
            'page' => __('Chatt', 'maca-restu-pro'),
        ),
        'maca-restu-backup' => array(
            'menu' => __('Säkerhetskopiering', 'maca-restu-pro'),
            'page' => __('Säkerhetskopiering och återställning', 'maca-restu-pro'),
        ),
        'maca-restu-legal' => array(
            'menu' => __('Villkor och integritet', 'maca-restu-pro'),
        ),
        'maca-restu-subscription' => array(
            'menu' => __('Prenumeration', 'maca-restu-pro'),
        ),
    );
}

/**
 * Ensure maca Restu admin submenu titles use the active locale.
 *
 * @return void
 */
function maca_menulist_apply_admin_submenu_translations() {
    global $submenu;

    if (!isset($submenu['maca-restu']) || !is_array($submenu['maca-restu'])) {
        return;
    }

    $labels = maca_menulist_get_admin_submenu_translations();

    foreach ($submenu['maca-restu'] as $index => $item) {
        if (!isset($item[2], $labels[ $item[2] ])) {
            continue;
        }

        $entry = $labels[ $item[2] ];
        $menu_label = $entry['menu'];

        if (strpos($item[2], 'group-') !== false) {
            $menu_label = '<span class="maca-menulist-submenu-heading maca-menulist-submenu-heading--toggle">' . esc_html($menu_label) . '</span>';
        }

        $submenu['maca-restu'][ $index ][0] = $menu_label;

        if (!empty($entry['page'])) {
            $submenu['maca-restu'][ $index ][3] = $entry['page'];
        }
    }
}

/**
 * Menu category display name.
 *
 * @param object|null $category Category row.
 * @return string
 */
function maca_menulist_get_category_display_name($category) {
    return maca_menulist_get_object_bilingual_field($category, 'name', 'name_en');
}

/**
 * Menu category display description.
 *
 * @param object|null $category Category row.
 * @return string
 */
function maca_menulist_get_category_display_description($category) {
    return maca_menulist_get_object_bilingual_field($category, 'description', 'description_en');
}

/**
 * Menu file display title.
 *
 * @param object|null $menu Menu row.
 * @return string
 */
function maca_menulist_get_menu_display_title($menu) {
    return maca_menulist_get_object_bilingual_field($menu, 'title', 'title_en');
}

/**
 * Dish category display name.
 *
 * @param object|null $category Dish category row.
 * @return string
 */
function maca_menulist_get_dish_category_display_name($category) {
    return maca_menulist_get_object_bilingual_field($category, 'name', 'name_en');
}

/**
 * Dish display title.
 *
 * @param object|null $dish Dish row.
 * @return string
 */
function maca_menulist_get_dish_display_title($dish) {
    return maca_menulist_get_object_bilingual_field($dish, 'title', 'title_en');
}

/**
 * Dish display description.
 *
 * @param object|null $dish Dish row.
 * @return string
 */
function maca_menulist_get_dish_display_description($dish) {
    return maca_menulist_get_object_bilingual_field($dish, 'description', 'description_en');
}

/**
 * Allergen display name (uses shared bilingual logic).
 *
 * @param object|null $allergen Allergen row.
 * @return string
 */
function maca_menulist_get_allergen_display_name($allergen) {
    return maca_menulist_get_object_bilingual_field($allergen, 'name', 'name_en');
}

/**
 * Admin allergen label (both languages when they differ).
 *
 * @param object|null $allergen Allergen row.
 * @return string
 */
function maca_menulist_get_allergen_admin_label($allergen) {
    if (!is_object($allergen)) {
        return '';
    }

    $local = isset($allergen->name) ? (string) $allergen->name : '';
    $english = isset($allergen->name_en) ? (string) $allergen->name_en : '';

    return maca_menulist_get_admin_bilingual_label($local, $english);
}

/**
 * Option key map for bilingual footer / print texts.
 *
 * @return array<string, array{local: string, en: string}>
 */
function maca_menulist_get_bilingual_option_keys() {
    return array(
        'allergy' => array(
            'local' => 'maca_menulist_menu_footer_allergy_text',
            'en' => 'maca_menulist_menu_footer_allergy_text_en',
        ),
        'price' => array(
            'local' => 'maca_menulist_menu_footer_price_text',
            'en' => 'maca_menulist_menu_footer_price_text_en',
        ),
        'age' => array(
            'local' => 'maca_menulist_menu_footer_age_text',
            'en' => 'maca_menulist_menu_footer_age_text_en',
        ),
        'print_title' => array(
            'local' => 'maca_menulist_menu_print_title',
            'en' => 'maca_menulist_menu_print_title_en',
        ),
        'website_menu_page_title' => array(
            'local' => 'maca_menulist_website_menu_page_title',
            'en' => 'maca_menulist_website_menu_page_title_en',
        ),
        'qr_menu_page_title' => array(
            'local' => 'maca_menulist_qr_menu_page_title',
            'en' => 'maca_menulist_qr_menu_page_title_en',
        ),
    );
}

/**
 * Stored bilingual option text with default fallback.
 *
 * @param string $key Footer key: allergy, price, age, print_title.
 * @return string
 */
function maca_menulist_get_bilingual_option_text($key) {
    $keys = maca_menulist_get_bilingual_option_keys();

    if (!isset($keys[$key])) {
        return '';
    }

    $local = get_option($keys[$key]['local'], '');
    $english = get_option($keys[$key]['en'], '');

    if (!is_string($local)) {
        $local = '';
    }
    if (!is_string($english)) {
        $english = '';
    }

    $local = trim($local);
    $english = trim($english);

    if ($local === '' && $english === '' && in_array($key, array('allergy', 'price', 'age'), true)) {
        return maca_menulist_get_menu_footer_default_text($key);
    }

    return maca_menulist_get_bilingual_field($local, $english);
}

/**
 * Menu page title from settings (one language at a time; never dual "EN / SV").
 *
 * @param string $key website_menu_page_title|qr_menu_page_title.
 * @return string
 */
function maca_menulist_get_menu_page_title_option_text($key) {
    $keys = maca_menulist_get_bilingual_option_keys();

    if (!isset($keys[ $key ])) {
        return '';
    }

    $local = get_option($keys[ $key ]['local'], '');
    $english = get_option($keys[ $key ]['en'], '');

    if (!is_string($local)) {
        $local = '';
    }
    if (!is_string($english)) {
        $english = '';
    }

    $local = trim($local);
    $english = trim($english);

    if (maca_menulist_should_use_local_content()) {
        return $local !== '' ? $local : $english;
    }

    return $english !== '' ? $english : $local;
}

/**
 * Ensure bilingual columns exist on content tables.
 */
function maca_menulist_db_ensure_bilingual_columns() {
    global $wpdb;

    static $ensured = false;

    if ($ensured) {
        return;
    }

    $columns = array(
        maca_menulist_db_categories_table() => array(
            'name_en' => "ADD COLUMN name_en varchar(255) DEFAULT NULL AFTER name",
            'description_en' => "ADD COLUMN description_en text DEFAULT NULL AFTER description",
        ),
        maca_menulist_db_menus_table() => array(
            'title_en' => "ADD COLUMN title_en varchar(255) DEFAULT NULL AFTER title",
        ),
        maca_menulist_db_dish_categories_table() => array(
            'name_en' => "ADD COLUMN name_en varchar(255) DEFAULT NULL AFTER name",
        ),
        maca_menulist_db_dishes_table() => array(
            'title_en' => "ADD COLUMN title_en varchar(255) DEFAULT NULL AFTER title",
            'description_en' => "ADD COLUMN description_en text DEFAULT NULL AFTER description",
        ),
    );

    foreach ($columns as $table => $defs) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $exists = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table));

        if ($exists !== $table) {
            continue;
        }

        foreach ($defs as $column => $alter_sql) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $has_column = $wpdb->get_var("SHOW COLUMNS FROM $table LIKE '$column'");

            if (!$has_column) {
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.SchemaChange
                $wpdb->query("ALTER TABLE $table $alter_sql");
            }
        }
    }

    $ensured = true;
}

/**
 * Build dynamic insert/update row for a table schema map.
 *
 * @param array<string, mixed> $data   Incoming data.
 * @param array<string, string> $schema Column => wpdb format.
 * @return array{0: array<string, mixed>, 1: array<int, string>}
 */
function maca_menulist_db_prepare_row($data, $schema) {
    $row = array();
    $formats = array();

    foreach ($schema as $key => $format) {
        if (array_key_exists($key, $data)) {
            $row[$key] = $data[$key];
            $formats[] = $format;
        }
    }

    return array($row, $formats);
}
