<?php
/**
 * Bundled guest UI translations (local language when guest chose site language).
 *
 * English msgids are used when the guest selects English on the menu switcher.
 * JSON files live in languages/guest/{code}.json.
 *
 * @package Maca_Menu_List
 */

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

/**
 * Staff-only UI strings: keep WordPress locale, not guest menu language.
 *
 * @return array<string, true>
 */
function maca_menulist_guest_staff_only_strings() {
    static $map = null;

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

    $strings = array(
        'Enter staff PIN',
        'PIN',
        'Show orders',
        'Incorrect PIN.',
        'Kitchen orders',
        'Waiter orders',
        'No new orders right now.',
        'No active orders right now.',
        'Mark as served',
        'Mark as handled',
        'Mark paid',
        'Guest left',
        'Take order',
        'Delivered to table',
        'Deliver to table',
        'Accept',
        'Start preparing',
        'Ready in…',
        'New orders',
        'In progress',
        'Ready',
        'Kitchen stats',
        'Kitchen time',
        'Average time',
        'Orders today',
        'Kitchen page is disabled.',
        'Waiter page is disabled.',
        'Could not update order.',
        'Invalid status change.',
        'Enter how many minutes until ready.',
        'Enter a valid number of minutes.',
    );

    $map = array_fill_keys($strings, true);

    return $map;
}

/**
 * Map site locale code to bundled guest JSON filename (without .json).
 *
 * @param string|null $code ISO 639-1 from maca_menulist_get_local_language_code().
 * @return string
 */
function maca_menulist_guest_translation_file_code($code = null) {
    if ($code === null) {
        $locale = strtolower(str_replace('-', '_', maca_menulist_get_site_locale()));

        if ($locale === 'nl_be') {
            return 'nl_BE';
        }

        if ($locale === 'fr_be') {
            return 'fr_BE';
        }

        $code = maca_menulist_get_local_language_code();
    }

    $code = sanitize_key($code);

    $map = array(
        'no' => 'nb',
        'nn' => 'nb',
        'nb' => 'nb',
        'nl_be' => 'nl_BE',
        'fr_be' => 'fr_BE',
    );

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

    return $code;
}

/**
 * Load one locale JSON catalog (cached per request).
 *
 * @param string|null $code File code without .json; defaults to site local language.
 * @return array<string, string>
 */
function maca_menulist_get_guest_translation_catalog($code = null) {
    static $cache = array();

    if ($code === null) {
        $code = maca_menulist_guest_translation_file_code();
    }

    $code = sanitize_key($code);

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

    $cache[ $code ] = array();
    $path           = MACA_MENULIST_PLUGIN_DIR . 'languages/guest/' . $code . '.json';

    if (!is_readable($path)) {
        return $cache[ $code ];
    }

    $raw = file_get_contents($path);

    if ($raw === false) {
        return $cache[ $code ];
    }

    $decoded = json_decode($raw, true);

    if (is_array($decoded)) {
        $cache[ $code ] = $decoded;
    }

    return $cache[ $code ];
}

/**
 * @return array<string, array<string, string>>
 */
function maca_menulist_get_guest_translation_catalogs() {
    static $catalogs = null;

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

    $catalogs = array();
    $dir      = MACA_MENULIST_PLUGIN_DIR . 'languages/guest/';

    if (!is_dir($dir)) {
        return $catalogs;
    }

    foreach (glob($dir . '*.json') ?: array() as $path) {
        $code = sanitize_key(pathinfo($path, PATHINFO_FILENAME));

        $catalogs[ $code ] = maca_menulist_get_guest_translation_catalog($code);
    }

    return $catalogs;
}

/**
 * WordPress .po fallback without re-entering guest gettext filters (avoids infinite recursion / 503).
 *
 * @param string $msgid English message id.
 * @return string
 */
function maca_menulist_translate_without_guest_filter($msgid) {
    static $depth = 0;

    if ($depth > 0) {
        return $msgid;
    }

    $depth++;

    remove_filter('gettext_maca-restu', 'maca_menulist_filter_guest_gettext', 20);
    remove_filter('ngettext_maca-restu', 'maca_menulist_filter_guest_ngettext', 20);
    remove_filter('gettext_with_context_maca-restu', 'maca_menulist_filter_guest_gettext_with_context', 20);

    // phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText -- Dynamic msgid from guest catalog lookup by design.
    $text = __($msgid, 'maca-restu-pro');

    add_filter('gettext_maca-restu', 'maca_menulist_filter_guest_gettext', 20, 3);
    add_filter('ngettext_maca-restu', 'maca_menulist_filter_guest_ngettext', 20, 5);
    add_filter('gettext_with_context_maca-restu', 'maca_menulist_filter_guest_gettext_with_context', 20, 4);

    $depth--;

    return $text;
}

/**
 * Look up a bundled translation for the site local language.
 *
 * @param string $msgid English message id.
 * @return string|null Null if not in catalog.
 */
function maca_menulist_lookup_guest_catalog_string($msgid) {
    $file_code = maca_menulist_guest_translation_file_code();
    $catalog   = maca_menulist_get_guest_translation_catalog($file_code);

    if (!isset($catalog[ $msgid ])) {
        return null;
    }

    $value = $catalog[ $msgid ];

    if (!is_string($value) || $value === '') {
        return null;
    }

    // Untranslated placeholder in JSON (msgid copied as value) — fall back to .po / overrides.
    if ($value === $msgid) {
        return null;
    }

    /**
     * Filter bundled guest UI translation.
     *
     * @param string $value  Translated string.
     * @param string $msgid  English message id.
     * @param string $code   Catalog language file code.
     */
    return apply_filters('maca_menulist_guest_catalog_string', $value, $msgid, $file_code);
}

/**
 * Whether gettext should follow guest menu language + bundled catalog.
 *
 * @return bool
 */
function maca_menulist_should_apply_guest_gettext_filter() {
    if (defined('MACA_MENULIST_STAFF_API_REQUEST') && MACA_MENULIST_STAFF_API_REQUEST) {
        return false;
    }

    if (defined('MACA_MENULIST_STAFF_PAGE_REQUEST') && MACA_MENULIST_STAFF_PAGE_REQUEST) {
        return false;
    }

    if (function_exists('maca_menulist_is_staff_api_request') && maca_menulist_is_staff_api_request()) {
        return false;
    }

    if (function_exists('maca_menulist_is_staff_orders_request') && maca_menulist_is_staff_orders_request()) {
        return false;
    }

    if (is_admin() && !wp_doing_ajax()) {
        return false;
    }

    if (wp_doing_ajax()) {
        $action = isset($_REQUEST['action']) ? sanitize_key((string) wp_unslash($_REQUEST['action'])) : '';

        if (function_exists('maca_menulist_get_staff_api_actions')
            && in_array($action, maca_menulist_get_staff_api_actions(), true)) {
            return false;
        }

        // All plugin AJAX handlers use __() or maca_menulist_guest_ui_string() directly.
        if (strpos($action, 'maca_') === 0) {
            return false;
        }

        if (strpos($action, 'maca_menulist_') === 0 && strpos($action, 'maca_menulist_activate') !== 0) {
            return false;
        }
    }

    return true;
}

/**
 * Resolve a guest-facing string for the current menu language preference.
 *
 * @param string $msgid English message id.
 * @return string
 */
function maca_menulist_resolve_guest_ui_string($msgid) {
    return maca_menulist_resolve_guest_string($msgid, maca_menulist_should_use_local_content());
}

/**
 * Filter plugin gettext on guest-facing requests.
 *
 * @param string $translated Translated or fallback string.
 * @param string $text       Message id.
 * @param string $domain     Text domain.
 * @return string
 */
function maca_menulist_filter_guest_gettext($translated, $text, $domain) {
    static $depth = 0;

    if ($depth > 0) {
        return $translated;
    }

    if ($domain !== 'maca-restu-pro' || !maca_menulist_should_apply_guest_gettext_filter()) {
        return $translated;
    }

    $staff_only = maca_menulist_guest_staff_only_strings();

    if (isset($staff_only[ $text ])) {
        return $translated;
    }

    $depth++;
    $result = maca_menulist_resolve_guest_string($text, maca_menulist_should_use_local_content());
    $depth--;

    return $result;
}

/**
 * @param string $translated Translated string.
 * @param string $single     Singular msgid.
 * @param string $plural     Plural msgid.
 * @param int    $number     Count.
 * @param string $domain     Text domain.
 * @return string
 */
function maca_menulist_filter_guest_ngettext($translated, $single, $plural, $number, $domain) {
    static $depth = 0;

    if ($depth > 0) {
        return $translated;
    }

    if ($domain !== 'maca-restu-pro' || !maca_menulist_should_apply_guest_gettext_filter()) {
        return $translated;
    }

    $staff_only = maca_menulist_guest_staff_only_strings();

    if (isset($staff_only[ $single ]) || isset($staff_only[ $plural ])) {
        return $translated;
    }

    $pick = ($number === 1) ? $single : $plural;

    $depth++;
    $result = maca_menulist_resolve_guest_string($pick, maca_menulist_should_use_local_content());
    $depth--;

    return $result;
}

/**
 * @param string $translated Translated string.
 * @param string $text       Message id.
 * @param string $context    Context.
 * @param string $domain     Text domain.
 * @return string
 */
function maca_menulist_filter_guest_gettext_with_context($translated, $text, $context, $domain) {
    static $depth = 0;

    if ($depth > 0) {
        return $translated;
    }

    if ($domain !== 'maca-restu-pro' || !maca_menulist_should_apply_guest_gettext_filter()) {
        return $translated;
    }

    $staff_only = maca_menulist_guest_staff_only_strings();

    if (isset($staff_only[ $text ])) {
        return $translated;
    }

    $depth++;
    $result = maca_menulist_resolve_guest_string($text, maca_menulist_should_use_local_content());
    $depth--;

    return $result;
}

add_filter('gettext_maca-restu', 'maca_menulist_filter_guest_gettext', 20, 3);
add_filter('ngettext_maca-restu', 'maca_menulist_filter_guest_ngettext', 20, 5);
add_filter('gettext_with_context_maca-restu', 'maca_menulist_filter_guest_gettext_with_context', 20, 4);
